@vkontakte/videoplayer-core 2.0.136-dev.d878e150.0 → 2.0.136-dev.e1130126.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,85 +1,85 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.136-dev.d878e150.0
3
- * Mon, 14 Jul 2025 08:47:23 GMT
2
+ * @vkontakte/videoplayer-core v2.0.136-dev.e1130126.0
3
+ * Thu, 17 Jul 2025 12:59:44 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-136/doc/
5
5
  */
6
- var OE=Object.create;var Bp=Object.defineProperty;var FE=Object.getOwnPropertyDescriptor;var NE=Object.getOwnPropertyNames;var UE=Object.getPrototypeOf,qE=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var jE=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of NE(e))!qE.call(a,r)&&r!==t&&Bp(a,r,{get:()=>e[r],enumerable:!(i=FE(e,r))||i.enumerable});return a};var N=(a,e,t)=>(t=a!=null?OE(UE(a)):{},jE(e||!a||!a.__esModule?Bp(t,"default",{value:a,enumerable:!0}):t,a));var oe=b((hu,_p)=>{"use strict";var Wr=function(a){return a&&a.Math===Math&&a};_p.exports=Wr(typeof globalThis=="object"&&globalThis)||Wr(typeof window=="object"&&window)||Wr(typeof self=="object"&&self)||Wr(typeof global=="object"&&global)||Wr(typeof hu=="object"&&hu)||function(){return this}()||Function("return this")()});var pe=b((UV,Op)=>{"use strict";Op.exports=function(a){try{return!!a()}catch(e){return!0}}});var zr=b((qV,Fp)=>{"use strict";var HE=pe();Fp.exports=!HE(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var fu=b((jV,jp)=>{"use strict";var QE=zr(),qp=Function.prototype,Np=qp.apply,Up=qp.call;jp.exports=typeof Reflect=="object"&&Reflect.apply||(QE?Up.bind(Np):function(){return Up.apply(Np,arguments)})});var he=b((HV,Gp)=>{"use strict";var Hp=zr(),Qp=Function.prototype,mu=Qp.call,GE=Hp&&Qp.bind.bind(mu,mu);Gp.exports=Hp?GE:function(a){return function(){return mu.apply(a,arguments)}}});var hi=b((QV,zp)=>{"use strict";var Wp=he(),WE=Wp({}.toString),zE=Wp("".slice);zp.exports=function(a){return zE(WE(a),8,-1)}});var bu=b((GV,Yp)=>{"use strict";var YE=hi(),KE=he();Yp.exports=function(a){if(YE(a)==="Function")return KE(a)}});var ue=b((WV,Kp)=>{"use strict";var gu=typeof document=="object"&&document.all;Kp.exports=typeof gu=="undefined"&&gu!==void 0?function(a){return typeof a=="function"||a===gu}:function(a){return typeof a=="function"}});var Ue=b((zV,Xp)=>{"use strict";var XE=pe();Xp.exports=!XE(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var qe=b((YV,Jp)=>{"use strict";var JE=zr(),Xs=Function.prototype.call;Jp.exports=JE?Xs.bind(Xs):function(){return Xs.apply(Xs,arguments)}});var Su=b(th=>{"use strict";var Zp={}.propertyIsEnumerable,eh=Object.getOwnPropertyDescriptor,ZE=eh&&!Zp.call({1:2},1);th.f=ZE?function(e){var t=eh(this,e);return!!t&&t.enumerable}:Zp});var Yr=b((XV,ih)=>{"use strict";ih.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var ah=b((JV,rh)=>{"use strict";var ex=he(),tx=pe(),ix=hi(),vu=Object,rx=ex("".split);rh.exports=tx(function(){return!vu("z").propertyIsEnumerable(0)})?function(a){return ix(a)==="String"?rx(a,""):vu(a)}:vu});var Kr=b((ZV,sh)=>{"use strict";sh.exports=function(a){return a==null}});var Qt=b((e_,nh)=>{"use strict";var ax=Kr(),sx=TypeError;nh.exports=function(a){if(ax(a))throw new sx("Can't call method on "+a);return a}});var fi=b((t_,oh)=>{"use strict";var nx=ah(),ox=Qt();oh.exports=function(a){return nx(ox(a))}});var $e=b((i_,uh)=>{"use strict";var ux=ue();uh.exports=function(a){return typeof a=="object"?a!==null:ux(a)}});var mi=b((r_,lh)=>{"use strict";lh.exports={}});var Pt=b((a_,dh)=>{"use strict";var yu=mi(),Tu=oe(),lx=ue(),ch=function(a){return lx(a)?a:void 0};dh.exports=function(a,e){return arguments.length<2?ch(yu[a])||ch(Tu[a]):yu[a]&&yu[a][e]||Tu[a]&&Tu[a][e]}});var Xr=b((s_,ph)=>{"use strict";var cx=he();ph.exports=cx({}.isPrototypeOf)});var bi=b((n_,mh)=>{"use strict";var dx=oe(),hh=dx.navigator,fh=hh&&hh.userAgent;mh.exports=fh?String(fh):""});var Eu=b((o_,Th)=>{"use strict";var yh=oe(),Iu=bi(),bh=yh.process,gh=yh.Deno,Sh=bh&&bh.versions||gh&&gh.version,vh=Sh&&Sh.v8,rt,Js;vh&&(rt=vh.split("."),Js=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!Js&&Iu&&(rt=Iu.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=Iu.match(/Chrome\/(\d+)/),rt&&(Js=+rt[1])));Th.exports=Js});var xu=b((u_,Eh)=>{"use strict";var Ih=Eu(),px=pe(),hx=oe(),fx=hx.String;Eh.exports=!!Object.getOwnPropertySymbols&&!px(function(){var a=Symbol("symbol detection");return!fx(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Ih&&Ih<41})});var wu=b((l_,xh)=>{"use strict";var mx=xu();xh.exports=mx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Au=b((c_,wh)=>{"use strict";var bx=Pt(),gx=ue(),Sx=Xr(),vx=wu(),yx=Object;wh.exports=vx?function(a){return typeof a=="symbol"}:function(a){var e=bx("Symbol");return gx(e)&&Sx(e.prototype,yx(a))}});var Jr=b((d_,Ah)=>{"use strict";var Tx=String;Ah.exports=function(a){try{return Tx(a)}catch(e){return"Object"}}});var ht=b((p_,Ph)=>{"use strict";var Ix=ue(),Ex=Jr(),xx=TypeError;Ph.exports=function(a){if(Ix(a))return a;throw new xx(Ex(a)+" is not a function")}});var Zr=b((h_,kh)=>{"use strict";var wx=ht(),Ax=Kr();kh.exports=function(a,e){var t=a[e];return Ax(t)?void 0:wx(t)}});var Lh=b((f_,Rh)=>{"use strict";var Pu=qe(),ku=ue(),Ru=$e(),Px=TypeError;Rh.exports=function(a,e){var t,i;if(e==="string"&&ku(t=a.toString)&&!Ru(i=Pu(t,a))||ku(t=a.valueOf)&&!Ru(i=Pu(t,a))||e!=="string"&&ku(t=a.toString)&&!Ru(i=Pu(t,a)))return i;throw new Px("Can't convert object to primitive value")}});var at=b((m_,$h)=>{"use strict";$h.exports=!0});var Ch=b((b_,Dh)=>{"use strict";var Mh=oe(),kx=Object.defineProperty;Dh.exports=function(a,e){try{kx(Mh,a,{value:e,configurable:!0,writable:!0})}catch(t){Mh[a]=e}return e}});var ea=b((g_,_h)=>{"use strict";var Rx=at(),Lx=oe(),$x=Ch(),Bh="__core-js_shared__",Vh=_h.exports=Lx[Bh]||$x(Bh,{});(Vh.versions||(Vh.versions=[])).push({version:"3.43.0",mode:Rx?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Lu=b((S_,Fh)=>{"use strict";var Oh=ea();Fh.exports=function(a,e){return Oh[a]||(Oh[a]=e||{})}});var Wi=b((v_,Nh)=>{"use strict";var Mx=Qt(),Dx=Object;Nh.exports=function(a){return Dx(Mx(a))}});var st=b((y_,Uh)=>{"use strict";var Cx=he(),Bx=Wi(),Vx=Cx({}.hasOwnProperty);Uh.exports=Object.hasOwn||function(e,t){return Vx(Bx(e),t)}});var $u=b((T_,qh)=>{"use strict";var _x=he(),Ox=0,Fx=Math.random(),Nx=_x(1.1.toString);qh.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Nx(++Ox+Fx,36)}});var ye=b((I_,Hh)=>{"use strict";var Ux=oe(),qx=Lu(),jh=st(),jx=$u(),Hx=xu(),Qx=wu(),zi=Ux.Symbol,Mu=qx("wks"),Gx=Qx?zi.for||zi:zi&&zi.withoutSetter||jx;Hh.exports=function(a){return jh(Mu,a)||(Mu[a]=Hx&&jh(zi,a)?zi[a]:Gx("Symbol."+a)),Mu[a]}});var zh=b((E_,Wh)=>{"use strict";var Wx=qe(),Qh=$e(),Gh=Au(),zx=Zr(),Yx=Lh(),Kx=ye(),Xx=TypeError,Jx=Kx("toPrimitive");Wh.exports=function(a,e){if(!Qh(a)||Gh(a))return a;var t=zx(a,Jx),i;if(t){if(e===void 0&&(e="default"),i=Wx(t,a,e),!Qh(i)||Gh(i))return i;throw new Xx("Can't convert object to primitive value")}return e===void 0&&(e="number"),Yx(a,e)}});var Du=b((x_,Yh)=>{"use strict";var Zx=zh(),ew=Au();Yh.exports=function(a){var e=Zx(a,"string");return ew(e)?e:e+""}});var Zs=b((w_,Xh)=>{"use strict";var tw=oe(),Kh=$e(),Cu=tw.document,iw=Kh(Cu)&&Kh(Cu.createElement);Xh.exports=function(a){return iw?Cu.createElement(a):{}}});var Bu=b((A_,Jh)=>{"use strict";var rw=Ue(),aw=pe(),sw=Zs();Jh.exports=!rw&&!aw(function(){return Object.defineProperty(sw("div"),"a",{get:function(){return 7}}).a!==7})});var tf=b(ef=>{"use strict";var nw=Ue(),ow=qe(),uw=Su(),lw=Yr(),cw=fi(),dw=Du(),pw=st(),hw=Bu(),Zh=Object.getOwnPropertyDescriptor;ef.f=nw?Zh:function(e,t){if(e=cw(e),t=dw(t),hw)try{return Zh(e,t)}catch(i){}if(pw(e,t))return lw(!ow(uw.f,e,t),e[t])}});var Vu=b((k_,rf)=>{"use strict";var fw=pe(),mw=ue(),bw=/#|\.prototype\./,ta=function(a,e){var t=Sw[gw(a)];return t===yw?!0:t===vw?!1:mw(e)?fw(e):!!e},gw=ta.normalize=function(a){return String(a).replace(bw,".").toLowerCase()},Sw=ta.data={},vw=ta.NATIVE="N",yw=ta.POLYFILL="P";rf.exports=ta});var Yi=b((R_,sf)=>{"use strict";var af=bu(),Tw=ht(),Iw=zr(),Ew=af(af.bind);sf.exports=function(a,e){return Tw(a),e===void 0?a:Iw?Ew(a,e):function(){return a.apply(e,arguments)}}});var _u=b((L_,nf)=>{"use strict";var xw=Ue(),ww=pe();nf.exports=xw&&ww(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ft=b(($_,of)=>{"use strict";var Aw=$e(),Pw=String,kw=TypeError;of.exports=function(a){if(Aw(a))return a;throw new kw(Pw(a)+" is not an object")}});var gi=b(lf=>{"use strict";var Rw=Ue(),Lw=Bu(),$w=_u(),en=ft(),uf=Du(),Mw=TypeError,Ou=Object.defineProperty,Dw=Object.getOwnPropertyDescriptor,Fu="enumerable",Nu="configurable",Uu="writable";lf.f=Rw?$w?function(e,t,i){if(en(e),t=uf(t),en(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Uu in i&&!i[Uu]){var r=Dw(e,t);r&&r[Uu]&&(e[t]=i.value,i={configurable:Nu in i?i[Nu]:r[Nu],enumerable:Fu in i?i[Fu]:r[Fu],writable:!1})}return Ou(e,t,i)}:Ou:function(e,t,i){if(en(e),t=uf(t),en(i),Lw)try{return Ou(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Mw("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ki=b((D_,cf)=>{"use strict";var Cw=Ue(),Bw=gi(),Vw=Yr();cf.exports=Cw?function(a,e,t){return Bw.f(a,e,Vw(1,t))}:function(a,e,t){return a[e]=t,a}});var de=b((C_,pf)=>{"use strict";var ia=oe(),_w=fu(),Ow=bu(),Fw=ue(),Nw=tf().f,Uw=Vu(),Xi=mi(),qw=Yi(),Ji=Ki(),df=st();ea();var jw=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return _w(a,this,arguments)};return e.prototype=a.prototype,e};pf.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?ia:r?ia[t]:ia[t]&&ia[t].prototype,o=i?Xi:Xi[t]||Ji(Xi,t,{})[t],u=o.prototype,l,d,c,f,p,h,m,g,S;for(f in e)l=Uw(i?f:t+(r?".":"#")+f,a.forced),d=!l&&n&&df(n,f),h=o[f],d&&(a.dontCallGetSet?(S=Nw(n,f),m=S&&S.value):m=n[f]),p=d&&m?m:e[f],!(!l&&!s&&typeof h==typeof p)&&(a.bind&&d?g=qw(p,ia):a.wrap&&d?g=jw(p):s&&Fw(p)?g=Ow(p):g=p,(a.sham||p&&p.sham||h&&h.sham)&&Ji(g,"sham",!0),Ji(o,f,g),s&&(c=t+"Prototype",df(Xi,c)||Ji(Xi,c,{}),Ji(Xi[c],f,p),a.real&&u&&(l||!u[f])&&Ji(u,f,p)))}});var ff=b((B_,hf)=>{"use strict";var Hw=Math.ceil,Qw=Math.floor;hf.exports=Math.trunc||function(e){var t=+e;return(t>0?Qw:Hw)(t)}});var ra=b((V_,mf)=>{"use strict";var Gw=ff();mf.exports=function(a){var e=+a;return e!==e||e===0?0:Gw(e)}});var gf=b((__,bf)=>{"use strict";var Ww=ra(),zw=Math.max,Yw=Math.min;bf.exports=function(a,e){var t=Ww(a);return t<0?zw(t+e,0):Yw(t,e)}});var qu=b((O_,Sf)=>{"use strict";var Kw=ra(),Xw=Math.min;Sf.exports=function(a){var e=Kw(a);return e>0?Xw(e,9007199254740991):0}});var Zi=b((F_,vf)=>{"use strict";var Jw=qu();vf.exports=function(a){return Jw(a.length)}});var ju=b((N_,Tf)=>{"use strict";var Zw=fi(),eA=gf(),tA=Zi(),yf=function(a){return function(e,t,i){var r=Zw(e),s=tA(r);if(s===0)return!a&&-1;var n=eA(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Tf.exports={includes:yf(!0),indexOf:yf(!1)}});var aa=b((U_,If)=>{"use strict";If.exports=function(){}});var Ef=b(()=>{"use strict";var iA=de(),rA=ju().includes,aA=pe(),sA=aa(),nA=aA(function(){return!Array(1).includes()});iA({target:"Array",proto:!0,forced:nA},{includes:function(e){return rA(this,e,arguments.length>1?arguments[1]:void 0)}});sA("includes")});var Gt=b((H_,xf)=>{"use strict";var oA=Pt();xf.exports=oA});var Af=b((Q_,wf)=>{"use strict";Ef();var uA=Gt();wf.exports=uA("Array","includes")});var kf=b((G_,Pf)=>{"use strict";var lA=Af();Pf.exports=lA});var Ye=b((W_,Rf)=>{"use strict";var cA=kf();Rf.exports=cA});var an=b((sO,_f)=>{"use strict";var SA=Lu(),vA=$u(),Vf=SA("keys");_f.exports=function(a){return Vf[a]||(Vf[a]=vA(a))}});var Ff=b((nO,Of)=>{"use strict";var yA=pe();Of.exports=!yA(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var sn=b((oO,Uf)=>{"use strict";var TA=st(),IA=ue(),EA=Wi(),xA=an(),wA=Ff(),Nf=xA("IE_PROTO"),Gu=Object,AA=Gu.prototype;Uf.exports=wA?Gu.getPrototypeOf:function(a){var e=EA(a);if(TA(e,Nf))return e[Nf];var t=e.constructor;return IA(t)&&e instanceof t?t.prototype:e instanceof Gu?AA:null}});var nn=b((uO,qf)=>{"use strict";qf.exports={}});var Qf=b((lO,Hf)=>{"use strict";var PA=he(),Wu=st(),kA=fi(),RA=ju().indexOf,LA=nn(),jf=PA([].push);Hf.exports=function(a,e){var t=kA(a),i=0,r=[],s;for(s in t)!Wu(LA,s)&&Wu(t,s)&&jf(r,s);for(;e.length>i;)Wu(t,s=e[i++])&&(~RA(r,s)||jf(r,s));return r}});var zu=b((cO,Gf)=>{"use strict";Gf.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Yu=b((dO,Wf)=>{"use strict";var $A=Qf(),MA=zu();Wf.exports=Object.keys||function(e){return $A(e,MA)}});var Ku=b((pO,Jf)=>{"use strict";var Yf=Ue(),DA=pe(),Kf=he(),CA=sn(),BA=Yu(),VA=fi(),_A=Su().f,Xf=Kf(_A),OA=Kf([].push),FA=Yf&&DA(function(){var a=Object.create(null);return a[2]=2,!Xf(a,2)}),zf=function(a){return function(e){for(var t=VA(e),i=BA(t),r=FA&&CA(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Yf||(r?u in t:Xf(t,u)))&&OA(o,a?[u,t[u]]:t[u]);return o}};Jf.exports={entries:zf(!0),values:zf(!1)}});var Zf=b(()=>{"use strict";var NA=de(),UA=Ku().entries;NA({target:"Object",stat:!0},{entries:function(e){return UA(e)}})});var tm=b((mO,em)=>{"use strict";Zf();var qA=mi();em.exports=qA.Object.entries});var rm=b((bO,im)=>{"use strict";var jA=tm();im.exports=jA});var er=b((gO,am)=>{"use strict";var HA=rm();am.exports=HA});var Si=b((SO,sm)=>{"use strict";sm.exports={}});var um=b((vO,om)=>{"use strict";var QA=oe(),GA=ue(),nm=QA.WeakMap;om.exports=GA(nm)&&/native code/.test(String(nm))});var el=b((yO,dm)=>{"use strict";var WA=um(),cm=oe(),zA=$e(),YA=Ki(),Xu=st(),Ju=ea(),KA=an(),XA=nn(),lm="Object already initialized",Zu=cm.TypeError,JA=cm.WeakMap,on,sa,un,ZA=function(a){return un(a)?sa(a):on(a,{})},eP=function(a){return function(e){var t;if(!zA(e)||(t=sa(e)).type!==a)throw new Zu("Incompatible receiver, "+a+" required");return t}};WA||Ju.state?(nt=Ju.state||(Ju.state=new JA),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,on=function(a,e){if(nt.has(a))throw new Zu(lm);return e.facade=a,nt.set(a,e),e},sa=function(a){return nt.get(a)||{}},un=function(a){return nt.has(a)}):(vi=KA("state"),XA[vi]=!0,on=function(a,e){if(Xu(a,vi))throw new Zu(lm);return e.facade=a,YA(a,vi,e),e},sa=function(a){return Xu(a,vi)?a[vi]:{}},un=function(a){return Xu(a,vi)});var nt,vi;dm.exports={set:on,get:sa,has:un,enforce:ZA,getterFor:eP}});var rl=b((TO,hm)=>{"use strict";var tl=Ue(),tP=st(),pm=Function.prototype,iP=tl&&Object.getOwnPropertyDescriptor,il=tP(pm,"name"),rP=il&&function(){}.name==="something",aP=il&&(!tl||tl&&iP(pm,"name").configurable);hm.exports={EXISTS:il,PROPER:rP,CONFIGURABLE:aP}});var mm=b(fm=>{"use strict";var sP=Ue(),nP=_u(),oP=gi(),uP=ft(),lP=fi(),cP=Yu();fm.f=sP&&!nP?Object.defineProperties:function(e,t){uP(e);for(var i=lP(t),r=cP(t),s=r.length,n=0,o;s>n;)oP.f(e,o=r[n++],i[o]);return e}});var al=b((EO,bm)=>{"use strict";var dP=Pt();bm.exports=dP("document","documentElement")});var ul=b((xO,Em)=>{"use strict";var pP=ft(),hP=mm(),gm=zu(),fP=nn(),mP=al(),bP=Zs(),gP=an(),Sm=">",vm="<",nl="prototype",ol="script",Tm=gP("IE_PROTO"),sl=function(){},Im=function(a){return vm+ol+Sm+a+vm+"/"+ol+Sm},ym=function(a){a.write(Im("")),a.close();var e=a.parentWindow.Object;return a=null,e},SP=function(){var a=bP("iframe"),e="java"+ol+":",t;return a.style.display="none",mP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Im("document.F=Object")),t.close(),t.F},ln,cn=function(){try{ln=new ActiveXObject("htmlfile")}catch(e){}cn=typeof document!="undefined"?document.domain&&ln?ym(ln):SP():ym(ln);for(var a=gm.length;a--;)delete cn[nl][gm[a]];return cn()};fP[Tm]=!0;Em.exports=Object.create||function(e,t){var i;return e!==null?(sl[nl]=pP(e),i=new sl,sl[nl]=null,i[Tm]=e):i=cn(),t===void 0?i:hP.f(i,t)}});var tr=b((wO,xm)=>{"use strict";var vP=Ki();xm.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:vP(a,e,t),a}});var pl=b((AO,Pm)=>{"use strict";var yP=pe(),TP=ue(),IP=$e(),EP=ul(),wm=sn(),xP=tr(),wP=ye(),AP=at(),dl=wP("iterator"),Am=!1,kt,ll,cl;[].keys&&(cl=[].keys(),"next"in cl?(ll=wm(wm(cl)),ll!==Object.prototype&&(kt=ll)):Am=!0);var PP=!IP(kt)||yP(function(){var a={};return kt[dl].call(a)!==a});PP?kt={}:AP&&(kt=EP(kt));TP(kt[dl])||xP(kt,dl,function(){return this});Pm.exports={IteratorPrototype:kt,BUGGY_SAFARI_ITERATORS:Am}});var dn=b((PO,Rm)=>{"use strict";var kP=ye(),RP=kP("toStringTag"),km={};km[RP]="z";Rm.exports=String(km)==="[object z]"});var na=b((kO,Lm)=>{"use strict";var LP=dn(),$P=ue(),pn=hi(),MP=ye(),DP=MP("toStringTag"),CP=Object,BP=pn(function(){return arguments}())==="Arguments",VP=function(a,e){try{return a[e]}catch(t){}};Lm.exports=LP?pn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=VP(e=CP(a),DP))=="string"?t:BP?pn(e):(i=pn(e))==="Object"&&$P(e.callee)?"Arguments":i}});var Mm=b((RO,$m)=>{"use strict";var _P=dn(),OP=na();$m.exports=_P?{}.toString:function(){return"[object "+OP(this)+"]"}});var oa=b((LO,Cm)=>{"use strict";var FP=dn(),NP=gi().f,UP=Ki(),qP=st(),jP=Mm(),HP=ye(),Dm=HP("toStringTag");Cm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(qP(r,Dm)||NP(r,Dm,{configurable:!0,value:e}),i&&!FP&&UP(r,"toString",jP))}});var Vm=b(($O,Bm)=>{"use strict";var QP=pl().IteratorPrototype,GP=ul(),WP=Yr(),zP=oa(),YP=Si(),KP=function(){return this};Bm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=GP(QP,{next:WP(+!i,t)}),zP(a,r,!1,!0),YP[r]=KP,a}});var Om=b((MO,_m)=>{"use strict";var XP=he(),JP=ht();_m.exports=function(a,e,t){try{return XP(JP(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Nm=b((DO,Fm)=>{"use strict";var ZP=$e();Fm.exports=function(a){return ZP(a)||a===null}});var qm=b((CO,Um)=>{"use strict";var ek=Nm(),tk=String,ik=TypeError;Um.exports=function(a){if(ek(a))return a;throw new ik("Can't set "+tk(a)+" as a prototype")}});var hl=b((BO,jm)=>{"use strict";var rk=Om(),ak=$e(),sk=Qt(),nk=qm();jm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=rk(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return sk(r),nk(s),ak(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var eb=b((VO,Zm)=>{"use strict";var ok=de(),uk=qe(),hn=at(),Xm=rl(),lk=ue(),ck=Vm(),Hm=sn(),Qm=hl(),dk=oa(),pk=Ki(),fl=tr(),hk=ye(),Gm=Si(),Jm=pl(),fk=Xm.PROPER,mk=Xm.CONFIGURABLE,Wm=Jm.IteratorPrototype,fn=Jm.BUGGY_SAFARI_ITERATORS,ua=hk("iterator"),zm="keys",la="values",Ym="entries",Km=function(){return this};Zm.exports=function(a,e,t,i,r,s,n){ck(t,e,i);var o=function(S){if(S===r&&f)return f;if(!fn&&S&&S in d)return d[S];switch(S){case zm:return function(){return new t(this,S)};case la:return function(){return new t(this,S)};case Ym:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=a.prototype,c=d[ua]||d["@@iterator"]||r&&d[r],f=!fn&&c||o(r),p=e==="Array"&&d.entries||c,h,m,g;if(p&&(h=Hm(p.call(new a)),h!==Object.prototype&&h.next&&(!hn&&Hm(h)!==Wm&&(Qm?Qm(h,Wm):lk(h[ua])||fl(h,ua,Km)),dk(h,u,!0,!0),hn&&(Gm[u]=Km))),fk&&r===la&&c&&c.name!==la&&(!hn&&mk?pk(d,"name",la):(l=!0,f=function(){return uk(c,this)})),r)if(m={values:o(la),keys:s?f:o(zm),entries:o(Ym)},n)for(g in m)(fn||l||!(g in d))&&fl(d,g,m[g]);else ok({target:e,proto:!0,forced:fn||l},m);return(!hn||n)&&d[ua]!==f&&fl(d,ua,f,{name:r}),Gm[e]=f,m}});var ib=b((_O,tb)=>{"use strict";tb.exports=function(a,e){return{value:a,done:e}}});var bl=b((OO,ob)=>{"use strict";var bk=fi(),ml=aa(),rb=Si(),sb=el(),gk=gi().f,Sk=eb(),mn=ib(),vk=at(),yk=Ue(),nb="Array Iterator",Tk=sb.set,Ik=sb.getterFor(nb);ob.exports=Sk(Array,"Array",function(a,e){Tk(this,{type:nb,target:bk(a),index:0,kind:e})},function(){var a=Ik(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,mn(void 0,!0);switch(a.kind){case"keys":return mn(t,!1);case"values":return mn(e[t],!1)}return mn([t,e[t]],!1)},"values");var ab=rb.Arguments=rb.Array;ml("keys");ml("values");ml("entries");if(!vk&&yk&&ab.name!=="values")try{gk(ab,"name",{value:"values"})}catch(a){}});var lb=b((FO,ub)=>{"use strict";var Ek=ye(),xk=Si(),wk=Ek("iterator"),Ak=Array.prototype;ub.exports=function(a){return a!==void 0&&(xk.Array===a||Ak[wk]===a)}});var gl=b((NO,db)=>{"use strict";var Pk=na(),cb=Zr(),kk=Kr(),Rk=Si(),Lk=ye(),$k=Lk("iterator");db.exports=function(a){if(!kk(a))return cb(a,$k)||cb(a,"@@iterator")||Rk[Pk(a)]}});var hb=b((UO,pb)=>{"use strict";var Mk=qe(),Dk=ht(),Ck=ft(),Bk=Jr(),Vk=gl(),_k=TypeError;pb.exports=function(a,e){var t=arguments.length<2?Vk(a):e;if(Dk(t))return Ck(Mk(t,a));throw new _k(Bk(a)+" is not iterable")}});var bb=b((qO,mb)=>{"use strict";var Ok=qe(),fb=ft(),Fk=Zr();mb.exports=function(a,e,t){var i,r;fb(a);try{if(i=Fk(a,"return"),!i){if(e==="throw")throw t;return t}i=Ok(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return fb(i),t}});var gn=b((jO,yb)=>{"use strict";var Nk=Yi(),Uk=qe(),qk=ft(),jk=Jr(),Hk=lb(),Qk=Zi(),gb=Xr(),Gk=hb(),Wk=gl(),Sb=bb(),zk=TypeError,bn=function(a,e){this.stopped=a,this.result=e},vb=bn.prototype;yb.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Nk(e,i),l,d,c,f,p,h,m,g=function(v){return l&&Sb(l,"normal"),new bn(!0,v)},S=function(v){return r?(qk(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(s)l=a.iterator;else if(n)l=a;else{if(d=Wk(a),!d)throw new zk(jk(a)+" is not iterable");if(Hk(d)){for(c=0,f=Qk(a);f>c;c++)if(p=S(a[c]),p&&gb(vb,p))return p;return new bn(!1)}l=Gk(a,d)}for(h=s?a.next:l.next;!(m=Uk(h,l)).done;){try{p=S(m.value)}catch(v){Sb(l,"throw",v)}if(typeof p=="object"&&p&&gb(vb,p))return p}return new bn(!1)}});var Ib=b((HO,Tb)=>{"use strict";var Yk=Ue(),Kk=gi(),Xk=Yr();Tb.exports=function(a,e,t){Yk?Kk.f(a,e,Xk(0,t)):a[e]=t}});var Eb=b(()=>{"use strict";var Jk=de(),Zk=gn(),eR=Ib();Jk({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Zk(e,function(i,r){eR(t,i,r)},{AS_ENTRIES:!0}),t}})});var wb=b((WO,xb)=>{"use strict";bl();Eb();var tR=mi();xb.exports=tR.Object.fromEntries});var Pb=b((zO,Ab)=>{"use strict";Ab.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Rb=b(()=>{"use strict";bl();var iR=Pb(),rR=oe(),aR=oa(),kb=Si();for(Sn in iR)aR(rR[Sn],Sn),kb[Sn]=kb.Array;var Sn});var $b=b((XO,Lb)=>{"use strict";var sR=wb();Rb();Lb.exports=sR});var Sl=b((JO,Mb)=>{"use strict";var nR=$b();Mb.exports=nR});var Db=b(()=>{"use strict"});var vl=b((tF,Cb)=>{"use strict";var ca=oe(),oR=bi(),uR=hi(),vn=function(a){return oR.slice(0,a.length)===a};Cb.exports=function(){return vn("Bun/")?"BUN":vn("Cloudflare-Workers")?"CLOUDFLARE":vn("Deno/")?"DENO":vn("Node.js/")?"NODE":ca.Bun&&typeof Bun.version=="string"?"BUN":ca.Deno&&typeof Deno.version=="object"?"DENO":uR(ca.process)==="process"?"NODE":ca.window&&ca.document?"BROWSER":"REST"}()});var yn=b((iF,Bb)=>{"use strict";var lR=vl();Bb.exports=lR==="NODE"});var _b=b((rF,Vb)=>{"use strict";var cR=gi();Vb.exports=function(a,e,t){return cR.f(a,e,t)}});var Nb=b((aF,Fb)=>{"use strict";var dR=Pt(),pR=_b(),hR=ye(),fR=Ue(),Ob=hR("species");Fb.exports=function(a){var e=dR(a);fR&&e&&!e[Ob]&&pR(e,Ob,{configurable:!0,get:function(){return this}})}});var qb=b((sF,Ub)=>{"use strict";var mR=Xr(),bR=TypeError;Ub.exports=function(a,e){if(mR(e,a))return a;throw new bR("Incorrect invocation")}});var Tl=b((nF,jb)=>{"use strict";var gR=he(),SR=ue(),yl=ea(),vR=gR(Function.toString);SR(yl.inspectSource)||(yl.inspectSource=function(a){return vR(a)});jb.exports=yl.inspectSource});var El=b((oF,zb)=>{"use strict";var yR=he(),TR=pe(),Hb=ue(),IR=na(),ER=Pt(),xR=Tl(),Qb=function(){},Gb=ER("Reflect","construct"),Il=/^\s*(?:class|function)\b/,wR=yR(Il.exec),AR=!Il.test(Qb),da=function(e){if(!Hb(e))return!1;try{return Gb(Qb,[],e),!0}catch(t){return!1}},Wb=function(e){if(!Hb(e))return!1;switch(IR(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return AR||!!wR(Il,xR(e))}catch(t){return!0}};Wb.sham=!0;zb.exports=!Gb||TR(function(){var a;return da(da.call)||!da(Object)||!da(function(){a=!0})||a})?Wb:da});var Kb=b((uF,Yb)=>{"use strict";var PR=El(),kR=Jr(),RR=TypeError;Yb.exports=function(a){if(PR(a))return a;throw new RR(kR(a)+" is not a constructor")}});var xl=b((lF,Jb)=>{"use strict";var Xb=ft(),LR=Kb(),$R=Kr(),MR=ye(),DR=MR("species");Jb.exports=function(a,e){var t=Xb(a).constructor,i;return t===void 0||$R(i=Xb(t)[DR])?e:LR(i)}});var eg=b((cF,Zb)=>{"use strict";var CR=he();Zb.exports=CR([].slice)});var ig=b((dF,tg)=>{"use strict";var BR=TypeError;tg.exports=function(a,e){if(a<e)throw new BR("Not enough arguments");return a}});var wl=b((pF,rg)=>{"use strict";var VR=bi();rg.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(VR)});var Cl=b((hF,pg)=>{"use strict";var je=oe(),_R=fu(),OR=Yi(),ag=ue(),FR=st(),dg=pe(),sg=al(),NR=eg(),ng=Zs(),UR=ig(),qR=wl(),jR=yn(),$l=je.setImmediate,Ml=je.clearImmediate,HR=je.process,Al=je.Dispatch,QR=je.Function,og=je.MessageChannel,GR=je.String,Pl=0,pa={},ug="onreadystatechange",ha,yi,kl,Rl;dg(function(){ha=je.location});var Dl=function(a){if(FR(pa,a)){var e=pa[a];delete pa[a],e()}},Ll=function(a){return function(){Dl(a)}},lg=function(a){Dl(a.data)},cg=function(a){je.postMessage(GR(a),ha.protocol+"//"+ha.host)};(!$l||!Ml)&&($l=function(e){UR(arguments.length,1);var t=ag(e)?e:QR(e),i=NR(arguments,1);return pa[++Pl]=function(){_R(t,void 0,i)},yi(Pl),Pl},Ml=function(e){delete pa[e]},jR?yi=function(a){HR.nextTick(Ll(a))}:Al&&Al.now?yi=function(a){Al.now(Ll(a))}:og&&!qR?(kl=new og,Rl=kl.port2,kl.port1.onmessage=lg,yi=OR(Rl.postMessage,Rl)):je.addEventListener&&ag(je.postMessage)&&!je.importScripts&&ha&&ha.protocol!=="file:"&&!dg(cg)?(yi=cg,je.addEventListener("message",lg,!1)):ug in ng("script")?yi=function(a){sg.appendChild(ng("script"))[ug]=function(){sg.removeChild(this),Dl(a)}}:yi=function(a){setTimeout(Ll(a),0)});pg.exports={set:$l,clear:Ml}});var mg=b((fF,fg)=>{"use strict";var hg=oe(),WR=Ue(),zR=Object.getOwnPropertyDescriptor;fg.exports=function(a){if(!WR)return hg[a];var e=zR(hg,a);return e&&e.value}});var Bl=b((mF,gg)=>{"use strict";var bg=function(){this.head=null,this.tail=null};bg.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};gg.exports=bg});var vg=b((bF,Sg)=>{"use strict";var YR=bi();Sg.exports=/ipad|iphone|ipod/i.test(YR)&&typeof Pebble!="undefined"});var Tg=b((gF,yg)=>{"use strict";var KR=bi();yg.exports=/web0s(?!.*chrome)/i.test(KR)});var kg=b((SF,Pg)=>{"use strict";var rr=oe(),XR=mg(),Ig=Yi(),Vl=Cl().set,JR=Bl(),ZR=wl(),eL=vg(),tL=Tg(),_l=yn(),Eg=rr.MutationObserver||rr.WebKitMutationObserver,xg=rr.document,wg=rr.process,Tn=rr.Promise,Nl=XR("queueMicrotask"),ir,Ol,Fl,In,Ag;Nl||(fa=new JR,ma=function(){var a,e;for(_l&&(a=wg.domain)&&a.exit();e=fa.get();)try{e()}catch(t){throw fa.head&&ir(),t}a&&a.enter()},!ZR&&!_l&&!tL&&Eg&&xg?(Ol=!0,Fl=xg.createTextNode(""),new Eg(ma).observe(Fl,{characterData:!0}),ir=function(){Fl.data=Ol=!Ol}):!eL&&Tn&&Tn.resolve?(In=Tn.resolve(void 0),In.constructor=Tn,Ag=Ig(In.then,In),ir=function(){Ag(ma)}):_l?ir=function(){wg.nextTick(ma)}:(Vl=Ig(Vl,rr),ir=function(){Vl(ma)}),Nl=function(a){fa.head||ir(),fa.add(a)});var fa,ma;Pg.exports=Nl});var Lg=b((vF,Rg)=>{"use strict";Rg.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var En=b((yF,$g)=>{"use strict";$g.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ti=b((TF,Mg)=>{"use strict";var iL=oe();Mg.exports=iL.Promise});var ar=b((IF,Vg)=>{"use strict";var rL=oe(),ba=Ti(),aL=ue(),sL=Vu(),nL=Tl(),oL=ye(),Dg=vl(),uL=at(),Ul=Eu(),Cg=ba&&ba.prototype,lL=oL("species"),ql=!1,Bg=aL(rL.PromiseRejectionEvent),cL=sL("Promise",function(){var a=nL(ba),e=a!==String(ba);if(!e&&Ul===66||uL&&!(Cg.catch&&Cg.finally))return!0;if(!Ul||Ul<51||!/native code/.test(a)){var t=new ba(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[lL]=i,ql=t.then(function(){})instanceof i,!ql)return!0}return!e&&(Dg==="BROWSER"||Dg==="DENO")&&!Bg});Vg.exports={CONSTRUCTOR:cL,REJECTION_EVENT:Bg,SUBCLASSING:ql}});var sr=b((EF,Og)=>{"use strict";var _g=ht(),dL=TypeError,pL=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new dL("Bad Promise constructor");e=i,t=r}),this.resolve=_g(e),this.reject=_g(t)};Og.exports.f=function(a){return new pL(a)}});var aS=b(()=>{"use strict";var hL=de(),fL=at(),Pn=yn(),Wt=oe(),mL=mi(),lr=qe(),Fg=tr(),Ng=hl(),bL=oa(),gL=Nb(),SL=ht(),An=ue(),vL=$e(),yL=qb(),TL=xl(),Qg=Cl().set,Wl=kg(),IL=Lg(),EL=En(),xL=Bl(),Gg=el(),kn=Ti(),zl=ar(),Wg=sr(),Rn="Promise",zg=zl.CONSTRUCTOR,wL=zl.REJECTION_EVENT,AL=zl.SUBCLASSING,jl=Gg.getterFor(Rn),PL=Gg.set,nr=kn&&kn.prototype,Ii=kn,xn=nr,Yg=Wt.TypeError,Hl=Wt.document,Yl=Wt.process,Ql=Wg.f,kL=Ql,RL=!!(Hl&&Hl.createEvent&&Wt.dispatchEvent),Kg="unhandledrejection",LL="rejectionhandled",Ug=0,Xg=1,$L=2,Kl=1,Jg=2,wn,qg,Zg,jg,eS=function(a){var e;return vL(a)&&An(e=a.then)?e:!1},tS=function(a,e){var t=e.value,i=e.state===Xg,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,d;try{r?(i||(e.rejection===Jg&&DL(e),e.rejection=Kl),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),d=!0)),u===a.promise?n(new Yg("Promise-chain cycle")):(l=eS(u))?lr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},iS=function(a,e){a.notified||(a.notified=!0,Wl(function(){for(var t=a.reactions,i;i=t.get();)tS(i,a);a.notified=!1,e&&!a.rejection&&ML(a)}))},rS=function(a,e,t){var i,r;RL?(i=Hl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Wt.dispatchEvent(i)):i={promise:e,reason:t},!wL&&(r=Wt["on"+a])?r(i):a===Kg&&IL("Unhandled promise rejection",t)},ML=function(a){lr(Qg,Wt,function(){var e=a.facade,t=a.value,i=Hg(a),r;if(i&&(r=EL(function(){Pn?Yl.emit("unhandledRejection",t,e):rS(Kg,e,t)}),a.rejection=Pn||Hg(a)?Jg:Kl,r.error))throw r.value})},Hg=function(a){return a.rejection!==Kl&&!a.parent},DL=function(a){lr(Qg,Wt,function(){var e=a.facade;Pn?Yl.emit("rejectionHandled",e):rS(LL,e,a.value)})},or=function(a,e,t){return function(i){a(e,i,t)}},ur=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=$L,iS(a,!0))},Gl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Yg("Promise can't be resolved itself");var i=eS(e);i?Wl(function(){var r={done:!1};try{lr(i,e,or(Gl,r,a),or(ur,r,a))}catch(s){ur(r,s,a)}}):(a.value=e,a.state=Xg,iS(a,!1))}catch(r){ur({done:!1},r,a)}}};if(zg&&(Ii=function(e){yL(this,xn),SL(e),lr(wn,this);var t=jl(this);try{e(or(Gl,t),or(ur,t))}catch(i){ur(t,i)}},xn=Ii.prototype,wn=function(e){PL(this,{type:Rn,done:!1,notified:!1,parent:!1,reactions:new xL,rejection:!1,state:Ug,value:null})},wn.prototype=Fg(xn,"then",function(e,t){var i=jl(this),r=Ql(TL(this,Ii));return i.parent=!0,r.ok=An(e)?e:!0,r.fail=An(t)&&t,r.domain=Pn?Yl.domain:void 0,i.state===Ug?i.reactions.add(r):Wl(function(){tS(r,i)}),r.promise}),qg=function(){var a=new wn,e=jl(a);this.promise=a,this.resolve=or(Gl,e),this.reject=or(ur,e)},Wg.f=Ql=function(a){return a===Ii||a===Zg?new qg(a):kL(a)},!fL&&An(kn)&&nr!==Object.prototype)){jg=nr.then,AL||Fg(nr,"then",function(e,t){var i=this;return new Ii(function(r,s){lr(jg,i,r,s)}).then(e,t)},{unsafe:!0});try{delete nr.constructor}catch(a){}Ng&&Ng(nr,xn)}hL({global:!0,constructor:!0,wrap:!0,forced:zg},{Promise:Ii});Zg=mL.Promise;bL(Ii,Rn,!1,!0);gL(Rn)});var lS=b((AF,uS)=>{"use strict";var CL=ye(),nS=CL("iterator"),oS=!1;try{sS=0,Xl={next:function(){return{done:!!sS++}},return:function(){oS=!0}},Xl[nS]=function(){return this},Array.from(Xl,function(){throw 2})}catch(a){}var sS,Xl;uS.exports=function(a,e){try{if(!e&&!oS)return!1}catch(r){return!1}var t=!1;try{var i={};i[nS]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Jl=b((PF,cS)=>{"use strict";var BL=Ti(),VL=lS(),_L=ar().CONSTRUCTOR;cS.exports=_L||!VL(function(a){BL.all(a).then(void 0,function(){})})});var dS=b(()=>{"use strict";var OL=de(),FL=qe(),NL=ht(),UL=sr(),qL=En(),jL=gn(),HL=Jl();OL({target:"Promise",stat:!0,forced:HL},{all:function(e){var t=this,i=UL.f(t),r=i.resolve,s=i.reject,n=qL(function(){var o=NL(t.resolve),u=[],l=0,d=1;jL(e,function(c){var f=l++,p=!1;d++,FL(o,t,c).then(function(h){p||(p=!0,u[f]=h,--d||r(u))},s)}),--d||r(u)});return n.error&&s(n.value),i.promise}})});var hS=b(()=>{"use strict";var QL=de(),GL=at(),WL=ar().CONSTRUCTOR,ec=Ti(),zL=Pt(),YL=ue(),KL=tr(),pS=ec&&ec.prototype;QL({target:"Promise",proto:!0,forced:WL,real:!0},{catch:function(a){return this.then(void 0,a)}});!GL&&YL(ec)&&(Zl=zL("Promise").prototype.catch,pS.catch!==Zl&&KL(pS,"catch",Zl,{unsafe:!0}));var Zl});var fS=b(()=>{"use strict";var XL=de(),JL=qe(),ZL=ht(),e$=sr(),t$=En(),i$=gn(),r$=Jl();XL({target:"Promise",stat:!0,forced:r$},{race:function(e){var t=this,i=e$.f(t),r=i.reject,s=t$(function(){var n=ZL(t.resolve);i$(e,function(o){JL(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var mS=b(()=>{"use strict";var a$=de(),s$=sr(),n$=ar().CONSTRUCTOR;a$({target:"Promise",stat:!0,forced:n$},{reject:function(e){var t=s$.f(this),i=t.reject;return i(e),t.promise}})});var tc=b((VF,bS)=>{"use strict";var o$=ft(),u$=$e(),l$=sr();bS.exports=function(a,e){if(o$(a),u$(e)&&e.constructor===a)return e;var t=l$.f(a),i=t.resolve;return i(e),t.promise}});var vS=b(()=>{"use strict";var c$=de(),d$=Pt(),gS=at(),p$=Ti(),SS=ar().CONSTRUCTOR,h$=tc(),f$=d$("Promise"),m$=gS&&!SS;c$({target:"Promise",stat:!0,forced:gS||SS},{resolve:function(e){return h$(m$&&this===f$?p$:this,e)}})});var yS=b(()=>{"use strict";aS();dS();hS();fS();mS();vS()});var xS=b(()=>{"use strict";var b$=de(),g$=at(),Ln=Ti(),S$=pe(),IS=Pt(),ES=ue(),v$=xl(),TS=tc(),y$=tr(),rc=Ln&&Ln.prototype,T$=!!Ln&&S$(function(){rc.finally.call({then:function(){}},function(){})});b$({target:"Promise",proto:!0,real:!0,forced:T$},{finally:function(a){var e=v$(this,IS("Promise")),t=ES(a);return this.then(t?function(i){return TS(e,a()).then(function(){return i})}:a,t?function(i){return TS(e,a()).then(function(){throw i})}:a)}});!g$&&ES(Ln)&&(ic=IS("Promise").prototype.finally,rc.finally!==ic&&y$(rc,"finally",ic,{unsafe:!0}));var ic});var AS=b((jF,wS)=>{"use strict";Db();yS();xS();var I$=Gt();wS.exports=I$("Promise","finally")});var kS=b((HF,PS)=>{"use strict";var E$=AS();PS.exports=E$});var $n=b((QF,RS)=>{"use strict";var x$=kS();RS.exports=x$});var qS=b(()=>{"use strict";var O$=de(),F$=Ku().values;O$({target:"Object",stat:!0},{values:function(e){return F$(e)}})});var HS=b((RN,jS)=>{"use strict";qS();var N$=mi();jS.exports=N$.Object.values});var GS=b((LN,QS)=>{"use strict";var U$=HS();QS.exports=U$});var dr=b(($N,WS)=>{"use strict";var q$=GS();WS.exports=q$});var cv=b(()=>{"use strict";var dM=de(),pM=Wi(),hM=Zi(),fM=ra(),mM=aa();dM({target:"Array",proto:!0},{at:function(e){var t=pM(this),i=hM(t),r=fM(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});mM("at")});var pv=b((NU,dv)=>{"use strict";cv();var bM=Gt();dv.exports=bM("Array","at")});var fv=b((UU,hv)=>{"use strict";var gM=pv();hv.exports=gM});var St=b((qU,mv)=>{"use strict";var SM=fv();mv.exports=SM});var Ac=b((D1,Kv)=>{"use strict";var JM=hi();Kv.exports=Array.isArray||function(e){return JM(e)==="Array"}});var Jv=b((C1,Xv)=>{"use strict";var ZM=TypeError,eD=9007199254740991;Xv.exports=function(a){if(a>eD)throw ZM("Maximum allowed index exceeded");return a}});var ty=b((B1,ey)=>{"use strict";var tD=Ac(),iD=Zi(),rD=Jv(),aD=Yi(),Zv=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,d=n?aD(n,o):!1,c,f;l<i;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&tD(c)?(f=iD(c),u=Zv(a,e,c,f,u,s-1)-1):(rD(u+1),a[u]=c),u++),l++;return u};ey.exports=Zv});var sy=b((V1,ay)=>{"use strict";var iy=Ac(),sD=El(),nD=$e(),oD=ye(),uD=oD("species"),ry=Array;ay.exports=function(a){var e;return iy(a)&&(e=a.constructor,sD(e)&&(e===ry||iy(e.prototype))?e=void 0:nD(e)&&(e=e[uD],e===null&&(e=void 0))),e===void 0?ry:e}});var oy=b((_1,ny)=>{"use strict";var lD=sy();ny.exports=function(a,e){return new(lD(a))(e===0?0:e)}});var uy=b(()=>{"use strict";var cD=de(),dD=ty(),pD=ht(),hD=Wi(),fD=Zi(),mD=oy();cD({target:"Array",proto:!0},{flatMap:function(e){var t=hD(this),i=fD(t),r;return pD(e),r=mD(t,0),r.length=dD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var ly=b(()=>{"use strict";var bD=aa();bD("flatMap")});var dy=b((q1,cy)=>{"use strict";uy();ly();var gD=Gt();cy.exports=gD("Array","flatMap")});var hy=b((j1,py)=>{"use strict";var SD=dy();py.exports=SD});var Ma=b((H1,fy)=>{"use strict";var vD=hy();fy.exports=vD});var Da=b((Q1,my)=>{"use strict";var yD=na(),TD=String;my.exports=function(a){if(yD(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return TD(a)}});var Pc=b((G1,by)=>{"use strict";by.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 vy=b((W1,Sy)=>{"use strict";var ID=he(),ED=Qt(),xD=Da(),Rc=Pc(),gy=ID("".replace),wD=RegExp("^["+Rc+"]+"),AD=RegExp("(^|[^"+Rc+"])["+Rc+"]+$"),kc=function(a){return function(e){var t=xD(ED(e));return a&1&&(t=gy(t,wD,"")),a&2&&(t=gy(t,AD,"$1")),t}};Sy.exports={start:kc(1),end:kc(2),trim:kc(3)}});var Ey=b((z1,Iy)=>{"use strict";var PD=rl().PROPER,kD=pe(),yy=Pc(),Ty="\u200B\x85\u180E";Iy.exports=function(a){return kD(function(){return!!yy[a]()||Ty[a]()!==Ty||PD&&yy[a].name!==a})}});var Lc=b((Y1,xy)=>{"use strict";var RD=vy().start,LD=Ey();xy.exports=LD("trimStart")?function(){return RD(this)}:"".trimStart});var Ay=b(()=>{"use strict";var $D=de(),wy=Lc();$D({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==wy},{trimLeft:wy})});var ky=b(()=>{"use strict";Ay();var MD=de(),Py=Lc();MD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Py},{trimStart:Py})});var Ly=b((ej,Ry)=>{"use strict";ky();var DD=Gt();Ry.exports=DD("String","trimLeft")});var My=b((tj,$y)=>{"use strict";var CD=Ly();$y.exports=CD});var Cy=b((ij,Dy)=>{"use strict";var BD=My();Dy.exports=BD});var Yy=b(()=>{"use strict"});var Ky=b(()=>{"use strict"});var Jy=b((_Q,Xy)=>{"use strict";var aC=$e(),sC=hi(),nC=ye(),oC=nC("match");Xy.exports=function(a){var e;return aC(a)&&((e=a[oC])!==void 0?!!e:sC(a)==="RegExp")}});var tT=b((OQ,eT)=>{"use strict";var uC=oe(),lC=pe(),Zy=uC.RegExp,cC=!lC(function(){var a=!0;try{Zy(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(Zy.prototype,"flags").get.call(e);return o!==i||t!==i});eT.exports={correct:cC}});var rT=b((FQ,iT)=>{"use strict";var dC=ft();iT.exports=function(){var a=dC(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var nT=b((NQ,sT)=>{"use strict";var pC=qe(),hC=st(),fC=Xr(),aT=tT(),mC=rT(),bC=RegExp.prototype;sT.exports=aT.correct?function(a){return a.flags}:function(a){return!aT.correct&&fC(bC,a)&&!hC(a,"flags")?pC(mC,a):a.flags}});var uT=b((UQ,oT)=>{"use strict";var Bc=he(),gC=Wi(),SC=Math.floor,Dc=Bc("".charAt),vC=Bc("".replace),Cc=Bc("".slice),yC=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,TC=/\$([$&'`]|\d{1,2})/g;oT.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=TC;return r!==void 0&&(r=gC(r),u=yC),vC(s,u,function(l,d){var c;switch(Dc(d,0)){case"$":return"$";case"&":return a;case"`":return Cc(e,0,t);case"'":return Cc(e,n);case"<":c=r[Cc(d,1,-1)];break;default:var f=+d;if(f===0)return l;if(f>o){var p=SC(f/10);return p===0?l:p<=o?i[p-1]===void 0?Dc(d,1):i[p-1]+Dc(d,1):l}c=i[f-1]}return c===void 0?"":c})}});var dT=b(()=>{"use strict";var IC=de(),EC=qe(),_c=he(),lT=Qt(),xC=ue(),wC=$e(),AC=Jy(),xr=Da(),PC=Zr(),kC=nT(),RC=uT(),LC=ye(),$C=at(),MC=LC("replace"),DC=TypeError,Vc=_c("".indexOf),CC=_c("".replace),cT=_c("".slice),BC=Math.max;IC({target:"String",proto:!0},{replaceAll:function(e,t){var i=lT(this),r,s,n,o,u,l,d,c,f,p,h=0,m="";if(wC(e)){if(r=AC(e),r&&(s=xr(lT(kC(e))),!~Vc(s,"g")))throw new DC("`.replaceAll` does not allow non-global regexes");if(n=PC(e,MC),n)return EC(n,e,i,t);if($C&&r)return CC(xr(i),e,t)}for(o=xr(i),u=xr(e),l=xC(t),l||(t=xr(t)),d=u.length,c=BC(1,d),f=Vc(o,u);f!==-1;)p=l?xr(t(u,f,o)):RC(u,o,f,[],void 0,t),m+=cT(o,h,f)+p,h=f+d,f=f+c>o.length?-1:Vc(o,u,f+c);return h<o.length&&(m+=cT(o,h)),m}})});var hT=b((HQ,pT)=>{"use strict";Yy();Ky();dT();var VC=Gt();pT.exports=VC("String","replaceAll")});var mT=b((QQ,fT)=>{"use strict";var _C=hT();fT.exports=_C});var gT=b((GQ,bT)=>{"use strict";var OC=mT();bT.exports=OC});var vT=b((WQ,ST)=>{"use strict";var FC=ra(),NC=Da(),UC=Qt(),qC=RangeError;ST.exports=function(e){var t=NC(UC(this)),i="",r=FC(e);if(r<0||r===1/0)throw new qC("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var xT=b((zQ,ET)=>{"use strict";var IT=he(),jC=qu(),yT=Da(),HC=vT(),QC=Qt(),GC=IT(HC),WC=IT("".slice),zC=Math.ceil,TT=function(a){return function(e,t,i){var r=yT(QC(e)),s=jC(t),n=r.length,o=i===void 0?" ":yT(i),u,l;return s<=n||o===""?r:(u=s-n,l=GC(o,zC(u/o.length)),l.length>u&&(l=WC(l,0,u)),a?r+l:l+r)}};ET.exports={start:TT(!1),end:TT(!0)}});var AT=b((YQ,wT)=>{"use strict";var YC=bi();wT.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(YC)});var PT=b(()=>{"use strict";var KC=de(),XC=xT().start,JC=AT();KC({target:"String",proto:!0,forced:JC},{padStart:function(e){return XC(this,e,arguments.length>1?arguments[1]:void 0)}})});var RT=b((JQ,kT)=>{"use strict";PT();var ZC=Gt();kT.exports=ZC("String","padStart")});var $T=b((ZQ,LT)=>{"use strict";var eB=RT();LT.exports=eB});var DT=b((eG,MT)=>{"use strict";var tB=$T();MT.exports=tB});var Vp="2.0.136-dev.d878e150.0";var Le=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Le||{}),At=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(At||{});var Ys=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ys||{}),du=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(du||{});var pu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(pu||{}),Ks=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ks||{});var LE=N(Ye(),1);import{assertNever as Bf,assertNonNullable as dA,isNonNullable as tn,ValueSubject as Hu,Subject as pA,Subscription as hA,merge as fA,observableFrom as mA,fromEvent as $f,map as Mf,tap as Df,filterChanged as bA,isNullable as Qu,ErrorCategory as Cf}from"@vkontakte/videoplayer-shared/es2018";var Lf=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var rn=class{constructor(e){this.connection$=new Hu(void 0);this.castState$=new Hu("NOT_AVAILABLE");this.errorEvent$=new pA;this.realCastState$=new Hu("NOT_AVAILABLE");this.subscription=new hA;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=tn((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Lf("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Cf.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){tn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Qu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Qu(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add($f(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Bf(r.sessionState)}})).add(fA($f(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Df(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Mf(r=>r.castState)),mA([i.getCastState()])).pipe(bA(),Mf(gA),Df(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=tn(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();dA(l);let d=l.getCastDevice(),c=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Qu(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?tn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Cf.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},gA=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Bf(a)}};var jd=N(Ye(),1),dE=N(er(),1),pE=N(Sl(),1);var FS=N($n(),1);import{assertNever as LS}from"@vkontakte/videoplayer-shared/es2018";var le=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:LS(t)}return a},zt=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:LS(e)}};var L=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as w$,Subject as Mn,merge as $S}from"@vkontakte/videoplayer-shared/es2018";var j=class{constructor(e){this.transitionStarted$=new Mn;this.transitionEnded$=new Mn;this.transitionUpdated$=new Mn;this.forceChanged$=new Mn;this.stateChangeStarted$=$S(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=$S(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||w$(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 MS=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return A$(a)}};import{assertNever as cr,assertNonNullable as Ei,debounce as DS,ErrorCategory as CS,fromEvent as xi,isNonNullable as BS,map as VS,merge as _S,observableFrom as P$,Subject as k$,Subscription as ac,timeout as R$,getHighestQuality as L$}from"@vkontakte/videoplayer-shared/es2018";var $$=5,M$=5,D$=500,OS=7e3,ga=class{constructor(e){this.subscription=new ac;this.loadMediaTimeoutSubscription=new ac;this.videoState=new j("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:cr(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:cr(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:cr(e)}break}default:cr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(MS(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 ac;this.subscription.add(e),this.subscription.add(_S(this.videoState.stateChangeStarted$.pipe(VS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(VS(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new k$;e.add(r.pipe(DS(D$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>$$)&&r.next(o),s=o})),e.add(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<M$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),L(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:cr(n)}}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=_S(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,P$(["init"])).pipe(DS(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),L(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),L(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&L(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let d=t[e];Ei(d);let c=L$(Object.keys(d));Ei(c);let f=d[c];Ei(f),i=f,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let d=t[e];Ei(d),i=d.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let d=t[e];Ei(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let d=t[e];Ei(d),i=d.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let d=t[e];Ei(d),i=le(d.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let d="Unsupported format for Chromecast",c=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:CS.VIDEO_PIPELINE,message:d,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return cr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return BS(o)&&(n.metadata.title=o),BS(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(R$(OS).subscribe(()=>s(`timeout(${OS})`)))});(0,FS.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:CS.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var xc=N(Ye(),1);import{clearVideoElement as US}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as C$}from"@vkontakte/videoplayer-shared/es2018";var NS=a=>{try{a.pause(),a.playbackRate=0,C$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as B$,Subscription as V$}from"@vkontakte/videoplayer-shared/es2018";var sc=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)}},nc=window.WeakMap?new WeakMap:new sc,oc=window.WeakMap?new WeakMap:new Map,_$=(a,e=20)=>{let t=0;return B$(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Me=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?US(i):(i=document.createElement("video"),a.appendChild(i)),nc.set(i,r);let s=new V$;return s.add(_$(i,e)),oc.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},De=a=>{let e=oc.get(a);e==null||e.unsubscribe(),oc.delete(a);let t=nc.get(a);nc.delete(a),t?US(a):NS(a)};var lc=N(dr(),1);import{assertNonNullable as va,isNonNullable as bt,isNullable as Q$,fromEvent as pr,merge as zS,observableFrom as YS,filterChanged as KS,map as ya,Subject as XS,Subscription as G$,ValueSubject as W$,ErrorCategory as z$}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as uc,isNullable as j$,Subscription as H$}from"@vkontakte/videoplayer-shared/es2018";var Dn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=j$(r),l=new H$;return r&&l.add(r.subscribe(d=>{let c=a.getState();i(d,c)&&a.setState(d)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(d=>{t(d.to),u&&a.setState(d.to)},s)),l},mt=(a,e,t)=>Dn(e,()=>a.loop,i=>{uc(i)&&(a.loop=i)},{onError:t}),Ce=(a,e,t,i)=>Dn(e,()=>({muted:a.muted,volume:a.volume}),r=>{uc(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ke=(a,e,t,i)=>Dn(e,()=>a.playbackRate,r=>{uc(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Sa=Dn;var Y$=a=>["__",a.language,a.label].join("|"),K$=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},cc=class a{constructor(e){this.available$=new XS;this.current$=new W$(void 0);this.error$=new XS;this.subscription=new G$;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:z$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Sa(t.internalTextTracks,()=>(0,lc.default)(this.internalTracks),s=>{bt(s)&&this.setInternal(s)},{equal:(s,n)=>bt(s)&&bt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ya(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Sa(t.externalTextTracks,()=>(0,lc.default)(this.externalTracks),s=>{bt(s)&&this.setExternal(s)},{equal:(s,n)=>bt(s)&&bt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ya(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Sa(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Sa(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){va(this.video);let{textTracks:e}=this.video;this.subscription.add(pr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(zS(pr(e,"addtrack"),pr(e,"removetrack"),YS(["init"])).pipe(ya(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),KS((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(zS(pr(e,"change"),YS(["init"])).pipe(ya(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),ya(i=>i&&this.htmlTextTrackToITextTrack(i).id),KS()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(pr(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,d,c,f,p;let u=(d=(l=o.target)==null?void 0:l.cues)!=null?d:null;u&&u.length&&(this.applyCueSettings((f=(c=o.target)==null?void 0:c.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(pr(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;bt(t.align)&&(r.align=t.align),bt(t.position)&&(r.position=t.position),bt(t.size)&&(r.size=t.size),bt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){va(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,d,c;let{language:t,label:i}=e,r=e.id?e.id:Y$(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(d=this.externalTracks.get(r))==null?void 0:d.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(c=this.internalTracks.get(r))==null?void 0:c.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){va(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Q$(e)||!K$(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){va(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){va(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Xe=cc;var wi=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var JS=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},dc=a=>{let e=JS(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ZS=a=>{let e=JS(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ae,map as gt,merge as Nn,filterChanged as ov,isNonNullable as uv,Subject as sM,filter as hc,mapTo as fc,combine as nM,once as oM,shareReplay as Pe,throttle as uM,ErrorCategory as lM,ValueSubject as lv,Subscription as cM}from"@vkontakte/videoplayer-shared/es2018";var X$=3,ev=(a,e,t=X$)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Cn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var tv=N(Ye(),1);var Ta=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Bn=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,tv.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=Ta()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Vn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var He=()=>window.ManagedMediaSource||window.MediaSource,hr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},iv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},_n=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var J$=document.createElement("video"),Z$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',eM='video/mp4; codecs="hev1.1.6.L93.B0"',rv='video/webm; codecs="vp09.00.10.08"',av='video/webm; codecs="av01.0.00M.08"',tM='audio/mp4; codecs="mp4a.40.2"',iM='audio/webm; codecs="opus"',sv,rM=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:av}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:rv}})]);sv={DASH_WEBM_AV1:e,DASH_WEBM:t}};rM().catch(a=>{console.log(J$),console.error(a)});var On=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 sv}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,d,c,f,p,h,m,g,S,v,y,I;this._video=document.createElement("video");try{this._protocols={mms:hr(),mse:iv(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let T=!!((d=(l=He())==null?void 0:l.isTypeSupported)!=null&&d.call(l,Z$)),x=!!((f=(c=He())==null?void 0:c.isTypeSupported)!=null&&f.call(c,eM)),V=!!((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,tM));this._codecs={h264:T,h265:x,vp9:!!((g=(m=He())==null?void 0:m.isTypeSupported)!=null&&g.call(m,rv)),av1:!!((v=(S=He())==null?void 0:S.isTypeSupported)!=null&&v.call(S,av)),aac:V,opus:!!((I=(y=He())==null?void 0:y.isTypeSupported)!=null&&I.call(y,iM)),mpeg:(T||x)&&V},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(T){console.error(T)}try{this.destroyVideoElement()}catch(T){console.error("Error destroying video element:",T)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var nv="audio/mpeg",Fn=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,nv))},this._codecs={mp3:!!((r=(i=He())==null?void 0:i.isTypeSupported)!=null&&r.call(i,nv))}}catch(s){console.error(s)}try{this.destroyAudioElement()}catch(s){console.error("Error destroying audio element:",s)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as aM}from"@vkontakte/videoplayer-shared/es2018";var pc=class{constructor(){this.isInited$=new aM(!1);this._displayChecker=new Vn,this._deviceChecker=new Bn(this._displayChecker),this._browserChecker=new Cn,this._videoChecker=new On(this._deviceChecker,this._browserChecker),this._audioChecker=new Fn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},U=new pc;var Be=a=>{let e=P=>Ae(a,P).pipe(fc(void 0),Pe(1)),t=new cM,i=()=>t.unsubscribe(),r=Nn(Ae(a,"progress"),Ae(a,"timeupdate")).pipe(gt(()=>ev(a.buffered,a.currentTime)),Pe(1)),s=U.browser.isSafari?nM({play:e("play").pipe(oM()),playing:e("playing")}).pipe(fc(void 0),Pe(1)):e("playing"),n=Ae(a,"volumechange").pipe(gt(()=>({muted:a.muted,volume:a.volume})),Pe(1)),o=Ae(a,"ratechange").pipe(gt(()=>a.playbackRate),Pe(1)),u=Ae(a,"error").pipe(hc(()=>!!(a.error||a.played.length)),gt(()=>{var B;let P=a.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:lM.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:(B=a.error)!=null?B:void 0}}),Pe(1)),l=Ae(a,"timeupdate").pipe(gt(()=>a.currentTime),Pe(1)),d=["waiting","seeking","seeked","timeupdate"],c=new sM,f=.3,p;t.add(Nn(...d.map(P=>Ae(a,P))).subscribe(P=>{let B=a.currentTime;a.loop&&uv(p)&&uv(B)&&p>=a.duration-f&&B<=f&&c.next(p),p=B}));let h=e("pause").pipe(hc(()=>!a.error&&p!==a.duration),Pe(1)),m=Ae(a,"enterpictureinpicture").pipe(Pe(1)),g=Ae(a,"leavepictureinpicture").pipe(Pe(1)),S=new lv(ZS(a));t.add(m.subscribe(()=>S.next(!0))),t.add(g.subscribe(()=>S.next(!1)));let v=new lv(dc(a)),y=Ae(a,"fullscreenchange").pipe(Pe(1));t.add(y.pipe(gt(()=>dc(a))).subscribe(v));let I=.1,T=1e3,x=Ae(a,"timeupdate").pipe(gt(P=>a.duration-a.currentTime<I),ov(),Pe(1)),V=Nn(x.pipe(hc(P=>!a.loop&&P)),Ae(a,"ended")).pipe(uM(T),fc(void 0),Pe(1)),w=Nn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>Ae(a,P)),x.pipe(gt(P=>({type:P?"ended":"unknown"})))).pipe(gt(P=>U.browser.isFirefox&&P.type==="ended"?a.readyState<2:a.readyState<3),ov(),Pe(1));return{playing$:s,pause$:h,canplay$:e("canplay"),ended$:V,looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ae(a,"durationchange").pipe(gt(()=>a.duration),Pe(1)),isBuffering$:w,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:v,enterPip$:m,leavePip$:g,destroy:i}};import{VideoQuality as Yt}from"@vkontakte/videoplayer-shared/es2018";var Kt=a=>{switch(a){case"mobile":return Yt.Q_144P;case"lowest":return Yt.Q_240P;case"low":return Yt.Q_360P;case"sd":case"medium":return Yt.Q_480P;case"hd":case"high":return Yt.Q_720P;case"fullhd":case"full":return Yt.Q_1080P;case"quadhd":case"quad":return Yt.Q_1440P;case"ultrahd":case"ultra":return Yt.Q_2160P}};var Re=N(St(),1),gc=N(Ye(),1),Ai=N(er(),1);import{isNonNullable as J,isNullable as Qn,now as wv,isHigher as Gn,isHigherOrEqual as mr,isInvariantQuality as Wn,isLowerOrEqual as br,videoSizeToQuality as Av,assertNotEmptyArray as zn,assertNonNullable as Pv}from"@vkontakte/videoplayer-shared/es2018";var mc=!1,Lt={},bv=a=>{mc=a},gv=()=>{Lt={}},Sv=a=>{a(Lt)},Ia=(a,e)=>{var t;mc&&(Lt.meta=(t=Lt.meta)!=null?t:{},Lt.meta[a]=e)},ke=class{constructor(e){this.name=e}next(e){var i,r;if(!mc)return;Lt.series=(i=Lt.series)!=null?i:{};let t=(r=Lt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Lt.series[this.name]=t}};import{isHigher as vM,isHigherOrEqual as zU,isLower as vv,isLowerOrEqual as YU,isNonNullable as Un,isNullable as yM,videoHeightToQuality as qn}from"@vkontakte/videoplayer-shared/es2018";function bc(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function jn(a,e,t){return!!a&&bc(a,e,t)==="high_quality"}function fr(a,e,t){return yM(a)||Un(a.min)&&Un(a.max)&&vv(a.max,a.min)||Un(a.min)&&e&&vM(a.min,e)||Un(a.max)&&t&&vv(a.max,t)}function yv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return fr({max:a!=null&&a.max?qn(a.max):void 0,min:a!=null&&a.min?qn(a.min):void 0},e?qn(e):void 0,t?qn(t):void 0)}var kv=new ke("best_bitrate"),Yn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var gr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Xt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=wv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Kn='Assertion "ABR Tracks is empty array" failed',Hn=new WeakMap,Tv=new WeakMap,Iv=new WeakMap,Ea=(a,e,t,i)=>{var u;let r=[...e].sort(gr(1)),s=[...t].sort(gr(1)),n=s.filter(l=>J(l.bitrate)&&J(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Re.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Re.default)(s,-1);return o&&(0,gc.default)(n,o)?o:n.length?(0,Re.default)(n,-1):(0,Re.default)(s,0)},xa=(a,e,t,i)=>{var u;let r=Hn.get(e);r||(r=[...e].sort(gr(1)),Hn.set(e,r));let s=Hn.get(t);s||(s=[...t].sort(gr(1)),Hn.set(t,s));let n=Iv.get(a);n||(n=s.filter(l=>J(l.bitrate)&&J(a.bitrate)?a.bitrate/l.bitrate>i:!0),Iv.set(a,n));let o=(u=(0,Re.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Re.default)(s,-1);return o&&(0,gc.default)(n,o)?o:n.length?(0,Re.default)(n,-1):(0,Re.default)(s,0)},Ev=a=>"quality"in a,Xn=(a,e,t,i)=>{var n;let r=J((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&J(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&wv()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Ev(o)?"video":"audio",l=Ev(o)?o.quality:o.bitrate;return e({message:`
6
+ var UE=Object.create;var Op=Object.defineProperty;var qE=Object.getOwnPropertyDescriptor;var jE=Object.getOwnPropertyNames;var HE=Object.getPrototypeOf,QE=Object.prototype.hasOwnProperty;var g=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var GE=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of jE(e))!QE.call(a,r)&&r!==t&&Op(a,r,{get:()=>e[r],enumerable:!(i=qE(e,r))||i.enumerable});return a};var O=(a,e,t)=>(t=a!=null?UE(HE(a)):{},GE(e||!a||!a.__esModule?Op(t,"default",{value:a,enumerable:!0}):t,a));var oe=g((hu,Np)=>{"use strict";var Wr=function(a){return a&&a.Math===Math&&a};Np.exports=Wr(typeof globalThis=="object"&&globalThis)||Wr(typeof window=="object"&&window)||Wr(typeof self=="object"&&self)||Wr(typeof global=="object"&&global)||Wr(typeof hu=="object"&&hu)||function(){return this}()||Function("return this")()});var pe=g((QV,Up)=>{"use strict";Up.exports=function(a){try{return!!a()}catch(e){return!0}}});var zr=g((GV,qp)=>{"use strict";var WE=pe();qp.exports=!WE(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var fu=g((WV,Gp)=>{"use strict";var zE=zr(),Qp=Function.prototype,jp=Qp.apply,Hp=Qp.call;Gp.exports=typeof Reflect=="object"&&Reflect.apply||(zE?Hp.bind(jp):function(){return Hp.apply(jp,arguments)})});var he=g((zV,Yp)=>{"use strict";var Wp=zr(),zp=Function.prototype,mu=zp.call,YE=Wp&&zp.bind.bind(mu,mu);Yp.exports=Wp?YE:function(a){return function(){return mu.apply(a,arguments)}}});var hi=g((YV,Xp)=>{"use strict";var Kp=he(),KE=Kp({}.toString),XE=Kp("".slice);Xp.exports=function(a){return XE(KE(a),8,-1)}});var bu=g((KV,Jp)=>{"use strict";var JE=hi(),ZE=he();Jp.exports=function(a){if(JE(a)==="Function")return ZE(a)}});var ue=g((XV,Zp)=>{"use strict";var gu=typeof document=="object"&&document.all;Zp.exports=typeof gu=="undefined"&&gu!==void 0?function(a){return typeof a=="function"||a===gu}:function(a){return typeof a=="function"}});var Ue=g((JV,eh)=>{"use strict";var ex=pe();eh.exports=!ex(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var qe=g((ZV,th)=>{"use strict";var tx=zr(),Xs=Function.prototype.call;th.exports=tx?Xs.bind(Xs):function(){return Xs.apply(Xs,arguments)}});var Su=g(ah=>{"use strict";var ih={}.propertyIsEnumerable,rh=Object.getOwnPropertyDescriptor,ix=rh&&!ih.call({1:2},1);ah.f=ix?function(e){var t=rh(this,e);return!!t&&t.enumerable}:ih});var Yr=g((t_,sh)=>{"use strict";sh.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var oh=g((i_,nh)=>{"use strict";var rx=he(),ax=pe(),sx=hi(),vu=Object,nx=rx("".split);nh.exports=ax(function(){return!vu("z").propertyIsEnumerable(0)})?function(a){return sx(a)==="String"?nx(a,""):vu(a)}:vu});var Kr=g((r_,uh)=>{"use strict";uh.exports=function(a){return a==null}});var Qt=g((a_,lh)=>{"use strict";var ox=Kr(),ux=TypeError;lh.exports=function(a){if(ox(a))throw new ux("Can't call method on "+a);return a}});var fi=g((s_,ch)=>{"use strict";var lx=oh(),cx=Qt();ch.exports=function(a){return lx(cx(a))}});var $e=g((n_,dh)=>{"use strict";var dx=ue();dh.exports=function(a){return typeof a=="object"?a!==null:dx(a)}});var mi=g((o_,ph)=>{"use strict";ph.exports={}});var Pt=g((u_,fh)=>{"use strict";var yu=mi(),Tu=oe(),px=ue(),hh=function(a){return px(a)?a:void 0};fh.exports=function(a,e){return arguments.length<2?hh(yu[a])||hh(Tu[a]):yu[a]&&yu[a][e]||Tu[a]&&Tu[a][e]}});var Xr=g((l_,mh)=>{"use strict";var hx=he();mh.exports=hx({}.isPrototypeOf)});var bi=g((c_,Sh)=>{"use strict";var fx=oe(),bh=fx.navigator,gh=bh&&bh.userAgent;Sh.exports=gh?String(gh):""});var Eu=g((d_,xh)=>{"use strict";var Eh=oe(),Iu=bi(),vh=Eh.process,yh=Eh.Deno,Th=vh&&vh.versions||yh&&yh.version,Ih=Th&&Th.v8,rt,Js;Ih&&(rt=Ih.split("."),Js=rt[0]>0&&rt[0]<4?1:+(rt[0]+rt[1]));!Js&&Iu&&(rt=Iu.match(/Edge\/(\d+)/),(!rt||rt[1]>=74)&&(rt=Iu.match(/Chrome\/(\d+)/),rt&&(Js=+rt[1])));xh.exports=Js});var xu=g((p_,Ah)=>{"use strict";var wh=Eu(),mx=pe(),bx=oe(),gx=bx.String;Ah.exports=!!Object.getOwnPropertySymbols&&!mx(function(){var a=Symbol("symbol detection");return!gx(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&wh&&wh<41})});var wu=g((h_,Ph)=>{"use strict";var Sx=xu();Ph.exports=Sx&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Au=g((f_,kh)=>{"use strict";var vx=Pt(),yx=ue(),Tx=Xr(),Ix=wu(),Ex=Object;kh.exports=Ix?function(a){return typeof a=="symbol"}:function(a){var e=vx("Symbol");return yx(e)&&Tx(e.prototype,Ex(a))}});var Jr=g((m_,Rh)=>{"use strict";var xx=String;Rh.exports=function(a){try{return xx(a)}catch(e){return"Object"}}});var ft=g((b_,Lh)=>{"use strict";var wx=ue(),Ax=Jr(),Px=TypeError;Lh.exports=function(a){if(wx(a))return a;throw new Px(Ax(a)+" is not a function")}});var Zr=g((g_,$h)=>{"use strict";var kx=ft(),Rx=Kr();$h.exports=function(a,e){var t=a[e];return Rx(t)?void 0:kx(t)}});var Dh=g((S_,Mh)=>{"use strict";var Pu=qe(),ku=ue(),Ru=$e(),Lx=TypeError;Mh.exports=function(a,e){var t,i;if(e==="string"&&ku(t=a.toString)&&!Ru(i=Pu(t,a))||ku(t=a.valueOf)&&!Ru(i=Pu(t,a))||e!=="string"&&ku(t=a.toString)&&!Ru(i=Pu(t,a)))return i;throw new Lx("Can't convert object to primitive value")}});var at=g((v_,Ch)=>{"use strict";Ch.exports=!0});var _h=g((y_,Vh)=>{"use strict";var Bh=oe(),$x=Object.defineProperty;Vh.exports=function(a,e){try{$x(Bh,a,{value:e,configurable:!0,writable:!0})}catch(t){Bh[a]=e}return e}});var ea=g((T_,Nh)=>{"use strict";var Mx=at(),Dx=oe(),Cx=_h(),Oh="__core-js_shared__",Fh=Nh.exports=Dx[Oh]||Cx(Oh,{});(Fh.versions||(Fh.versions=[])).push({version:"3.43.0",mode:Mx?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Lu=g((I_,qh)=>{"use strict";var Uh=ea();qh.exports=function(a,e){return Uh[a]||(Uh[a]=e||{})}});var Wi=g((E_,jh)=>{"use strict";var Bx=Qt(),Vx=Object;jh.exports=function(a){return Vx(Bx(a))}});var st=g((x_,Hh)=>{"use strict";var _x=he(),Ox=Wi(),Fx=_x({}.hasOwnProperty);Hh.exports=Object.hasOwn||function(e,t){return Fx(Ox(e),t)}});var $u=g((w_,Qh)=>{"use strict";var Nx=he(),Ux=0,qx=Math.random(),jx=Nx(1.1.toString);Qh.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+jx(++Ux+qx,36)}});var ye=g((A_,Wh)=>{"use strict";var Hx=oe(),Qx=Lu(),Gh=st(),Gx=$u(),Wx=xu(),zx=wu(),zi=Hx.Symbol,Mu=Qx("wks"),Yx=zx?zi.for||zi:zi&&zi.withoutSetter||Gx;Wh.exports=function(a){return Gh(Mu,a)||(Mu[a]=Wx&&Gh(zi,a)?zi[a]:Yx("Symbol."+a)),Mu[a]}});var Xh=g((P_,Kh)=>{"use strict";var Kx=qe(),zh=$e(),Yh=Au(),Xx=Zr(),Jx=Dh(),Zx=ye(),ew=TypeError,tw=Zx("toPrimitive");Kh.exports=function(a,e){if(!zh(a)||Yh(a))return a;var t=Xx(a,tw),i;if(t){if(e===void 0&&(e="default"),i=Kx(t,a,e),!zh(i)||Yh(i))return i;throw new ew("Can't convert object to primitive value")}return e===void 0&&(e="number"),Jx(a,e)}});var Du=g((k_,Jh)=>{"use strict";var iw=Xh(),rw=Au();Jh.exports=function(a){var e=iw(a,"string");return rw(e)?e:e+""}});var Zs=g((R_,ef)=>{"use strict";var aw=oe(),Zh=$e(),Cu=aw.document,sw=Zh(Cu)&&Zh(Cu.createElement);ef.exports=function(a){return sw?Cu.createElement(a):{}}});var Bu=g((L_,tf)=>{"use strict";var nw=Ue(),ow=pe(),uw=Zs();tf.exports=!nw&&!ow(function(){return Object.defineProperty(uw("div"),"a",{get:function(){return 7}}).a!==7})});var sf=g(af=>{"use strict";var lw=Ue(),cw=qe(),dw=Su(),pw=Yr(),hw=fi(),fw=Du(),mw=st(),bw=Bu(),rf=Object.getOwnPropertyDescriptor;af.f=lw?rf:function(e,t){if(e=hw(e),t=fw(t),bw)try{return rf(e,t)}catch(i){}if(mw(e,t))return pw(!cw(dw.f,e,t),e[t])}});var Vu=g((M_,nf)=>{"use strict";var gw=pe(),Sw=ue(),vw=/#|\.prototype\./,ta=function(a,e){var t=Tw[yw(a)];return t===Ew?!0:t===Iw?!1:Sw(e)?gw(e):!!e},yw=ta.normalize=function(a){return String(a).replace(vw,".").toLowerCase()},Tw=ta.data={},Iw=ta.NATIVE="N",Ew=ta.POLYFILL="P";nf.exports=ta});var Yi=g((D_,uf)=>{"use strict";var of=bu(),xw=ft(),ww=zr(),Aw=of(of.bind);uf.exports=function(a,e){return xw(a),e===void 0?a:ww?Aw(a,e):function(){return a.apply(e,arguments)}}});var _u=g((C_,lf)=>{"use strict";var Pw=Ue(),kw=pe();lf.exports=Pw&&kw(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var mt=g((B_,cf)=>{"use strict";var Rw=$e(),Lw=String,$w=TypeError;cf.exports=function(a){if(Rw(a))return a;throw new $w(Lw(a)+" is not an object")}});var gi=g(pf=>{"use strict";var Mw=Ue(),Dw=Bu(),Cw=_u(),en=mt(),df=Du(),Bw=TypeError,Ou=Object.defineProperty,Vw=Object.getOwnPropertyDescriptor,Fu="enumerable",Nu="configurable",Uu="writable";pf.f=Mw?Cw?function(e,t,i){if(en(e),t=df(t),en(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Uu in i&&!i[Uu]){var r=Vw(e,t);r&&r[Uu]&&(e[t]=i.value,i={configurable:Nu in i?i[Nu]:r[Nu],enumerable:Fu in i?i[Fu]:r[Fu],writable:!1})}return Ou(e,t,i)}:Ou:function(e,t,i){if(en(e),t=df(t),en(i),Dw)try{return Ou(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new Bw("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ki=g((__,hf)=>{"use strict";var _w=Ue(),Ow=gi(),Fw=Yr();hf.exports=_w?function(a,e,t){return Ow.f(a,e,Fw(1,t))}:function(a,e,t){return a[e]=t,a}});var de=g((O_,mf)=>{"use strict";var ia=oe(),Nw=fu(),Uw=bu(),qw=ue(),jw=sf().f,Hw=Vu(),Xi=mi(),Qw=Yi(),Ji=Ki(),ff=st();ea();var Gw=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return Nw(a,this,arguments)};return e.prototype=a.prototype,e};mf.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?ia:r?ia[t]:ia[t]&&ia[t].prototype,o=i?Xi:Xi[t]||Ji(Xi,t,{})[t],u=o.prototype,l,c,d,f,p,h,m,b,S;for(f in e)l=Hw(i?f:t+(r?".":"#")+f,a.forced),c=!l&&n&&ff(n,f),h=o[f],c&&(a.dontCallGetSet?(S=jw(n,f),m=S&&S.value):m=n[f]),p=c&&m?m:e[f],!(!l&&!s&&typeof h==typeof p)&&(a.bind&&c?b=Qw(p,ia):a.wrap&&c?b=Gw(p):s&&qw(p)?b=Uw(p):b=p,(a.sham||p&&p.sham||h&&h.sham)&&Ji(b,"sham",!0),Ji(o,f,b),s&&(d=t+"Prototype",ff(Xi,d)||Ji(Xi,d,{}),Ji(Xi[d],f,p),a.real&&u&&(l||!u[f])&&Ji(u,f,p)))}});var gf=g((F_,bf)=>{"use strict";var Ww=Math.ceil,zw=Math.floor;bf.exports=Math.trunc||function(e){var t=+e;return(t>0?zw:Ww)(t)}});var ra=g((N_,Sf)=>{"use strict";var Yw=gf();Sf.exports=function(a){var e=+a;return e!==e||e===0?0:Yw(e)}});var yf=g((U_,vf)=>{"use strict";var Kw=ra(),Xw=Math.max,Jw=Math.min;vf.exports=function(a,e){var t=Kw(a);return t<0?Xw(t+e,0):Jw(t,e)}});var qu=g((q_,Tf)=>{"use strict";var Zw=ra(),eA=Math.min;Tf.exports=function(a){var e=Zw(a);return e>0?eA(e,9007199254740991):0}});var Zi=g((j_,If)=>{"use strict";var tA=qu();If.exports=function(a){return tA(a.length)}});var ju=g((H_,xf)=>{"use strict";var iA=fi(),rA=yf(),aA=Zi(),Ef=function(a){return function(e,t,i){var r=iA(e),s=aA(r);if(s===0)return!a&&-1;var n=rA(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};xf.exports={includes:Ef(!0),indexOf:Ef(!1)}});var aa=g((Q_,wf)=>{"use strict";wf.exports=function(){}});var Af=g(()=>{"use strict";var sA=de(),nA=ju().includes,oA=pe(),uA=aa(),lA=oA(function(){return!Array(1).includes()});sA({target:"Array",proto:!0,forced:lA},{includes:function(e){return nA(this,e,arguments.length>1?arguments[1]:void 0)}});uA("includes")});var Gt=g((z_,Pf)=>{"use strict";var cA=Pt();Pf.exports=cA});var Rf=g((Y_,kf)=>{"use strict";Af();var dA=Gt();kf.exports=dA("Array","includes")});var $f=g((K_,Lf)=>{"use strict";var pA=Rf();Lf.exports=pA});var Ye=g((X_,Mf)=>{"use strict";var hA=$f();Mf.exports=hA});var an=g((lO,Nf)=>{"use strict";var TA=Lu(),IA=$u(),Ff=TA("keys");Nf.exports=function(a){return Ff[a]||(Ff[a]=IA(a))}});var qf=g((cO,Uf)=>{"use strict";var EA=pe();Uf.exports=!EA(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var sn=g((dO,Hf)=>{"use strict";var xA=st(),wA=ue(),AA=Wi(),PA=an(),kA=qf(),jf=PA("IE_PROTO"),Gu=Object,RA=Gu.prototype;Hf.exports=kA?Gu.getPrototypeOf:function(a){var e=AA(a);if(xA(e,jf))return e[jf];var t=e.constructor;return wA(t)&&e instanceof t?t.prototype:e instanceof Gu?RA:null}});var nn=g((pO,Qf)=>{"use strict";Qf.exports={}});var zf=g((hO,Wf)=>{"use strict";var LA=he(),Wu=st(),$A=fi(),MA=ju().indexOf,DA=nn(),Gf=LA([].push);Wf.exports=function(a,e){var t=$A(a),i=0,r=[],s;for(s in t)!Wu(DA,s)&&Wu(t,s)&&Gf(r,s);for(;e.length>i;)Wu(t,s=e[i++])&&(~MA(r,s)||Gf(r,s));return r}});var zu=g((fO,Yf)=>{"use strict";Yf.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Yu=g((mO,Kf)=>{"use strict";var CA=zf(),BA=zu();Kf.exports=Object.keys||function(e){return CA(e,BA)}});var Ku=g((bO,tm)=>{"use strict";var Jf=Ue(),VA=pe(),Zf=he(),_A=sn(),OA=Yu(),FA=fi(),NA=Su().f,em=Zf(NA),UA=Zf([].push),qA=Jf&&VA(function(){var a=Object.create(null);return a[2]=2,!em(a,2)}),Xf=function(a){return function(e){for(var t=FA(e),i=OA(t),r=qA&&_A(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Jf||(r?u in t:em(t,u)))&&UA(o,a?[u,t[u]]:t[u]);return o}};tm.exports={entries:Xf(!0),values:Xf(!1)}});var im=g(()=>{"use strict";var jA=de(),HA=Ku().entries;jA({target:"Object",stat:!0},{entries:function(e){return HA(e)}})});var am=g((vO,rm)=>{"use strict";im();var QA=mi();rm.exports=QA.Object.entries});var nm=g((yO,sm)=>{"use strict";var GA=am();sm.exports=GA});var er=g((TO,om)=>{"use strict";var WA=nm();om.exports=WA});var Si=g((IO,um)=>{"use strict";um.exports={}});var dm=g((EO,cm)=>{"use strict";var zA=oe(),YA=ue(),lm=zA.WeakMap;cm.exports=YA(lm)&&/native code/.test(String(lm))});var el=g((xO,fm)=>{"use strict";var KA=dm(),hm=oe(),XA=$e(),JA=Ki(),Xu=st(),Ju=ea(),ZA=an(),eP=nn(),pm="Object already initialized",Zu=hm.TypeError,tP=hm.WeakMap,on,sa,un,iP=function(a){return un(a)?sa(a):on(a,{})},rP=function(a){return function(e){var t;if(!XA(e)||(t=sa(e)).type!==a)throw new Zu("Incompatible receiver, "+a+" required");return t}};KA||Ju.state?(nt=Ju.state||(Ju.state=new tP),nt.get=nt.get,nt.has=nt.has,nt.set=nt.set,on=function(a,e){if(nt.has(a))throw new Zu(pm);return e.facade=a,nt.set(a,e),e},sa=function(a){return nt.get(a)||{}},un=function(a){return nt.has(a)}):(vi=ZA("state"),eP[vi]=!0,on=function(a,e){if(Xu(a,vi))throw new Zu(pm);return e.facade=a,JA(a,vi,e),e},sa=function(a){return Xu(a,vi)?a[vi]:{}},un=function(a){return Xu(a,vi)});var nt,vi;fm.exports={set:on,get:sa,has:un,enforce:iP,getterFor:rP}});var rl=g((wO,bm)=>{"use strict";var tl=Ue(),aP=st(),mm=Function.prototype,sP=tl&&Object.getOwnPropertyDescriptor,il=aP(mm,"name"),nP=il&&function(){}.name==="something",oP=il&&(!tl||tl&&sP(mm,"name").configurable);bm.exports={EXISTS:il,PROPER:nP,CONFIGURABLE:oP}});var Sm=g(gm=>{"use strict";var uP=Ue(),lP=_u(),cP=gi(),dP=mt(),pP=fi(),hP=Yu();gm.f=uP&&!lP?Object.defineProperties:function(e,t){dP(e);for(var i=pP(t),r=hP(t),s=r.length,n=0,o;s>n;)cP.f(e,o=r[n++],i[o]);return e}});var al=g((PO,vm)=>{"use strict";var fP=Pt();vm.exports=fP("document","documentElement")});var ul=g((kO,Am)=>{"use strict";var mP=mt(),bP=Sm(),ym=zu(),gP=nn(),SP=al(),vP=Zs(),yP=an(),Tm=">",Im="<",nl="prototype",ol="script",xm=yP("IE_PROTO"),sl=function(){},wm=function(a){return Im+ol+Tm+a+Im+"/"+ol+Tm},Em=function(a){a.write(wm("")),a.close();var e=a.parentWindow.Object;return a=null,e},TP=function(){var a=vP("iframe"),e="java"+ol+":",t;return a.style.display="none",SP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(wm("document.F=Object")),t.close(),t.F},ln,cn=function(){try{ln=new ActiveXObject("htmlfile")}catch(e){}cn=typeof document!="undefined"?document.domain&&ln?Em(ln):TP():Em(ln);for(var a=ym.length;a--;)delete cn[nl][ym[a]];return cn()};gP[xm]=!0;Am.exports=Object.create||function(e,t){var i;return e!==null?(sl[nl]=mP(e),i=new sl,sl[nl]=null,i[xm]=e):i=cn(),t===void 0?i:bP.f(i,t)}});var tr=g((RO,Pm)=>{"use strict";var IP=Ki();Pm.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:IP(a,e,t),a}});var pl=g((LO,Lm)=>{"use strict";var EP=pe(),xP=ue(),wP=$e(),AP=ul(),km=sn(),PP=tr(),kP=ye(),RP=at(),dl=kP("iterator"),Rm=!1,kt,ll,cl;[].keys&&(cl=[].keys(),"next"in cl?(ll=km(km(cl)),ll!==Object.prototype&&(kt=ll)):Rm=!0);var LP=!wP(kt)||EP(function(){var a={};return kt[dl].call(a)!==a});LP?kt={}:RP&&(kt=AP(kt));xP(kt[dl])||PP(kt,dl,function(){return this});Lm.exports={IteratorPrototype:kt,BUGGY_SAFARI_ITERATORS:Rm}});var dn=g(($O,Mm)=>{"use strict";var $P=ye(),MP=$P("toStringTag"),$m={};$m[MP]="z";Mm.exports=String($m)==="[object z]"});var na=g((MO,Dm)=>{"use strict";var DP=dn(),CP=ue(),pn=hi(),BP=ye(),VP=BP("toStringTag"),_P=Object,OP=pn(function(){return arguments}())==="Arguments",FP=function(a,e){try{return a[e]}catch(t){}};Dm.exports=DP?pn:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=FP(e=_P(a),VP))=="string"?t:OP?pn(e):(i=pn(e))==="Object"&&CP(e.callee)?"Arguments":i}});var Bm=g((DO,Cm)=>{"use strict";var NP=dn(),UP=na();Cm.exports=NP?{}.toString:function(){return"[object "+UP(this)+"]"}});var oa=g((CO,_m)=>{"use strict";var qP=dn(),jP=gi().f,HP=Ki(),QP=st(),GP=Bm(),WP=ye(),Vm=WP("toStringTag");_m.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(QP(r,Vm)||jP(r,Vm,{configurable:!0,value:e}),i&&!qP&&HP(r,"toString",GP))}});var Fm=g((BO,Om)=>{"use strict";var zP=pl().IteratorPrototype,YP=ul(),KP=Yr(),XP=oa(),JP=Si(),ZP=function(){return this};Om.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=YP(zP,{next:KP(+!i,t)}),XP(a,r,!1,!0),JP[r]=ZP,a}});var Um=g((VO,Nm)=>{"use strict";var ek=he(),tk=ft();Nm.exports=function(a,e,t){try{return ek(tk(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var jm=g((_O,qm)=>{"use strict";var ik=$e();qm.exports=function(a){return ik(a)||a===null}});var Qm=g((OO,Hm)=>{"use strict";var rk=jm(),ak=String,sk=TypeError;Hm.exports=function(a){if(rk(a))return a;throw new sk("Can't set "+ak(a)+" as a prototype")}});var hl=g((FO,Gm)=>{"use strict";var nk=Um(),ok=$e(),uk=Qt(),lk=Qm();Gm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=nk(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return uk(r),lk(s),ok(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var rb=g((NO,ib)=>{"use strict";var ck=de(),dk=qe(),hn=at(),eb=rl(),pk=ue(),hk=Fm(),Wm=sn(),zm=hl(),fk=oa(),mk=Ki(),fl=tr(),bk=ye(),Ym=Si(),tb=pl(),gk=eb.PROPER,Sk=eb.CONFIGURABLE,Km=tb.IteratorPrototype,fn=tb.BUGGY_SAFARI_ITERATORS,ua=bk("iterator"),Xm="keys",la="values",Jm="entries",Zm=function(){return this};ib.exports=function(a,e,t,i,r,s,n){hk(t,e,i);var o=function(S){if(S===r&&f)return f;if(!fn&&S&&S in c)return c[S];switch(S){case Xm:return function(){return new t(this,S)};case la:return function(){return new t(this,S)};case Jm:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[ua]||c["@@iterator"]||r&&c[r],f=!fn&&d||o(r),p=e==="Array"&&c.entries||d,h,m,b;if(p&&(h=Wm(p.call(new a)),h!==Object.prototype&&h.next&&(!hn&&Wm(h)!==Km&&(zm?zm(h,Km):pk(h[ua])||fl(h,ua,Zm)),fk(h,u,!0,!0),hn&&(Ym[u]=Zm))),gk&&r===la&&d&&d.name!==la&&(!hn&&Sk?mk(c,"name",la):(l=!0,f=function(){return dk(d,this)})),r)if(m={values:o(la),keys:s?f:o(Xm),entries:o(Jm)},n)for(b in m)(fn||l||!(b in c))&&fl(c,b,m[b]);else ck({target:e,proto:!0,forced:fn||l},m);return(!hn||n)&&c[ua]!==f&&fl(c,ua,f,{name:r}),Ym[e]=f,m}});var sb=g((UO,ab)=>{"use strict";ab.exports=function(a,e){return{value:a,done:e}}});var bl=g((qO,cb)=>{"use strict";var vk=fi(),ml=aa(),nb=Si(),ub=el(),yk=gi().f,Tk=rb(),mn=sb(),Ik=at(),Ek=Ue(),lb="Array Iterator",xk=ub.set,wk=ub.getterFor(lb);cb.exports=Tk(Array,"Array",function(a,e){xk(this,{type:lb,target:vk(a),index:0,kind:e})},function(){var a=wk(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,mn(void 0,!0);switch(a.kind){case"keys":return mn(t,!1);case"values":return mn(e[t],!1)}return mn([t,e[t]],!1)},"values");var ob=nb.Arguments=nb.Array;ml("keys");ml("values");ml("entries");if(!Ik&&Ek&&ob.name!=="values")try{yk(ob,"name",{value:"values"})}catch(a){}});var pb=g((jO,db)=>{"use strict";var Ak=ye(),Pk=Si(),kk=Ak("iterator"),Rk=Array.prototype;db.exports=function(a){return a!==void 0&&(Pk.Array===a||Rk[kk]===a)}});var gl=g((HO,fb)=>{"use strict";var Lk=na(),hb=Zr(),$k=Kr(),Mk=Si(),Dk=ye(),Ck=Dk("iterator");fb.exports=function(a){if(!$k(a))return hb(a,Ck)||hb(a,"@@iterator")||Mk[Lk(a)]}});var bb=g((QO,mb)=>{"use strict";var Bk=qe(),Vk=ft(),_k=mt(),Ok=Jr(),Fk=gl(),Nk=TypeError;mb.exports=function(a,e){var t=arguments.length<2?Fk(a):e;if(Vk(t))return _k(Bk(t,a));throw new Nk(Ok(a)+" is not iterable")}});var vb=g((GO,Sb)=>{"use strict";var Uk=qe(),gb=mt(),qk=Zr();Sb.exports=function(a,e,t){var i,r;gb(a);try{if(i=qk(a,"return"),!i){if(e==="throw")throw t;return t}i=Uk(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return gb(i),t}});var gn=g((WO,Eb)=>{"use strict";var jk=Yi(),Hk=qe(),Qk=mt(),Gk=Jr(),Wk=pb(),zk=Zi(),yb=Xr(),Yk=bb(),Kk=gl(),Tb=vb(),Xk=TypeError,bn=function(a,e){this.stopped=a,this.result=e},Ib=bn.prototype;Eb.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=jk(e,i),l,c,d,f,p,h,m,b=function(y){return l&&Tb(l,"normal"),new bn(!0,y)},S=function(y){return r?(Qk(y),o?u(y[0],y[1],b):u(y[0],y[1])):o?u(y,b):u(y)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Kk(a),!c)throw new Xk(Gk(a)+" is not iterable");if(Wk(c)){for(d=0,f=zk(a);f>d;d++)if(p=S(a[d]),p&&yb(Ib,p))return p;return new bn(!1)}l=Yk(a,c)}for(h=s?a.next:l.next;!(m=Hk(h,l)).done;){try{p=S(m.value)}catch(y){Tb(l,"throw",y)}if(typeof p=="object"&&p&&yb(Ib,p))return p}return new bn(!1)}});var wb=g((zO,xb)=>{"use strict";var Jk=Ue(),Zk=gi(),eR=Yr();xb.exports=function(a,e,t){Jk?Zk.f(a,e,eR(0,t)):a[e]=t}});var Ab=g(()=>{"use strict";var tR=de(),iR=gn(),rR=wb();tR({target:"Object",stat:!0},{fromEntries:function(e){var t={};return iR(e,function(i,r){rR(t,i,r)},{AS_ENTRIES:!0}),t}})});var kb=g((XO,Pb)=>{"use strict";bl();Ab();var aR=mi();Pb.exports=aR.Object.fromEntries});var Lb=g((JO,Rb)=>{"use strict";Rb.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Mb=g(()=>{"use strict";bl();var sR=Lb(),nR=oe(),oR=oa(),$b=Si();for(Sn in sR)oR(nR[Sn],Sn),$b[Sn]=$b.Array;var Sn});var Cb=g((tF,Db)=>{"use strict";var uR=kb();Mb();Db.exports=uR});var Sl=g((iF,Bb)=>{"use strict";var lR=Cb();Bb.exports=lR});var Vb=g(()=>{"use strict"});var vl=g((sF,_b)=>{"use strict";var ca=oe(),cR=bi(),dR=hi(),vn=function(a){return cR.slice(0,a.length)===a};_b.exports=function(){return vn("Bun/")?"BUN":vn("Cloudflare-Workers")?"CLOUDFLARE":vn("Deno/")?"DENO":vn("Node.js/")?"NODE":ca.Bun&&typeof Bun.version=="string"?"BUN":ca.Deno&&typeof Deno.version=="object"?"DENO":dR(ca.process)==="process"?"NODE":ca.window&&ca.document?"BROWSER":"REST"}()});var yn=g((nF,Ob)=>{"use strict";var pR=vl();Ob.exports=pR==="NODE"});var Nb=g((oF,Fb)=>{"use strict";var hR=gi();Fb.exports=function(a,e,t){return hR.f(a,e,t)}});var jb=g((uF,qb)=>{"use strict";var fR=Pt(),mR=Nb(),bR=ye(),gR=Ue(),Ub=bR("species");qb.exports=function(a){var e=fR(a);gR&&e&&!e[Ub]&&mR(e,Ub,{configurable:!0,get:function(){return this}})}});var Qb=g((lF,Hb)=>{"use strict";var SR=Xr(),vR=TypeError;Hb.exports=function(a,e){if(SR(e,a))return a;throw new vR("Incorrect invocation")}});var Tl=g((cF,Gb)=>{"use strict";var yR=he(),TR=ue(),yl=ea(),IR=yR(Function.toString);TR(yl.inspectSource)||(yl.inspectSource=function(a){return IR(a)});Gb.exports=yl.inspectSource});var El=g((dF,Xb)=>{"use strict";var ER=he(),xR=pe(),Wb=ue(),wR=na(),AR=Pt(),PR=Tl(),zb=function(){},Yb=AR("Reflect","construct"),Il=/^\s*(?:class|function)\b/,kR=ER(Il.exec),RR=!Il.test(zb),da=function(e){if(!Wb(e))return!1;try{return Yb(zb,[],e),!0}catch(t){return!1}},Kb=function(e){if(!Wb(e))return!1;switch(wR(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return RR||!!kR(Il,PR(e))}catch(t){return!0}};Kb.sham=!0;Xb.exports=!Yb||xR(function(){var a;return da(da.call)||!da(Object)||!da(function(){a=!0})||a})?Kb:da});var Zb=g((pF,Jb)=>{"use strict";var LR=El(),$R=Jr(),MR=TypeError;Jb.exports=function(a){if(LR(a))return a;throw new MR($R(a)+" is not a constructor")}});var xl=g((hF,tg)=>{"use strict";var eg=mt(),DR=Zb(),CR=Kr(),BR=ye(),VR=BR("species");tg.exports=function(a,e){var t=eg(a).constructor,i;return t===void 0||CR(i=eg(t)[VR])?e:DR(i)}});var rg=g((fF,ig)=>{"use strict";var _R=he();ig.exports=_R([].slice)});var sg=g((mF,ag)=>{"use strict";var OR=TypeError;ag.exports=function(a,e){if(a<e)throw new OR("Not enough arguments");return a}});var wl=g((bF,ng)=>{"use strict";var FR=bi();ng.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(FR)});var Cl=g((gF,mg)=>{"use strict";var je=oe(),NR=fu(),UR=Yi(),og=ue(),qR=st(),fg=pe(),ug=al(),jR=rg(),lg=Zs(),HR=sg(),QR=wl(),GR=yn(),$l=je.setImmediate,Ml=je.clearImmediate,WR=je.process,Al=je.Dispatch,zR=je.Function,cg=je.MessageChannel,YR=je.String,Pl=0,pa={},dg="onreadystatechange",ha,yi,kl,Rl;fg(function(){ha=je.location});var Dl=function(a){if(qR(pa,a)){var e=pa[a];delete pa[a],e()}},Ll=function(a){return function(){Dl(a)}},pg=function(a){Dl(a.data)},hg=function(a){je.postMessage(YR(a),ha.protocol+"//"+ha.host)};(!$l||!Ml)&&($l=function(e){HR(arguments.length,1);var t=og(e)?e:zR(e),i=jR(arguments,1);return pa[++Pl]=function(){NR(t,void 0,i)},yi(Pl),Pl},Ml=function(e){delete pa[e]},GR?yi=function(a){WR.nextTick(Ll(a))}:Al&&Al.now?yi=function(a){Al.now(Ll(a))}:cg&&!QR?(kl=new cg,Rl=kl.port2,kl.port1.onmessage=pg,yi=UR(Rl.postMessage,Rl)):je.addEventListener&&og(je.postMessage)&&!je.importScripts&&ha&&ha.protocol!=="file:"&&!fg(hg)?(yi=hg,je.addEventListener("message",pg,!1)):dg in lg("script")?yi=function(a){ug.appendChild(lg("script"))[dg]=function(){ug.removeChild(this),Dl(a)}}:yi=function(a){setTimeout(Ll(a),0)});mg.exports={set:$l,clear:Ml}});var Sg=g((SF,gg)=>{"use strict";var bg=oe(),KR=Ue(),XR=Object.getOwnPropertyDescriptor;gg.exports=function(a){if(!KR)return bg[a];var e=XR(bg,a);return e&&e.value}});var Bl=g((vF,yg)=>{"use strict";var vg=function(){this.head=null,this.tail=null};vg.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};yg.exports=vg});var Ig=g((yF,Tg)=>{"use strict";var JR=bi();Tg.exports=/ipad|iphone|ipod/i.test(JR)&&typeof Pebble!="undefined"});var xg=g((TF,Eg)=>{"use strict";var ZR=bi();Eg.exports=/web0s(?!.*chrome)/i.test(ZR)});var $g=g((IF,Lg)=>{"use strict";var rr=oe(),eL=Sg(),wg=Yi(),Vl=Cl().set,tL=Bl(),iL=wl(),rL=Ig(),aL=xg(),_l=yn(),Ag=rr.MutationObserver||rr.WebKitMutationObserver,Pg=rr.document,kg=rr.process,Tn=rr.Promise,Nl=eL("queueMicrotask"),ir,Ol,Fl,In,Rg;Nl||(fa=new tL,ma=function(){var a,e;for(_l&&(a=kg.domain)&&a.exit();e=fa.get();)try{e()}catch(t){throw fa.head&&ir(),t}a&&a.enter()},!iL&&!_l&&!aL&&Ag&&Pg?(Ol=!0,Fl=Pg.createTextNode(""),new Ag(ma).observe(Fl,{characterData:!0}),ir=function(){Fl.data=Ol=!Ol}):!rL&&Tn&&Tn.resolve?(In=Tn.resolve(void 0),In.constructor=Tn,Rg=wg(In.then,In),ir=function(){Rg(ma)}):_l?ir=function(){kg.nextTick(ma)}:(Vl=wg(Vl,rr),ir=function(){Vl(ma)}),Nl=function(a){fa.head||ir(),fa.add(a)});var fa,ma;Lg.exports=Nl});var Dg=g((EF,Mg)=>{"use strict";Mg.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var En=g((xF,Cg)=>{"use strict";Cg.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ti=g((wF,Bg)=>{"use strict";var sL=oe();Bg.exports=sL.Promise});var ar=g((AF,Fg)=>{"use strict";var nL=oe(),ba=Ti(),oL=ue(),uL=Vu(),lL=Tl(),cL=ye(),Vg=vl(),dL=at(),Ul=Eu(),_g=ba&&ba.prototype,pL=cL("species"),ql=!1,Og=oL(nL.PromiseRejectionEvent),hL=uL("Promise",function(){var a=lL(ba),e=a!==String(ba);if(!e&&Ul===66||dL&&!(_g.catch&&_g.finally))return!0;if(!Ul||Ul<51||!/native code/.test(a)){var t=new ba(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[pL]=i,ql=t.then(function(){})instanceof i,!ql)return!0}return!e&&(Vg==="BROWSER"||Vg==="DENO")&&!Og});Fg.exports={CONSTRUCTOR:hL,REJECTION_EVENT:Og,SUBCLASSING:ql}});var sr=g((PF,Ug)=>{"use strict";var Ng=ft(),fL=TypeError,mL=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new fL("Bad Promise constructor");e=i,t=r}),this.resolve=Ng(e),this.reject=Ng(t)};Ug.exports.f=function(a){return new mL(a)}});var oS=g(()=>{"use strict";var bL=de(),gL=at(),Pn=yn(),Wt=oe(),SL=mi(),lr=qe(),qg=tr(),jg=hl(),vL=oa(),yL=jb(),TL=ft(),An=ue(),IL=$e(),EL=Qb(),xL=xl(),zg=Cl().set,Wl=$g(),wL=Dg(),AL=En(),PL=Bl(),Yg=el(),kn=Ti(),zl=ar(),Kg=sr(),Rn="Promise",Xg=zl.CONSTRUCTOR,kL=zl.REJECTION_EVENT,RL=zl.SUBCLASSING,jl=Yg.getterFor(Rn),LL=Yg.set,nr=kn&&kn.prototype,Ii=kn,xn=nr,Jg=Wt.TypeError,Hl=Wt.document,Yl=Wt.process,Ql=Kg.f,$L=Ql,ML=!!(Hl&&Hl.createEvent&&Wt.dispatchEvent),Zg="unhandledrejection",DL="rejectionhandled",Hg=0,eS=1,CL=2,Kl=1,tS=2,wn,Qg,iS,Gg,rS=function(a){var e;return IL(a)&&An(e=a.then)?e:!1},aS=function(a,e){var t=e.value,i=e.state===eS,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===tS&&VL(e),e.rejection=Kl),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Jg("Promise-chain cycle")):(l=rS(u))?lr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},sS=function(a,e){a.notified||(a.notified=!0,Wl(function(){for(var t=a.reactions,i;i=t.get();)aS(i,a);a.notified=!1,e&&!a.rejection&&BL(a)}))},nS=function(a,e,t){var i,r;ML?(i=Hl.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Wt.dispatchEvent(i)):i={promise:e,reason:t},!kL&&(r=Wt["on"+a])?r(i):a===Zg&&wL("Unhandled promise rejection",t)},BL=function(a){lr(zg,Wt,function(){var e=a.facade,t=a.value,i=Wg(a),r;if(i&&(r=AL(function(){Pn?Yl.emit("unhandledRejection",t,e):nS(Zg,e,t)}),a.rejection=Pn||Wg(a)?tS:Kl,r.error))throw r.value})},Wg=function(a){return a.rejection!==Kl&&!a.parent},VL=function(a){lr(zg,Wt,function(){var e=a.facade;Pn?Yl.emit("rejectionHandled",e):nS(DL,e,a.value)})},or=function(a,e,t){return function(i){a(e,i,t)}},ur=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=CL,sS(a,!0))},Gl=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Jg("Promise can't be resolved itself");var i=rS(e);i?Wl(function(){var r={done:!1};try{lr(i,e,or(Gl,r,a),or(ur,r,a))}catch(s){ur(r,s,a)}}):(a.value=e,a.state=eS,sS(a,!1))}catch(r){ur({done:!1},r,a)}}};if(Xg&&(Ii=function(e){EL(this,xn),TL(e),lr(wn,this);var t=jl(this);try{e(or(Gl,t),or(ur,t))}catch(i){ur(t,i)}},xn=Ii.prototype,wn=function(e){LL(this,{type:Rn,done:!1,notified:!1,parent:!1,reactions:new PL,rejection:!1,state:Hg,value:null})},wn.prototype=qg(xn,"then",function(e,t){var i=jl(this),r=Ql(xL(this,Ii));return i.parent=!0,r.ok=An(e)?e:!0,r.fail=An(t)&&t,r.domain=Pn?Yl.domain:void 0,i.state===Hg?i.reactions.add(r):Wl(function(){aS(r,i)}),r.promise}),Qg=function(){var a=new wn,e=jl(a);this.promise=a,this.resolve=or(Gl,e),this.reject=or(ur,e)},Kg.f=Ql=function(a){return a===Ii||a===iS?new Qg(a):$L(a)},!gL&&An(kn)&&nr!==Object.prototype)){Gg=nr.then,RL||qg(nr,"then",function(e,t){var i=this;return new Ii(function(r,s){lr(Gg,i,r,s)}).then(e,t)},{unsafe:!0});try{delete nr.constructor}catch(a){}jg&&jg(nr,xn)}bL({global:!0,constructor:!0,wrap:!0,forced:Xg},{Promise:Ii});iS=SL.Promise;vL(Ii,Rn,!1,!0);yL(Rn)});var pS=g((LF,dS)=>{"use strict";var _L=ye(),lS=_L("iterator"),cS=!1;try{uS=0,Xl={next:function(){return{done:!!uS++}},return:function(){cS=!0}},Xl[lS]=function(){return this},Array.from(Xl,function(){throw 2})}catch(a){}var uS,Xl;dS.exports=function(a,e){try{if(!e&&!cS)return!1}catch(r){return!1}var t=!1;try{var i={};i[lS]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Jl=g(($F,hS)=>{"use strict";var OL=Ti(),FL=pS(),NL=ar().CONSTRUCTOR;hS.exports=NL||!FL(function(a){OL.all(a).then(void 0,function(){})})});var fS=g(()=>{"use strict";var UL=de(),qL=qe(),jL=ft(),HL=sr(),QL=En(),GL=gn(),WL=Jl();UL({target:"Promise",stat:!0,forced:WL},{all:function(e){var t=this,i=HL.f(t),r=i.resolve,s=i.reject,n=QL(function(){var o=jL(t.resolve),u=[],l=0,c=1;GL(e,function(d){var f=l++,p=!1;c++,qL(o,t,d).then(function(h){p||(p=!0,u[f]=h,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var bS=g(()=>{"use strict";var zL=de(),YL=at(),KL=ar().CONSTRUCTOR,ec=Ti(),XL=Pt(),JL=ue(),ZL=tr(),mS=ec&&ec.prototype;zL({target:"Promise",proto:!0,forced:KL,real:!0},{catch:function(a){return this.then(void 0,a)}});!YL&&JL(ec)&&(Zl=XL("Promise").prototype.catch,mS.catch!==Zl&&ZL(mS,"catch",Zl,{unsafe:!0}));var Zl});var gS=g(()=>{"use strict";var e$=de(),t$=qe(),i$=ft(),r$=sr(),a$=En(),s$=gn(),n$=Jl();e$({target:"Promise",stat:!0,forced:n$},{race:function(e){var t=this,i=r$.f(t),r=i.reject,s=a$(function(){var n=i$(t.resolve);s$(e,function(o){t$(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var SS=g(()=>{"use strict";var o$=de(),u$=sr(),l$=ar().CONSTRUCTOR;o$({target:"Promise",stat:!0,forced:l$},{reject:function(e){var t=u$.f(this),i=t.reject;return i(e),t.promise}})});var tc=g((NF,vS)=>{"use strict";var c$=mt(),d$=$e(),p$=sr();vS.exports=function(a,e){if(c$(a),d$(e)&&e.constructor===a)return e;var t=p$.f(a),i=t.resolve;return i(e),t.promise}});var IS=g(()=>{"use strict";var h$=de(),f$=Pt(),yS=at(),m$=Ti(),TS=ar().CONSTRUCTOR,b$=tc(),g$=f$("Promise"),S$=yS&&!TS;h$({target:"Promise",stat:!0,forced:yS||TS},{resolve:function(e){return b$(S$&&this===g$?m$:this,e)}})});var ES=g(()=>{"use strict";oS();fS();bS();gS();SS();IS()});var PS=g(()=>{"use strict";var v$=de(),y$=at(),Ln=Ti(),T$=pe(),wS=Pt(),AS=ue(),I$=xl(),xS=tc(),E$=tr(),rc=Ln&&Ln.prototype,x$=!!Ln&&T$(function(){rc.finally.call({then:function(){}},function(){})});v$({target:"Promise",proto:!0,real:!0,forced:x$},{finally:function(a){var e=I$(this,wS("Promise")),t=AS(a);return this.then(t?function(i){return xS(e,a()).then(function(){return i})}:a,t?function(i){return xS(e,a()).then(function(){throw i})}:a)}});!y$&&AS(Ln)&&(ic=wS("Promise").prototype.finally,rc.finally!==ic&&E$(rc,"finally",ic,{unsafe:!0}));var ic});var RS=g((WF,kS)=>{"use strict";Vb();ES();PS();var w$=Gt();kS.exports=w$("Promise","finally")});var $S=g((zF,LS)=>{"use strict";var A$=RS();LS.exports=A$});var $n=g((YF,MS)=>{"use strict";var P$=$S();MS.exports=P$});var XS=g(()=>{"use strict";var z$=de(),Y$=Ku().values;z$({target:"Object",stat:!0},{values:function(e){return Y$(e)}})});var ZS=g((hU,JS)=>{"use strict";XS();var K$=mi();JS.exports=K$.Object.values});var tv=g((fU,ev)=>{"use strict";var X$=ZS();ev.exports=X$});var pr=g((mU,iv)=>{"use strict";var J$=tv();iv.exports=J$});var hv=g(()=>{"use strict";var fM=de(),mM=Wi(),bM=Zi(),gM=ra(),SM=aa();fM({target:"Array",proto:!0},{at:function(e){var t=mM(this),i=bM(t),r=gM(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});SM("at")});var mv=g((QU,fv)=>{"use strict";hv();var vM=Gt();fv.exports=vM("Array","at")});var gv=g((GU,bv)=>{"use strict";var yM=mv();bv.exports=yM});var ot=g((WU,Sv)=>{"use strict";var TM=gv();Sv.exports=TM});var kc=g((O1,Zv)=>{"use strict";var tD=hi();Zv.exports=Array.isArray||function(e){return tD(e)==="Array"}});var ty=g((F1,ey)=>{"use strict";var iD=TypeError,rD=9007199254740991;ey.exports=function(a){if(a>rD)throw iD("Maximum allowed index exceeded");return a}});var ay=g((N1,ry)=>{"use strict";var aD=kc(),sD=Zi(),nD=ty(),oD=Yi(),iy=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?oD(n,o):!1,d,f;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&aD(d)?(f=sD(d),u=iy(a,e,d,f,u,s-1)-1):(nD(u+1),a[u]=d),u++),l++;return u};ry.exports=iy});var uy=g((U1,oy)=>{"use strict";var sy=kc(),uD=El(),lD=$e(),cD=ye(),dD=cD("species"),ny=Array;oy.exports=function(a){var e;return sy(a)&&(e=a.constructor,uD(e)&&(e===ny||sy(e.prototype))?e=void 0:lD(e)&&(e=e[dD],e===null&&(e=void 0))),e===void 0?ny:e}});var cy=g((q1,ly)=>{"use strict";var pD=uy();ly.exports=function(a,e){return new(pD(a))(e===0?0:e)}});var dy=g(()=>{"use strict";var hD=de(),fD=ay(),mD=ft(),bD=Wi(),gD=Zi(),SD=cy();hD({target:"Array",proto:!0},{flatMap:function(e){var t=bD(this),i=gD(t),r;return mD(e),r=SD(t,0),r.length=fD(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var py=g(()=>{"use strict";var vD=aa();vD("flatMap")});var fy=g((W1,hy)=>{"use strict";dy();py();var yD=Gt();hy.exports=yD("Array","flatMap")});var by=g((z1,my)=>{"use strict";var TD=fy();my.exports=TD});var Ma=g((Y1,gy)=>{"use strict";var ID=by();gy.exports=ID});var Da=g((K1,Sy)=>{"use strict";var ED=na(),xD=String;Sy.exports=function(a){if(ED(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return xD(a)}});var Rc=g((X1,vy)=>{"use strict";vy.exports=`
7
+ \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Iy=g((J1,Ty)=>{"use strict";var wD=he(),AD=Qt(),PD=Da(),$c=Rc(),yy=wD("".replace),kD=RegExp("^["+$c+"]+"),RD=RegExp("(^|[^"+$c+"])["+$c+"]+$"),Lc=function(a){return function(e){var t=PD(AD(e));return a&1&&(t=yy(t,kD,"")),a&2&&(t=yy(t,RD,"$1")),t}};Ty.exports={start:Lc(1),end:Lc(2),trim:Lc(3)}});var Ay=g((Z1,wy)=>{"use strict";var LD=rl().PROPER,$D=pe(),Ey=Rc(),xy="\u200B\x85\u180E";wy.exports=function(a){return $D(function(){return!!Ey[a]()||xy[a]()!==xy||LD&&Ey[a].name!==a})}});var Mc=g((ej,Py)=>{"use strict";var MD=Iy().start,DD=Ay();Py.exports=DD("trimStart")?function(){return MD(this)}:"".trimStart});var Ry=g(()=>{"use strict";var CD=de(),ky=Mc();CD({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==ky},{trimLeft:ky})});var $y=g(()=>{"use strict";Ry();var BD=de(),Ly=Mc();BD({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Ly},{trimStart:Ly})});var Dy=g((sj,My)=>{"use strict";$y();var VD=Gt();My.exports=VD("String","trimLeft")});var By=g((nj,Cy)=>{"use strict";var _D=Dy();Cy.exports=_D});var _y=g((oj,Vy)=>{"use strict";var OD=By();Vy.exports=OD});var Zy=g(()=>{"use strict"});var eT=g(()=>{"use strict"});var iT=g((WQ,tT)=>{"use strict";var uC=$e(),lC=hi(),cC=ye(),dC=cC("match");tT.exports=function(a){var e;return uC(a)&&((e=a[dC])!==void 0?!!e:lC(a)==="RegExp")}});var sT=g((zQ,aT)=>{"use strict";var pC=oe(),hC=pe(),rT=pC.RegExp,fC=!hC(function(){var a=!0;try{rT(".","d")}catch(u){a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(rT.prototype,"flags").get.call(e);return o!==i||t!==i});aT.exports={correct:fC}});var oT=g((YQ,nT)=>{"use strict";var mC=mt();nT.exports=function(){var a=mC(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var cT=g((KQ,lT)=>{"use strict";var bC=qe(),gC=st(),SC=Xr(),uT=sT(),vC=oT(),yC=RegExp.prototype;lT.exports=uT.correct?function(a){return a.flags}:function(a){return!uT.correct&&SC(yC,a)&&!gC(a,"flags")?bC(vC,a):a.flags}});var pT=g((XQ,dT)=>{"use strict";var _c=he(),TC=Wi(),IC=Math.floor,Bc=_c("".charAt),EC=_c("".replace),Vc=_c("".slice),xC=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,wC=/\$([$&'`]|\d{1,2})/g;dT.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=wC;return r!==void 0&&(r=TC(r),u=xC),EC(s,u,function(l,c){var d;switch(Bc(c,0)){case"$":return"$";case"&":return a;case"`":return Vc(e,0,t);case"'":return Vc(e,n);case"<":d=r[Vc(c,1,-1)];break;default:var f=+c;if(f===0)return l;if(f>o){var p=IC(f/10);return p===0?l:p<=o?i[p-1]===void 0?Bc(c,1):i[p-1]+Bc(c,1):l}d=i[f-1]}return d===void 0?"":d})}});var mT=g(()=>{"use strict";var AC=de(),PC=qe(),Fc=he(),hT=Qt(),kC=ue(),RC=$e(),LC=iT(),xr=Da(),$C=Zr(),MC=cT(),DC=pT(),CC=ye(),BC=at(),VC=CC("replace"),_C=TypeError,Oc=Fc("".indexOf),OC=Fc("".replace),fT=Fc("".slice),FC=Math.max;AC({target:"String",proto:!0},{replaceAll:function(e,t){var i=hT(this),r,s,n,o,u,l,c,d,f,p,h=0,m="";if(RC(e)){if(r=LC(e),r&&(s=xr(hT(MC(e))),!~Oc(s,"g")))throw new _C("`.replaceAll` does not allow non-global regexes");if(n=$C(e,VC),n)return PC(n,e,i,t);if(BC&&r)return OC(xr(i),e,t)}for(o=xr(i),u=xr(e),l=kC(t),l||(t=xr(t)),c=u.length,d=FC(1,c),f=Oc(o,u);f!==-1;)p=l?xr(t(u,f,o)):DC(u,o,f,[],void 0,t),m+=fT(o,h,f)+p,h=f+c,f=f+d>o.length?-1:Oc(o,u,f+d);return h<o.length&&(m+=fT(o,h)),m}})});var gT=g((eG,bT)=>{"use strict";Zy();eT();mT();var NC=Gt();bT.exports=NC("String","replaceAll")});var vT=g((tG,ST)=>{"use strict";var UC=gT();ST.exports=UC});var TT=g((iG,yT)=>{"use strict";var qC=vT();yT.exports=qC});var ET=g((rG,IT)=>{"use strict";var jC=ra(),HC=Da(),QC=Qt(),GC=RangeError;IT.exports=function(e){var t=HC(QC(this)),i="",r=jC(e);if(r<0||r===1/0)throw new GC("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var kT=g((aG,PT)=>{"use strict";var AT=he(),WC=qu(),xT=Da(),zC=ET(),YC=Qt(),KC=AT(zC),XC=AT("".slice),JC=Math.ceil,wT=function(a){return function(e,t,i){var r=xT(YC(e)),s=WC(t),n=r.length,o=i===void 0?" ":xT(i),u,l;return s<=n||o===""?r:(u=s-n,l=KC(o,JC(u/o.length)),l.length>u&&(l=XC(l,0,u)),a?r+l:l+r)}};PT.exports={start:wT(!1),end:wT(!0)}});var LT=g((sG,RT)=>{"use strict";var ZC=bi();RT.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(ZC)});var $T=g(()=>{"use strict";var eB=de(),tB=kT().start,iB=LT();eB({target:"String",proto:!0,forced:iB},{padStart:function(e){return tB(this,e,arguments.length>1?arguments[1]:void 0)}})});var DT=g((uG,MT)=>{"use strict";$T();var rB=Gt();MT.exports=rB("String","padStart")});var BT=g((lG,CT)=>{"use strict";var aB=DT();CT.exports=aB});var _T=g((cG,VT)=>{"use strict";var sB=BT();VT.exports=sB});var Fp="2.0.136-dev.e1130126.0";var Le=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Le||{}),At=(v=>(v.MPEG="MPEG",v.DASH="DASH",v.DASH_SEP="DASH_SEP",v.DASH_SEP_VK="DASH_SEP",v.DASH_WEBM="DASH_WEBM",v.DASH_WEBM_AV1="DASH_WEBM_AV1",v.DASH_STREAMS="DASH_STREAMS",v.DASH_WEBM_VK="DASH_WEBM",v.DASH_ONDEMAND="DASH_ONDEMAND",v.DASH_ONDEMAND_VK="DASH_ONDEMAND",v.DASH_LIVE="DASH_LIVE",v.DASH_LIVE_CMAF="DASH_LIVE_CMAF",v.DASH_LIVE_WEBM="DASH_LIVE_WEBM",v.HLS="HLS",v.HLS_ONDEMAND="HLS_ONDEMAND",v.HLS_JS="HLS",v.HLS_LIVE="HLS_LIVE",v.HLS_LIVE_CMAF="HLS_LIVE_CMAF",v.WEB_RTC_LIVE="WEB_RTC_LIVE",v))(At||{});var Ys=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ys||{}),du=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(du||{});var pu=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(pu||{}),Ks=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Ks||{});var DE=O(Ye(),1);import{assertNever as Of,assertNonNullable as fA,isNonNullable as tn,ValueSubject as Hu,Subject as mA,Subscription as bA,merge as gA,observableFrom as SA,fromEvent as Cf,map as Bf,tap as Vf,filterChanged as vA,isNullable as Qu,ErrorCategory as _f}from"@vkontakte/videoplayer-shared/es2018";var Df=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var rn=class{constructor(e){this.connection$=new Hu(void 0);this.castState$=new Hu("NOT_AVAILABLE");this.errorEvent$=new mA;this.realCastState$=new Hu("NOT_AVAILABLE");this.subscription=new bA;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=tn((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||Df("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_f.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){tn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Qu(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Qu(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Cf(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Of(r.sessionState)}})).add(gA(Cf(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Vf(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Bf(r=>r.castState)),SA([i.getCastState()])).pipe(vA(),Bf(yA),Vf(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=tn(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();fA(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Qu(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?tn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:_f.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},yA=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Of(a)}};var Gd=O(Ye(),1),fE=O(er(),1),mE=O(Sl(),1);var zS=O($n(),1);import{assertNever as DS}from"@vkontakte/videoplayer-shared/es2018";var le=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:DS(t)}return a},zt=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:DS(e)}};var $=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as k$,Subject as Mn,merge as CS}from"@vkontakte/videoplayer-shared/es2018";var q=class{constructor(e){this.transitionStarted$=new Mn;this.transitionEnded$=new Mn;this.transitionUpdated$=new Mn;this.forceChanged$=new Mn;this.stateChangeStarted$=CS(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=CS(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||k$(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as US}from"@vkontakte/videoplayer-shared/es2018";var Dn=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var BS=O(Ye(),1);var ga=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var Cn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,BS.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=ga()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e!=null&&e.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Bn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var He=()=>window.ManagedMediaSource||window.MediaSource,cr=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},VS=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Vn=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var R$=document.createElement("video"),L$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',$$='video/mp4; codecs="hev1.1.6.L93.B0"',_S='video/webm; codecs="vp09.00.10.08"',OS='video/webm; codecs="av01.0.00M.08"',M$='audio/mp4; codecs="mp4a.40.2"',D$='audio/webm; codecs="opus"',FS,C$=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:OS}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:_S}})]);FS={DASH_WEBM_AV1:e,DASH_WEBM:t}};C$().catch(a=>{console.log(R$),console.error(a)});var _n=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return FS}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,f,p,h,m,b,S,y,v,I;this._video=document.createElement("video");try{this._protocols={mms:cr(),mse:VS(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let E=!!((c=(l=He())==null?void 0:l.isTypeSupported)!=null&&c.call(l,L$)),A=!!((f=(d=He())==null?void 0:d.isTypeSupported)!=null&&f.call(d,$$)),M=!!((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,M$));this._codecs={h264:E,h265:A,vp9:!!((b=(m=He())==null?void 0:m.isTypeSupported)!=null&&b.call(m,_S)),av1:!!((y=(S=He())==null?void 0:S.isTypeSupported)!=null&&y.call(S,OS)),aac:M,opus:!!((I=(v=He())==null?void 0:v.isTypeSupported)!=null&&I.call(v,D$)),mpeg:(E||A)&&M},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(E){console.error(E)}try{this.destroyVideoElement()}catch(E){console.error("Error destroying video element:",E)}}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var NS="audio/mpeg",On=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,NS))},this._codecs={mp3:!!((r=(i=He())==null?void 0:i.isTypeSupported)!=null&&r.call(i,NS))}}catch(s){console.error(s)}try{this.destroyAudioElement()}catch(s){console.error("Error destroying audio element:",s)}}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as B$}from"@vkontakte/videoplayer-shared/es2018";var ac=class{constructor(){this.isInited$=new B$(!1);this._displayChecker=new Bn,this._deviceChecker=new Cn(this._displayChecker),this._browserChecker=new Dn,this._videoChecker=new _n(this._deviceChecker,this._browserChecker),this._audioChecker=new On,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},F=new ac;var sc=(a,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:n}=F.video,o=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return a.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return u&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return US(l)}})},nc=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return US(a)}},V$=(a,e)=>{let i=Object.keys(a).filter(r=>!nc(r));return sc(i,e).length>0};import{assertNever as dr,assertNonNullable as Ei,debounce as qS,ErrorCategory as jS,fromEvent as xi,isNonNullable as HS,map as QS,merge as GS,observableFrom as _$,Subject as O$,Subscription as oc,timeout as F$,getHighestQuality as N$}from"@vkontakte/videoplayer-shared/es2018";var U$=5,q$=5,j$=500,WS=7e3,Sa=class{constructor(e){this.subscription=new oc;this.loadMediaTimeoutSubscription=new oc;this.videoState=new q("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:dr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:dr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:dr(e)}break}default:dr(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(nc(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new oc;this.subscription.add(e),this.subscription.add(GS(this.videoState.stateChangeStarted$.pipe(QS(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(QS(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new O$;e.add(r.pipe(qS(j$)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>U$)&&r.next(o),s=o})),e.add(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<q$&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),$(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:dr(n)}}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(xi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=GS(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,_$(["init"])).pipe(qS(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),$(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),$(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&$(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];Ei(c);let d=N$(Object.keys(c));Ei(d);let f=c[d];Ei(f),i=f,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Ei(c),i=c.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];Ei(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Ei(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Ei(c),i=le(c.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:jS.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return dr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return HS(o)&&(n.metadata.title=o),HS(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(F$(WS).subscribe(()=>s(`timeout(${WS})`)))});(0,zS.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:jS.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Ac=O(Ye(),1);import{clearVideoElement as KS}from"@vkontakte/videoplayer-shared/es2018";import{clearVideoElement as H$}from"@vkontakte/videoplayer-shared/es2018";var YS=a=>{try{a.pause(),a.playbackRate=0,H$(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as Q$,Subscription as G$}from"@vkontakte/videoplayer-shared/es2018";var uc=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},lc=window.WeakMap?new WeakMap:new uc,cc=window.WeakMap?new WeakMap:new Map,W$=(a,e=20)=>{let t=0;return Q$(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Me=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?KS(i):(i=document.createElement("video"),a.appendChild(i)),lc.set(i,r);let s=new G$;return s.add(W$(i,e)),cc.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},De=a=>{let e=cc.get(a);e==null||e.unsubscribe(),cc.delete(a);let t=lc.get(a);lc.delete(a),t?KS(a):YS(a)};var pc=O(pr(),1);import{assertNonNullable as ya,isNonNullable as gt,isNullable as tM,fromEvent as hr,merge as rv,observableFrom as av,filterChanged as sv,map as Ta,Subject as nv,Subscription as iM,ValueSubject as rM,ErrorCategory as aM}from"@vkontakte/videoplayer-shared/es2018";import{isNonNullable as dc,isNullable as Z$,Subscription as eM}from"@vkontakte/videoplayer-shared/es2018";var Fn=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=Z$(r),l=new eM;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},bt=(a,e,t)=>Fn(e,()=>a.loop,i=>{dc(i)&&(a.loop=i)},{onError:t}),Ce=(a,e,t,i)=>Fn(e,()=>({muted:a.muted,volume:a.volume}),r=>{dc(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ke=(a,e,t,i)=>Fn(e,()=>a.playbackRate,r=>{dc(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),va=Fn;var sM=a=>["__",a.language,a.label].join("|"),nM=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},hc=class a{constructor(e){this.available$=new nv;this.current$=new rM(void 0);this.error$=new nv;this.subscription=new iM;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:aM.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(va(t.internalTextTracks,()=>(0,pc.default)(this.internalTracks),s=>{gt(s)&&this.setInternal(s)},{equal:(s,n)=>gt(s)&&gt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ta(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(va(t.externalTextTracks,()=>(0,pc.default)(this.externalTracks),s=>{gt(s)&&this.setExternal(s)},{equal:(s,n)=>gt(s)&&gt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ta(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(va(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(va(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ya(this.video);let{textTracks:e}=this.video;this.subscription.add(hr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(rv(hr(e,"addtrack"),hr(e,"removetrack"),av(["init"])).pipe(Ta(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),sv((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(rv(hr(e,"change"),av(["init"])).pipe(Ta(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ta(i=>i&&this.htmlTextTrackToITextTrack(i).id),sv()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(hr(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,f,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((f=(d=o.target)==null?void 0:d.cues)!=null?f:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(hr(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;gt(t.align)&&(r.align=t.align),gt(t.position)&&(r.position=t.position),gt(t.size)&&(r.size=t.size),gt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ya(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:i}=e,r=e.id?e.id:sM(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){ya(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(tM(e)||!nM(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){ya(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){ya(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Xe=hc;var wi=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var ov=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},fc=a=>{let e=ov(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},uv=a=>{let e=ov(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ae,map as St,merge as Nn,filterChanged as cv,isNonNullable as dv,Subject as uM,filter as mc,mapTo as bc,combine as lM,once as cM,shareReplay as Pe,throttle as dM,ErrorCategory as pM,ValueSubject as pv,Subscription as hM}from"@vkontakte/videoplayer-shared/es2018";var oM=3,lv=(a,e,t=oM)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Be=a=>{let e=k=>Ae(a,k).pipe(bc(void 0),Pe(1)),t=new hM,i=()=>t.unsubscribe(),r=Nn(Ae(a,"progress"),Ae(a,"timeupdate")).pipe(St(()=>lv(a.buffered,a.currentTime)),Pe(1)),s=F.browser.isSafari?lM({play:e("play").pipe(cM()),playing:e("playing")}).pipe(bc(void 0),Pe(1)):e("playing"),n=Ae(a,"volumechange").pipe(St(()=>({muted:a.muted,volume:a.volume})),Pe(1)),o=Ae(a,"ratechange").pipe(St(()=>a.playbackRate),Pe(1)),u=Ae(a,"error").pipe(mc(()=>!!(a.error||a.played.length)),St(()=>{var V;let k=a.error;return{id:k?`MediaError#${k.code}`:"HtmlVideoError",category:pM.VIDEO_PIPELINE,message:k?k.message:"Error event from HTML video element",thrown:(V=a.error)!=null?V:void 0}}),Pe(1)),l=Ae(a,"timeupdate").pipe(St(()=>a.currentTime),Pe(1)),c=["waiting","seeking","seeked","timeupdate"],d=new uM,f=.3,p;t.add(Nn(...c.map(k=>Ae(a,k))).subscribe(k=>{let V=a.currentTime;a.loop&&dv(p)&&dv(V)&&p>=a.duration-f&&V<=f&&d.next(p),p=V}));let h=e("pause").pipe(mc(()=>!a.error&&p!==a.duration),Pe(1)),m=Ae(a,"enterpictureinpicture").pipe(Pe(1)),b=Ae(a,"leavepictureinpicture").pipe(Pe(1)),S=new pv(uv(a));t.add(m.subscribe(()=>S.next(!0))),t.add(b.subscribe(()=>S.next(!1)));let y=new pv(fc(a)),v=Ae(a,"fullscreenchange").pipe(Pe(1));t.add(v.pipe(St(()=>fc(a))).subscribe(y));let I=.1,E=1e3,A=Ae(a,"timeupdate").pipe(St(k=>a.duration-a.currentTime<I),cv(),Pe(1)),M=Nn(A.pipe(mc(k=>!a.loop&&k)),Ae(a,"ended")).pipe(dM(E),bc(void 0),Pe(1)),P=Nn(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(k=>Ae(a,k)),A.pipe(St(k=>({type:k?"ended":"unknown"})))).pipe(St(k=>F.browser.isFirefox&&k.type==="ended"?a.readyState<2:a.readyState<3),cv(),Pe(1));return{playing$:s,pause$:h,canplay$:e("canplay"),ended$:M,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ae(a,"durationchange").pipe(St(()=>a.duration),Pe(1)),isBuffering$:P,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:S,inFullscreen$:y,enterPip$:m,leavePip$:b,destroy:i}};import{VideoQuality as Yt}from"@vkontakte/videoplayer-shared/es2018";var Kt=a=>{switch(a){case"mobile":return Yt.Q_144P;case"lowest":return Yt.Q_240P;case"low":return Yt.Q_360P;case"sd":case"medium":return Yt.Q_480P;case"hd":case"high":return Yt.Q_720P;case"fullhd":case"full":return Yt.Q_1080P;case"quadhd":case"quad":return Yt.Q_1440P;case"ultrahd":case"ultra":return Yt.Q_2160P}};var Re=O(ot(),1),vc=O(Ye(),1),Ai=O(er(),1);import{isNonNullable as X,isNullable as Qn,now as kv,isHigher as Gn,isHigherOrEqual as mr,isInvariantQuality as Wn,isLowerOrEqual as br,videoSizeToQuality as Rv,assertNotEmptyArray as zn,assertNonNullable as Lv}from"@vkontakte/videoplayer-shared/es2018";var gc=!1,Lt={},vv=a=>{gc=a},yv=()=>{Lt={}},Tv=a=>{a(Lt)},Ia=(a,e)=>{var t;gc&&(Lt.meta=(t=Lt.meta)!=null?t:{},Lt.meta[a]=e)},ke=class{constructor(e){this.name=e}next(e){var i,r;if(!gc)return;Lt.series=(i=Lt.series)!=null?i:{};let t=(r=Lt.series[this.name])!=null?r:[];t.push([Date.now(),e]),Lt.series[this.name]=t}};import{isHigher as IM,isHigherOrEqual as ZU,isLower as Iv,isLowerOrEqual as eq,isNonNullable as Un,isNullable as EM,videoHeightToQuality as qn}from"@vkontakte/videoplayer-shared/es2018";function Sc(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function jn(a,e,t){return!!a&&Sc(a,e,t)==="high_quality"}function fr(a,e,t){return EM(a)||Un(a.min)&&Un(a.max)&&Iv(a.max,a.min)||Un(a.min)&&e&&IM(a.min,e)||Un(a.max)&&t&&Iv(a.max,t)}function Ev({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return fr({max:a!=null&&a.max?qn(a.max):void 0,min:a!=null&&a.min?qn(a.min):void 0},e?qn(e):void 0,t?qn(t):void 0)}var $v=new ke("best_bitrate"),Yn=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var gr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Xt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=kv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Kn='Assertion "ABR Tracks is empty array" failed',Hn=new WeakMap,xv=new WeakMap,wv=new WeakMap,Ea=(a,e,t,i)=>{var u;let r=[...e].sort(gr(1)),s=[...t].sort(gr(1)),n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Re.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Re.default)(s,-1);return o&&(0,vc.default)(n,o)?o:n.length?(0,Re.default)(n,-1):(0,Re.default)(s,0)},xa=(a,e,t,i)=>{var u;let r=Hn.get(e);r||(r=[...e].sort(gr(1)),Hn.set(e,r));let s=Hn.get(t);s||(s=[...t].sort(gr(1)),Hn.set(t,s));let n=wv.get(a);n||(n=s.filter(l=>X(l.bitrate)&&X(a.bitrate)?a.bitrate/l.bitrate>i:!0),wv.set(a,n));let o=(u=(0,Re.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Re.default)(s,-1);return o&&(0,vc.default)(n,o)?o:n.length?(0,Re.default)(n,-1):(0,Re.default)(s,0)},Av=a=>"quality"in a,Xn=(a,e,t,i)=>{var n;let r=X((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&X(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&kv()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=Av(o)?"video":"audio",l=Av(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return i==null||i.recordSwitch(t),t},TM=(a,e)=>Math.log(e)/Math.log(a),Rv=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&U.display.pixelRatio){let s=U.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,d=TM(n,o*s+u)+l;Number.isFinite(d)&&(r*=d)}}return jn(t,a.highQualityLimit,a.trafficSavingLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},xv=new WeakMap,vt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var R,Q,O,A,_;zn(a,Kn);let{containerSizeFactor:g,containerSizeLimit:S}=Rv({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&J(o)?o:1,y=xv.get(a);y||(y=a.filter(k=>!Wn(k.quality)).sort((k,E)=>Gn(k.quality,E.quality)?-1:1),xv.set(a,y));let I=(R=(0,Re.default)(y,-1))==null?void 0:R.quality,T=(Q=(0,Re.default)(y,0))==null?void 0:Q.quality,x=fr(r,T,I),V=v*Yn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},w=null;for(let k of y){let E=!0;if(S)if(k.size)E=k.size.width<=S.width&&k.size.height<=S.height;else{let Ne=S&&Av(S);E=Ne?br(k.quality,Ne):!0}if(!E){$[k.quality]="FitsContainer";continue}let C=p||t,ne=J(C)&&isFinite(C)&&J(k.bitrate)?C-s>=k.bitrate*V:!0,Fe=jn(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===k.quality;if(!ne&&!Fe){$[k.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&J(i.minBufferToSwitchUp)&&u&&!Wn(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Gn(k.quality,u.quality)){$[k.quality]="Buffer";continue}if(!!c&&mr(k.quality,c)&&!Fe){$[k.quality]="DroppedFramesLimit";continue}if(!!f&&mr(k.quality,f)&&!Fe){$[k.quality]="StallsLimit";continue}let Se=x||(Qn(r==null?void 0:r.max)||br(k.quality,r.max))&&(Qn(r==null?void 0:r.min)||mr(k.quality,r.min)),ve=J(d)&&!d?br(k.quality,i.backgroundVideoQualityLimit):!0;if(!Se||!ve){$[k.quality]="FitsQualityLimits";continue}w||(w=k)}w&&w.bitrate&&kv.next(w.bitrate);let P=(O=w!=null?w:(0,Re.default)(y,-1))!=null?O:a[0],B=l==null?void 0:l.last,M=Xn(i,h,P,l);return J(l)&&M.quality!==(B==null?void 0:B.quality)&&h({message:`
9
+ `}),o}return i==null||i.recordSwitch(t),t},xM=(a,e)=>Math.log(e)/Math.log(a),Mv=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&F.display.pixelRatio){let s=F.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,c=xM(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return jn(t,a.highQualityLimit,a.trafficSavingLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Pv=new WeakMap,vt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var _,Y,J,T,R;zn(a,Kn);let{containerSizeFactor:b,containerSizeLimit:S}=Mv({container:e,tuning:i,limits:r,panelSize:m}),y=i.considerPlaybackRate&&X(o)?o:1,v=Pv.get(a);v||(v=a.filter(x=>!Wn(x.quality)).sort((x,w)=>Gn(x.quality,w.quality)?-1:1),Pv.set(a,v));let I=(_=(0,Re.default)(v,-1))==null?void 0:_.quality,E=(Y=(0,Re.default)(v,0))==null?void 0:Y.quality,A=fr(r,E,I),M=y*Yn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},P=null;for(let x of v){let w=!0;if(S)if(x.size)w=x.size.width<=S.width&&x.size.height<=S.height;else{let Ne=S&&Rv(S);w=Ne?br(x.quality,Ne):!0}if(!w){L[x.quality]="FitsContainer";continue}let B=p||t,ne=X(B)&&isFinite(B)&&X(x.bitrate)?B-s>=x.bitrate*M:!0,Fe=jn(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===x.quality;if(!ne&&!Fe){L[x.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!Wn(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Gn(x.quality,u.quality)){L[x.quality]="Buffer";continue}if(!!d&&mr(x.quality,d)&&!Fe){L[x.quality]="DroppedFramesLimit";continue}if(!!f&&mr(x.quality,f)&&!Fe){L[x.quality]="StallsLimit";continue}let Se=A||(Qn(r==null?void 0:r.max)||br(x.quality,r.max))&&(Qn(r==null?void 0:r.min)||mr(x.quality,r.min)),ve=X(c)&&!c?br(x.quality,i.backgroundVideoQualityLimit):!0;if(!Se||!ve){L[x.quality]="FitsQualityLimits";continue}P||(P=x)}P&&P.bitrate&&$v.next(P.bitrate);let k=(J=P!=null?P:(0,Re.default)(v,-1))!=null?J:a[0],V=l==null?void 0:l.last,D=Xn(i,h,k,l);return X(l)&&D.quality!==(V==null?void 0:V.quality)&&h({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${a.map(k=>{var E,C;return`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate}, size: ${(E=k.size)==null?void 0:E.width}:${(C=k.size)==null?void 0:C.height} }`}).join(`
12
+ ${a.map(x=>{var w,B;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(w=x.size)==null?void 0:w.width}:${(B=x.size)==null?void 0:B.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,Ai.default)(i!=null?i:{}).map(([k,E])=>`${k}: ${E}`).join(`
16
+ ${(0,Ai.default)(i!=null?i:{}).map(([x,w])=>`${x}: ${w}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
- containerSizeFactor: ${g},
21
- containerSizeLimit: ${(A=S==null?void 0:S.width)!=null?A:0} x ${(_=S==null?void 0:S.height)!=null?_:0},
20
+ containerSizeFactor: ${b},
21
+ containerSizeLimit: ${(T=S==null?void 0:S.width)!=null?T:0} x ${(R=S==null?void 0:S.height)!=null?R:0},
22
22
  estimatedThroughput: ${t},
23
23
  stallsPredictedThroughput: ${p},
24
24
  reserve: ${s},
25
25
  playbackRate: ${o},
26
- playbackRateFactor: ${v},
26
+ playbackRateFactor: ${y},
27
27
  forwardBufferHealth: ${n},
28
- bitrateFactor: ${V},
28
+ bitrateFactor: ${M},
29
29
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
30
- droppedVideoMaxQualityLimit: ${c},
30
+ droppedVideoMaxQualityLimit: ${d},
31
31
  stallsVideoMaxQualityLimit: ${f},
32
- limitsAreInvalid: ${x},
32
+ limitsAreInvalid: ${A},
33
33
  maxQualityLimit: ${r==null?void 0:r.max},
34
34
  minQualityLimit: ${r==null?void 0:r.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,Ai.default)($).map(([k,E])=>`${k}: ${E}`).join(`
37
+ ${(0,Ai.default)(L).map(([x,w])=>`${x}: ${w}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
- [best video track] ${w==null?void 0:w.quality}
41
- [selected video track] ${M==null?void 0:M.quality}
42
- `}),M},Jn=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var Q,O,A,_,k;zn(a,Kn);let{containerSizeFactor:g,containerSizeLimit:S}=Rv({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&J(o)?o:1,y=a.filter(E=>!Wn(E.quality)).sort((E,C)=>Gn(E.quality,C.quality)?-1:1),I=(Q=(0,Re.default)(y,-1))==null?void 0:Q.quality,T=(O=(0,Re.default)(y,0))==null?void 0:O.quality,x=fr(r,T,I),V=v*Yn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),$={},P=y.filter(E=>{let C=!0;if(S)if(E.size)C=E.size.width<=S.width&&E.size.height<=S.height;else{let xt=S&&Av(S);C=xt?br(E.quality,xt):!0}if(!C)return $[E.quality]="FitsContainer",!1;let ne=p||t,Fe=J(ne)&&isFinite(ne)&&J(E.bitrate)?ne-s>=E.bitrate*V:!0,ie=jn(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===E.quality;if(!Fe&&!ie)return $[E.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&J(i.minBufferToSwitchUp)&&u&&!Wn(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Gn(E.quality,u.quality))return $[E.quality]="Buffer",!1;if(!!c&&mr(E.quality,c)&&!ie)return $[E.quality]="DroppedFramesLimit",!1;if(!!f&&mr(E.quality,f)&&!ie)return $[E.quality]="StallsLimit",!1;let ve=x||(Qn(r==null?void 0:r.max)||br(E.quality,r.max))&&(Qn(r==null?void 0:r.min)||mr(E.quality,r.min)),Ne=J(d)&&!d?br(E.quality,i.backgroundVideoQualityLimit):!0;return!ve||!Ne?($[E.quality]="FitsQualityLimits",!1):!0})[0];P&&P.bitrate&&kv.next(P.bitrate);let B=(A=P!=null?P:(0,Re.default)(y,-1))!=null?A:a[0],M=l==null?void 0:l.last,R=Xn(i,h,B,l);return J(l)&&R.quality!==(M==null?void 0:M.quality)&&h({message:`
40
+ [best video track] ${P==null?void 0:P.quality}
41
+ [selected video track] ${D==null?void 0:D.quality}
42
+ `}),D},Jn=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:f,stallsPredictedThroughput:p,abrLogger:h,panelSize:m})=>{var Y,J,T,R,x;zn(a,Kn);let{containerSizeFactor:b,containerSizeLimit:S}=Mv({container:e,tuning:i,limits:r,panelSize:m}),y=i.considerPlaybackRate&&X(o)?o:1,v=a.filter(w=>!Wn(w.quality)).sort((w,B)=>Gn(w.quality,B.quality)?-1:1),I=(Y=(0,Re.default)(v,-1))==null?void 0:Y.quality,E=(J=(0,Re.default)(v,0))==null?void 0:J.quality,A=fr(r,E,I),M=y*Yn(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),L={},k=v.filter(w=>{let B=!0;if(S)if(w.size)B=w.size.width<=S.width&&w.size.height<=S.height;else{let xt=S&&Rv(S);B=xt?br(w.quality,xt):!0}if(!B)return L[w.quality]="FitsContainer",!1;let ne=p||t,Fe=X(ne)&&isFinite(ne)&&X(w.bitrate)?ne-s>=w.bitrate*M:!0,ie=jn(r,i.highQualityLimit,i.trafficSavingLimit)&&(r==null?void 0:r.min)===w.quality;if(!Fe&&!ie)return L[w.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&X(i.minBufferToSwitchUp)&&u&&!Wn(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Gn(w.quality,u.quality))return L[w.quality]="Buffer",!1;if(!!d&&mr(w.quality,d)&&!ie)return L[w.quality]="DroppedFramesLimit",!1;if(!!f&&mr(w.quality,f)&&!ie)return L[w.quality]="StallsLimit",!1;let ve=A||(Qn(r==null?void 0:r.max)||br(w.quality,r.max))&&(Qn(r==null?void 0:r.min)||mr(w.quality,r.min)),Ne=X(c)&&!c?br(w.quality,i.backgroundVideoQualityLimit):!0;return!ve||!Ne?(L[w.quality]="FitsQualityLimits",!1):!0})[0];k&&k.bitrate&&$v.next(k.bitrate);let V=(T=k!=null?k:(0,Re.default)(v,-1))!=null?T:a[0],D=l==null?void 0:l.last,_=Xn(i,h,V,l);return X(l)&&_.quality!==(D==null?void 0:D.quality)&&h({message:`
43
43
  [VIDEO TRACKS ABR]
44
44
  [available video tracks]
45
- ${a.map(E=>{var C,ne;return`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate}, size: ${(C=E.size)==null?void 0:C.width}:${(ne=E.size)==null?void 0:ne.height} }`}).join(`
45
+ ${a.map(w=>{var B,ne;return`{ id: ${w.id}, quality: ${w.quality}, bitrate: ${w.bitrate}, size: ${(B=w.size)==null?void 0:B.width}:${(ne=w.size)==null?void 0:ne.height} }`}).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,Ai.default)(i!=null?i:{}).map(([E,C])=>`${E}: ${C}`).join(`
49
+ ${(0,Ai.default)(i!=null?i:{}).map(([w,B])=>`${w}: ${B}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
53
- containerSizeFactor: ${g},
54
- containerSizeLimit: ${(_=S==null?void 0:S.width)!=null?_:0} x ${(k=S==null?void 0:S.height)!=null?k:0},
53
+ containerSizeFactor: ${b},
54
+ containerSizeLimit: ${(R=S==null?void 0:S.width)!=null?R:0} x ${(x=S==null?void 0:S.height)!=null?x:0},
55
55
  estimatedThroughput: ${t},
56
56
  stallsPredictedThroughput: ${p},
57
57
  reserve: ${s},
58
58
  playbackRate: ${o},
59
- playbackRateFactor: ${v},
59
+ playbackRateFactor: ${y},
60
60
  forwardBufferHealth: ${n},
61
- bitrateFactor: ${V},
61
+ bitrateFactor: ${M},
62
62
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
63
- droppedVideoMaxQualityLimit: ${c},
63
+ droppedVideoMaxQualityLimit: ${d},
64
64
  stallsVideoMaxQualityLimit: ${f},
65
- limitsAreInvalid: ${x},
65
+ limitsAreInvalid: ${A},
66
66
  maxQualityLimit: ${r==null?void 0:r.max},
67
67
  minQualityLimit: ${r==null?void 0:r.min},
68
68
 
69
69
  [limited video tracks]
70
- ${(0,Ai.default)($).map(([E,C])=>`${E}: ${C}`).join(`
70
+ ${(0,Ai.default)(L).map(([w,B])=>`${w}: ${B}`).join(`
71
71
  `)||"All tracks are available"}
72
72
 
73
- [best video track] ${P==null?void 0:P.quality}
74
- [selected video track] ${R==null?void 0:R.quality}
75
- `}),R},Zn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{zn(t,Kn);let d=r.considerPlaybackRate&&J(s)?s:1,c=[...t].sort(gr(-1)),f=a.bitrate;Pv(f);let p=d*Yn(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=Ea(a,e,t,r.minVideoAudioRatio),g=l||i;J(g)&&isFinite(g)&&(h=c.find(y=>J(y.bitrate)&&J(m==null?void 0:m.bitrate)?g-f>=y.bitrate*p&&y.bitrate>=m.bitrate:!1)),h||(h=m);let S=o==null?void 0:o.last,v=h&&Xn(r,u,h,o);return J(o)&&(v==null?void 0:v.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
73
+ [best video track] ${k==null?void 0:k.quality}
74
+ [selected video track] ${_==null?void 0:_.quality}
75
+ `}),_},Zn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{zn(t,Kn);let c=r.considerPlaybackRate&&X(s)?s:1,d=[...t].sort(gr(-1)),f=a.bitrate;Lv(f);let p=c*Yn(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=Ea(a,e,t,r.minVideoAudioRatio),b=l||i;X(b)&&isFinite(b)&&(h=d.find(v=>X(v.bitrate)&&X(m==null?void 0:m.bitrate)?b-f>=v.bitrate*p&&v.bitrate>=m.bitrate:!1)),h||(h=m);let S=o==null?void 0:o.last,y=h&&Xn(r,u,h,o);return X(o)&&(y==null?void 0:y.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
76
76
  [AUDIO TRACKS ABR]
77
77
  [available audio tracks]
78
- ${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
78
+ ${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
79
79
  `)}
80
80
 
81
81
  [tuning]
82
- ${(0,Ai.default)(r!=null?r:{}).map(([y,I])=>`${y}: ${I}`).join(`
82
+ ${(0,Ai.default)(r!=null?r:{}).map(([v,I])=>`${v}: ${I}`).join(`
83
83
  `)}
84
84
 
85
85
  [limit params]
@@ -87,20 +87,20 @@ var OE=Object.create;var Bp=Object.defineProperty;var FE=Object.getOwnPropertyDe
87
87
  stallsPredictedThroughput: ${l},
88
88
  reserve: ${f},
89
89
  playbackRate: ${s},
90
- playbackRateFactor: ${d},
90
+ playbackRateFactor: ${c},
91
91
  forwardBufferHealth: ${n},
92
92
  bitrateFactor: ${p},
93
93
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
94
94
 
95
- [selected audio track] ${v==null?void 0:v.id}
96
- `}),v},eo=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{zn(t,Kn);let d=r.considerPlaybackRate&&J(s)?s:1,c=Tv.get(t);c||(c=[...t].sort(gr(-1)),Tv.set(t,c));let f=a.bitrate;Pv(f);let p=d*Yn(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=xa(a,e,t,r.minVideoAudioRatio),g=l||i;J(g)&&isFinite(g)&&(h=c.find(y=>J(y.bitrate)&&J(m==null?void 0:m.bitrate)?g-f>=y.bitrate*p&&y.bitrate>=m.bitrate:!1)),h||(h=m);let S=o==null?void 0:o.last,v=h&&Xn(r,u,h,o);return J(o)&&(v==null?void 0:v.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
95
+ [selected audio track] ${y==null?void 0:y.id}
96
+ `}),y},eo=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{zn(t,Kn);let c=r.considerPlaybackRate&&X(s)?s:1,d=xv.get(t);d||(d=[...t].sort(gr(-1)),xv.set(t,d));let f=a.bitrate;Lv(f);let p=c*Yn(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),h,m=xa(a,e,t,r.minVideoAudioRatio),b=l||i;X(b)&&isFinite(b)&&(h=d.find(v=>X(v.bitrate)&&X(m==null?void 0:m.bitrate)?b-f>=v.bitrate*p&&v.bitrate>=m.bitrate:!1)),h||(h=m);let S=o==null?void 0:o.last,y=h&&Xn(r,u,h,o);return X(o)&&(y==null?void 0:y.bitrate)!==(S==null?void 0:S.bitrate)&&u({message:`
97
97
  [AUDIO TRACKS ABR]
98
98
  [available audio tracks]
99
- ${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
99
+ ${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
100
100
  `)}
101
101
 
102
102
  [tuning]
103
- ${(0,Ai.default)(r!=null?r:{}).map(([y,I])=>`${y}: ${I}`).join(`
103
+ ${(0,Ai.default)(r!=null?r:{}).map(([v,I])=>`${v}: ${I}`).join(`
104
104
  `)}
105
105
 
106
106
  [limit params]
@@ -108,20 +108,20 @@ var OE=Object.create;var Bp=Object.defineProperty;var FE=Object.getOwnPropertyDe
108
108
  stallsPredictedThroughput: ${l},
109
109
  reserve: ${f},
110
110
  playbackRate: ${s},
111
- playbackRateFactor: ${d},
111
+ playbackRateFactor: ${c},
112
112
  forwardBufferHealth: ${n},
113
113
  bitrateFactor: ${p},
114
114
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
115
115
 
116
- [selected audio track] ${v==null?void 0:v.id}
117
- `}),v};var Te=a=>new URL(a).hostname;import{assertNever as Nv,assertNonNullable as Uv,combine as qM,debounce as jM,ErrorCategory as qv,filter as jv,filterChanged as HM,isNonNullable as Ic,map as ao,merge as Hv,observableFrom as QM,once as GM,Subscription as WM,ValueSubject as Ec,videoQualityToHeight as Qv,videoSizeToQuality as zM}from"@vkontakte/videoplayer-shared/es2018";var Vv=N(St(),1);var $v=N(Ye(),1),Lv=a=>{if(a instanceof DOMException&&(0,$v.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Ve=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!Lv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return Lv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as io,isNullable as xM,assertNonNullable as Pa}from"@vkontakte/videoplayer-shared/es2018";var Dv=N(dr(),1);import{isNonNullable as Mv,assertNonNullable as to,now as IM}from"@vkontakte/videoplayer-shared/es2018";function fe(){return IM()}function Sc(a){return fe()-a}function vc(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Cv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Sr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,f=!1,p="arraybuffer",h=7e3,m=2e3,g=()=>{if(u)return;to(d);let M=Sc(d),R;if(M<m){R=m-M,setTimeout(g,R);return}m*=2,m>h&&(m=h),n&&n.abort(),n=new r,x()},S=M=>(s=M,B),v=M=>(c=M,B),y=()=>(p="json",B),I=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},T=M=>(f=M,B),x=()=>{d=fe(),n=new r,n.open("get",a);let M=0,R,Q=0,O=()=>(to(d),Math.max(d,Math.max(R||0,Q||0)));if(s&&n.addEventListener("progress",A=>{let _=fe();s.updateChunk&&A.loaded>M&&(s.updateChunk(O(),A.loaded-M),M=A.loaded,R=_)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;to(n);let A=n.status;if(A>=200&&A<300){let{response:_,responseType:k}=n,E=_==null?void 0:_.byteLength;if(typeof E=="number"&&s){let C=E-M;C&&s.updateChunk&&s.updateChunk(O(),C)}k==="json"&&(!_||!(0,Dv.default)(_).length)?I():(c&&c(),e(_))}else I()}),n.addEventListener("error",()=>{I()}),f){let A=()=>{to(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=fe(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=p,n.send(),B},B={withBitrateReporting:S,withParallel:T,withJSONResponse:y,withRetryCount:M=>(l=M,B),withRetryInterval:(M,R)=>(Mv(M)&&(m=M),Mv(R)&&(h=R),B),withTimeout:M=>(o=M,B),withFinally:v,send:x,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return B}var wa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Bv=N(dr(),1);var Aa=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=fe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=fe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Sr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=fe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=fe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Bv.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as wM}from"@vkontakte/videoplayer-shared/es2018";var ro=1e4,yc=3;var AM=6e4,PM=10,kM=1,RM=500,ka=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new wM,this.chunkRateEstimator=new wa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=vc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=vc(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(s=e.error)==null?void 0:s.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(U.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!yv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Vv.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||io(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Cv(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Aa(yc,ro,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,d=!1,c=()=>{let I=s&&(!d||d===this.rep);return I||t("Not running!"),I},f=(I,T,x)=>{u&&u.abort(),u=Sr(this.urlResolver.resolve(I,!1),T,x,()=>this._retryCallback()).withTimeout(ro).withBitrateReporting(this.bitrateSwitcher).withRetryCount(yc).withFinally(()=>{u=null}).send()},p=(I,T,x)=>{Pa(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),T,x,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=I=>{let T=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${T}=>${I}`),i.playbackRate=I)},m=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let x=fe()-1e4,V=0;for(let w=0;w<this.bufferStates.length;w++){let P=this.bufferStates[w];I=Math.min(I,P.buf),P.ts<x&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${I} drop=${V} jitter=${this.sourceJitter}`);let $=I-kM;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?h(1.15):$>1?h(1.1):$>.3?h(1.05):h(1)}},S=I=>{let T,x=()=>T&&T.start?T.start.length:0,V=A=>T.start[A]/1e3,$=A=>T.dur[A]/1e3,w=A=>T.fragIndex+A,P=(A,_)=>({chunkIdx:w(A),startTS:V(A),dur:$(A),discontinuity:_}),B=()=>{let A=0;if(T&&T.dur){let _=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,k=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,E=_;this.sourceJitter>1&&(E+=this.sourceJitter-1);let C=T.dur.length-1;for(;C>=0&&(E-=T.dur[C],!(E<=0));--C);A=Math.min(C,T.dur.length-1-k),A=Math.max(A,0)}return P(A,!0)},M=A=>{let _=x();if(!(_<=0)){if(io(A)){for(let k=0;k<_;k++)if(V(k)>A)return P(k)}return B()}},R=A=>{let _=x(),k=A?A.chunkIdx+1:0,E=k-T.fragIndex;if(!(_<=0)){if(!A||E<0||E-_>PM)return t(`Resync: offset=${E} bChunks=${_} chunk=`+JSON.stringify(A)),B();if(!(E>=_))return P(k-T.fragIndex,!1)}},Q=(A,_,k)=>{l&&l.abort(),l=Sr(this.urlResolver.resolve(A,!0,this.lowLatency),_,k,()=>this._retryCallback()).withTimeout(ro).withRetryCount(yc).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,_)=>{Q(I,k=>{if(!c())return;T=k;let E=!!T.lowLatency;E!==this.lowLatency&&m(E);let C=0;for(let ne=0;ne<T.dur.length;++ne)C+=T.dur[ne];C>0&&(Pa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(C/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,A(M(_))},()=>this._handleNetworkError())},nextChunk:R}},v=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Pa(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:I=>{let{videoElement:T,logger:x}=this.params,V=S(e.jidxUrl),$,w,P,B,M=0,R,Q,O,A=()=>{R&&(clearTimeout(R),R=void 0);let Y=Math.max(RM,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=M+Y,Se=fe(),ve=Math.min(1e4,ge-Se);M=Se;let Ne=()=>{l||c()&&V.seek(()=>{c()&&(M=fe(),_(),A())})};ve>0?R=window.setTimeout(()=>{this.paused?A():Ne()},ve):Ne()},_=()=>{let Y;for(;Y=V.nextChunk(B);)B=Y,Fe(Y);let ge=V.nextChunk(P);if(ge){if(P&&ge.discontinuity){x("Detected discontinuity; restarting playback"),this.paused?A():(v(),this._initPlayerWith(e));return}ne(ge)}else A()},k=(Y,ge)=>{if(!c()||!this.sourceBuffer)return;let Se,ve,Ne,xt=Ot=>{window.setTimeout(()=>{c()&&k(Y,ge)},Ot)};if(this.sourceBuffer.updating)x("Source buffer is updating; delaying appendBuffer"),xt(100);else{let Ot=fe(),ni=T.currentTime;!this.paused&&T.buffered.length>1&&Q===ni&&Ot-O>500&&(x("Stall suspected; trying to fix"),this._fixupStall()),Q!==ni&&(Q=ni,O=Ot);let Ni=this._getBufferSizeSec();if(Ni>30)x(`Buffered ${Ni} seconds; delaying appendBuffer`),xt(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:Ni}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Nr){if(Nr.name==="QuotaExceededError")x("QuotaExceededError; delaying appendBuffer"),Ne=this.sourceBuffer.buffered.length,Ne!==0&&(Se=this.sourceBuffer.buffered.start(0),ve=ni,ve-Se>4&&this.sourceBuffer.remove(Se,ve-3)),xt(1e3);else throw Nr}}},E=()=>{w&&$&&(x([`Appending chunk, sz=${w.byteLength}:`,JSON.stringify(P)]),k(w,function(){w=null,_()}))},C=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),ne=Y=>{c()&&p(C(Y),(ge,Se)=>{if(c()){if(Se/=1e3,w=ge,P=Y,n=Y.startTS,Se){let ve=Math.min(10,Y.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ve:ve}E()}},()=>this._handleNetworkError())},Fe=Y=>{c()&&(Pa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(C(Y),!1)))},ie=Y=>{c()&&(e.cachedHeader=Y,k(Y,()=>{$=!0,E()}))};s=!0,V.seek(Y=>{if(c()){if(M=fe(),!Y){A();return}B=Y,!xM(I)||Y.startTS>I?ne(Y):(P=Y,_())}},I),e.cachedHeader?ie(e.cachedHeader):f(e.headerUrl,ie,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),io(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Pa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return io(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),h=c/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}f=this._selectQuality(c),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(f,p)=>{let h=fe();if(this.chunkRateEstimator.addInterval(f,h,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:g}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Sc(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,f)=>{let p=s.updateChunk(c,f);return p&&l(),p},notifySwitch:c=>{let f=fe();c<o&&(n=f),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Sr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ro).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ve(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var d,c;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((c=(d=window.MediaSource)==null?void 0:d.isTypeSupported)!=null&&c.call(d,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},AM))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Fv=N(er(),1);import{debounce as LM,filter as _v,fromEvent as $M,interval as MM,isHigher as DM,isInvariantQuality as CM,isLower as BM,merge as VM,Subject as Ov,Subscription as _M}from"@vkontakte/videoplayer-shared/es2018";var Tc=class{constructor(){this.onDroopedVideoFramesLimit$=new Ov;this.subscription=new _M;this.playing=!1;this.tracks=[];this.forceChecker$=new Ov;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&&!CM(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&DM(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($M(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=MM(this.droppedFramesChecker.checkTime).pipe(_v(()=>this.playing),_v(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(LM(this.droppedFramesChecker.checkTime)),i=VM(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,Fv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>BM(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},vr=Tc;import{map as OM,Observable as FM}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as NM}from"@vkontakte/videoplayer-shared/es2018";var Ra=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var UM=(a,e)=>new FM(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ra()))},{...i,...e});r.observe(a);let s=NM(document,"visibilitychange").pipe(OM(n=>!document.hidden||Ra())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Je=UM;var YM=["paused","playing","ready"],KM=["paused","playing","ready"],La=class{constructor(e){this.subscription=new WM;this.videoState=new j("stopped");this.representations$=new Ec([]);this.droppedFramesManager=new vr;this.maxSeekBackTime$=new Ec(1/0);this.zeroTime$=new Ec(void 0);this.liveOffset=new wi;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:qv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),d=(i=Kt(u.name))!=null?i:zM(u.video),c=u.bitrate/1e3,f={...u.video};if(!d)continue;let p={id:l,quality:d,bitrate:c,size:f};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),Ic(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,xc.default)(KM,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,xc.default)(YM,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(le(this.params.source.url,u))}return;default:return Nv(e)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:qv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Hv(this.videoState.stateChangeStarted$.pipe(ao(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ao(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Be(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(ao(r=>r.map(({track:s})=>s)),jv(r=>!!r.length),GM()).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(HM(),ao(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(qM({zeroTime:this.zeroTime$.pipe(jv(Ic)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(Ce(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ke(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Qv(r),min:s&&Qv(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Nv(r.to)}},t)).add(Hv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,QM(["init"])).pipe(jM(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),De(this.video)}createLiveDashPlayer(){let e=new ka({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,d,c,f,p,h;let e=this.representations$.getValue(),t=(d=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?d:this.params.desiredState.videoTrack.getState(),i=(f=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Ic(t)?t:vt(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let m=(h=e.find(({track:g})=>g.id===s))==null?void 0:h.representation;Uv(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;Uv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(le(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Gv=La;var pI=N(Ye(),1);var me=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as VB,assertNonNullable as _B,debounce as OB,ErrorCategory as lI,filter as nd,filterChanged as Mo,fromEvent as FB,isNonNullable as cI,isNullable as NB,map as od,merge as Do,observableFrom as ud,once as dI,Subscription as UB}from"@vkontakte/videoplayer-shared/es2018";var{NativeAbortSignal:v1,NativeAbortController:y1}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function Wv(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function zv(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var so=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},yr=class extends so{constructor(){super(),this.listeners||so.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Pi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Pi;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},Pi=class{constructor(){Object.defineProperty(this,"signal",{value:new yr,writable:!0,configurable:!0})}abort(e){let t=zv(e),i=Wv(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Pi.prototype[Symbol.toStringTag]="AbortController",yr.prototype[Symbol.toStringTag]="AbortSignal");function no(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function wc(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!no({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let f=new t(l,d);return c&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),f},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch(p){c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let f=new Promise((p,h)=>{d.addEventListener("abort",()=>h(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:s}}var XM=()=>"fetch"in window,$a=XM()&&no({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Yv=$a?wc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=$a?Yv.fetch:window.fetch,L1=$a?Yv.Request:window.Request,Z=$a?Pi:window.AbortController,$1=$a?yr:window.AbortSignal;var ed=N(Ma(),1);var By=N(Cy(),1);import{ErrorCategory as Ca}from"@vkontakte/videoplayer-shared/es2018";var oo=a=>{if(!a)return{id:"EmptyResponse",category:Ca.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ca.NETWORK,message:`UV Error ${a}`};let e=(0,By.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ca.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ca.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ca.PARSER,message:"Response is valid XML, but parser failed"}};var Ie=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as Xc,assertNonNullable as Lr,combine as $r,ErrorCategory as lt,filter as xo,filterChanged as ps,flattenObject as hs,fromEvent as Bt,getTraceSubscriptionMethod as SB,interval as Jc,isNonNullable as fs,isNullable as rI,map as Mr,merge as Mi,now as Zc,Subject as wo,Subscription as aI,tap as vB,throttle as yB,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var co=N(Ye(),1),$i=N(St(),1),po=N(Ma(),1);var VD=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},_D=a=>window.clearTimeout(a),Vy=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),_y=!Vy(window.requestIdleCallback)||!Vy(window.cancelIdleCallback),Tr=_y?VD:window.requestIdleCallback,yt=_y?_D:window.cancelIdleCallback;var WT=N($n(),1);import{assertNever as OD,ErrorCategory as Oy,Subject as Fy}from"@vkontakte/videoplayer-shared/es2018";var FD=18,Ny=!1;try{Ny=U.browser.isSafari&&!!U.browser.safariVersion&&U.browser.safariVersion<=FD}catch(a){console.error(a)}var $c=class{constructor(e){this.bufferFull$=new Fy;this.error$=new Fy;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:Oy.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Ny&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Oy.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:OD(t)}}},Uy=$c;var Ir=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Zt,assertNonNullable as _e,ErrorCategory as Mt,fromEvent as Qc,getExponentialDelay as Gc,isNonNullable as Pr,isNullable as Ee,now as lo,once as nB,Subject as oB,Subscription as uB,ValueSubject as Li}from"@vkontakte/videoplayer-shared/es2018";var W=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Er=class extends W{};var Ba=class extends W{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var Va=class extends W{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var _a=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var re=class extends W{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Oa=class extends re{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Fa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Na=class extends W{constructor(e,t){super(e,t),this.data=this.content}};var ki=class extends re{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Ua=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ja=class extends re{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ha=class extends re{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Qa=class extends re{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Ga=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wa=class extends re{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var za=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ka=class extends re{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Xa=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ja=class extends re{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Za=class extends re{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var es=class extends re{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ts=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var is=class extends re{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var rs=class extends W{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var UD={ftyp:Va,moov:_a,mvhd:Oa,moof:Fa,mdat:Na,sidx:ki,trak:Ua,mdia:Ga,mfhd:Ka,tkhd:Wa,traf:Xa,tfhd:Ja,tfdt:Za,trun:es,minf:za,sv3d:qa,st3d:ja,prhd:Ha,proj:Ya,equi:Qa,uuid:Ba,stbl:ts,stsd:is,avc1:rs,unknown:Er},$t=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=UD[e];return i?new i(t,new a):new Er(t,new a)}};var Jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var jD=new TextDecoder("ascii"),HD=a=>jD.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",QD=a=>{let e=new ki(a,new $t),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},GD=(a,e)=>{let i=new $t().parse(a),r=new Jt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,c)},WD=a=>{let t=new $t().parse(a),i=new Jt(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},zD=a=>{var r;let t=new $t().parse(a);return(r=new Jt(t).find("sidx"))==null?void 0:r.timescale},YD=(a,e)=>{let i=new $t().parse(a),s=new Jt(i).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,f)=>c+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},KD=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new $t().parse(a),r=new Jt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},qy={validateData:HD,parseInit:KD,getIndexRange:()=>{},parseSegments:QD,parseFeedableSegmentChunk:GD,getChunkEndTime:YD,getServerLatencyTimestamps:WD,getTimescaleFromIndex:zD};var ns=N(Ye(),1);import{assertNonNullable as Mc,isNonNullable as Gy,isNullable as JD}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as XD}from"@vkontakte/videoplayer-shared/es2018";var jy={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},Hy=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ss(a,t),r=i in jy,s=r?jy[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,d=ss(u),c=l*2**((o-1)*8)+d,f=t+o,p;return f+c>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:f,tagSize:f+c,value:p,valueSize:c}},ss=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ot=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ss(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:XD(e)}},Ri=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Hy(i);if(!e(r))return;r.type==="master"&&Ri(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Qy=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Hy(a);return Ri(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ot(o,n):s===17026?t=ot(o,n):s===17029&&(i=ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Wy=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],ZD=[231,22612,22743,167,171,163,160,175],eC=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return Ri(a,({tag:f,type:p,value:h,valueSize:m})=>{if(f===21419){let g=ot(h,p);l=ss(g)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+m):f===357149030?s=!0:f===290298740?n=!0:f===2807729?i=ot(h,p):f===17545?r=ot(h,p):f===21420&&l===475249515?u=ot(h,p):f===374648427?Ri(h,({tag:g,type:S,value:v})=>g===30321?(d=ot(v,S)===1,!1):!0):s&&n&&(0,ns.default)(Wy,f)&&(o=!0),!o}),Mc(e,"Failed to parse webm Segment start"),Mc(t,"Failed to parse webm Segment end"),Mc(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}}}},tC=a=>{if(JD(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},iC=(a,e)=>{let t=!1,i=!1,r=o=>Gy(o.time)&&Gy(o.position),s=[],n;return Ri(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=ot(l,u));break;case 183:break;case 241:n&&(n.position=ot(l,u));break;default:t&&(0,ns.default)(Wy,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},rC=a=>{let e=0,t=!1;try{Ri(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ns.default)(ZD,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ns.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},zy={validateData:Qy,parseInit:eC,getIndexRange:tC,parseSegments:iC,parseFeedableSegmentChunk:rC};var Tt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return zy;case"mp4":return qy}}throw new ReferenceError(`Unsupported mime type ${a}`)};var It=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Fc=N(gT(),1),FT=N(er(),1),NT=N(DT(),1),UT=N(St(),1),Nc=N(dr(),1);var CT=N(Ye(),1),Oc=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,CT.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as rB,isNullable as _T}from"@vkontakte/videoplayer-shared/es2018";var BT=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var VT=a=>{var e;try{let t=iB(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function iB(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
116
+ [selected audio track] ${y==null?void 0:y.id}
117
+ `}),y};var Te=a=>new URL(a).hostname;import{assertNever as jv,assertNonNullable as Hv,combine as QM,debounce as GM,ErrorCategory as Qv,filter as Gv,filterChanged as WM,isNonNullable as xc,map as ao,merge as Wv,observableFrom as zM,once as YM,Subscription as KM,ValueSubject as wc,videoQualityToHeight as zv,videoSizeToQuality as XM}from"@vkontakte/videoplayer-shared/es2018";var Fv=O(ot(),1);var Cv=O(Ye(),1),Dv=a=>{if(a instanceof DOMException&&(0,Cv.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Ve=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!Dv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return Dv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as io,isNullable as PM,assertNonNullable as Pa}from"@vkontakte/videoplayer-shared/es2018";var Vv=O(pr(),1);import{isNonNullable as Bv,assertNonNullable as to,now as wM}from"@vkontakte/videoplayer-shared/es2018";function fe(){return wM()}function yc(a){return fe()-a}function Tc(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function _v(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Sr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,f=!1,p="arraybuffer",h=7e3,m=2e3,b=()=>{if(u)return;to(c);let D=yc(c),_;if(D<m){_=m-D,setTimeout(b,_);return}m*=2,m>h&&(m=h),n&&n.abort(),n=new r,A()},S=D=>(s=D,V),y=D=>(d=D,V),v=()=>(p="json",V),I=()=>{if(!u){if(--l>=0){b(),i&&i();return}u=!0,d&&d(),t&&t()}},E=D=>(f=D,V),A=()=>{c=fe(),n=new r,n.open("get",a);let D=0,_,Y=0,J=()=>(to(c),Math.max(c,Math.max(_||0,Y||0)));if(s&&n.addEventListener("progress",T=>{let R=fe();s.updateChunk&&T.loaded>D&&(s.updateChunk(J(),T.loaded-D),D=T.loaded,_=R)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;to(n);let T=n.status;if(T>=200&&T<300){let{response:R,responseType:x}=n,w=R==null?void 0:R.byteLength;if(typeof w=="number"&&s){let B=w-D;B&&s.updateChunk&&s.updateChunk(J(),B)}x==="json"&&(!R||!(0,Vv.default)(R).length)?I():(d&&d(),e(R))}else I()}),n.addEventListener("error",()=>{I()}),f){let T=()=>{to(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Y=fe(),n.removeEventListener("readystatechange",T))};n.addEventListener("readystatechange",T)}return n.responseType=p,n.send(),V},V={withBitrateReporting:S,withParallel:E,withJSONResponse:v,withRetryCount:D=>(l=D,V),withRetryInterval:(D,_)=>(Bv(D)&&(m=D),Bv(_)&&(h=_),V),withTimeout:D=>(o=D,V),withFinally:y,send:A,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return V}var wa=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ov=O(pr(),1);var Aa=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=fe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=fe()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Sr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=fe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=fe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Ov.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as kM}from"@vkontakte/videoplayer-shared/es2018";var ro=1e4,Ic=3;var RM=6e4,LM=10,$M=1,MM=500,ka=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new kM,this.chunkRateEstimator=new wa(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Tc(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Tc(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r,s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}, details: ${(s=e.error)==null?void 0:s.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(F.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!Ev({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Fv.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||io(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{_v(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Aa(Ic,ro,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},f=(I,E,A)=>{u&&u.abort(),u=Sr(this.urlResolver.resolve(I,!1),E,A,()=>this._retryCallback()).withTimeout(ro).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ic).withFinally(()=>{u=null}).send()},p=(I,E,A)=>{Pa(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=I=>{let E=i.playbackRate;i.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),i.playbackRate=I)},m=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let A=fe()-1e4,M=0;for(let P=0;P<this.bufferStates.length;P++){let k=this.bufferStates[P];I=Math.min(I,k.buf),k.ts<A&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${I} drop=${M} jitter=${this.sourceJitter}`);let L=I-$M;this.sourceJitter>=0?L-=this.sourceJitter/2:this.sourceJitter-=1,L>3?h(1.15):L>1?h(1.1):L>.3?h(1.05):h(1)}},S=I=>{let E,A=()=>E&&E.start?E.start.length:0,M=T=>E.start[T]/1e3,L=T=>E.dur[T]/1e3,P=T=>E.fragIndex+T,k=(T,R)=>({chunkIdx:P(T),startTS:M(T),dur:L(T),discontinuity:R}),V=()=>{let T=0;if(E&&E.dur){let R=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,x=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,w=R;this.sourceJitter>1&&(w+=this.sourceJitter-1);let B=E.dur.length-1;for(;B>=0&&(w-=E.dur[B],!(w<=0));--B);T=Math.min(B,E.dur.length-1-x),T=Math.max(T,0)}return k(T,!0)},D=T=>{let R=A();if(!(R<=0)){if(io(T)){for(let x=0;x<R;x++)if(M(x)>T)return k(x)}return V()}},_=T=>{let R=A(),x=T?T.chunkIdx+1:0,w=x-E.fragIndex;if(!(R<=0)){if(!T||w<0||w-R>LM)return t(`Resync: offset=${w} bChunks=${R} chunk=`+JSON.stringify(T)),V();if(!(w>=R))return k(x-E.fragIndex,!1)}},Y=(T,R,x)=>{l&&l.abort(),l=Sr(this.urlResolver.resolve(T,!0,this.lowLatency),R,x,()=>this._retryCallback()).withTimeout(ro).withRetryCount(Ic).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(T,R)=>{Y(I,x=>{if(!d())return;E=x;let w=!!E.lowLatency;w!==this.lowLatency&&m(w);let B=0;for(let ne=0;ne<E.dur.length;++ne)B+=E.dur[ne];B>0&&(Pa(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(B/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,T(D(R))},()=>this._handleNetworkError())},nextChunk:_}},y=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Pa(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:A}=this.params,M=S(e.jidxUrl),L,P,k,V,D=0,_,Y,J,T=()=>{_&&(clearTimeout(_),_=void 0);let W=Math.max(MM,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=D+W,Se=fe(),ve=Math.min(1e4,ge-Se);D=Se;let Ne=()=>{l||d()&&M.seek(()=>{d()&&(D=fe(),R(),T())})};ve>0?_=window.setTimeout(()=>{this.paused?T():Ne()},ve):Ne()},R=()=>{let W;for(;W=M.nextChunk(V);)V=W,Fe(W);let ge=M.nextChunk(k);if(ge){if(k&&ge.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?T():(y(),this._initPlayerWith(e));return}ne(ge)}else T()},x=(W,ge)=>{if(!d()||!this.sourceBuffer)return;let Se,ve,Ne,xt=Ot=>{window.setTimeout(()=>{d()&&x(W,ge)},Ot)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),xt(100);else{let Ot=fe(),ni=E.currentTime;!this.paused&&E.buffered.length>1&&Y===ni&&Ot-J>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),Y!==ni&&(Y=ni,J=Ot);let Ni=this._getBufferSizeSec();if(Ni>30)A(`Buffered ${Ni} seconds; delaying appendBuffer`),xt(2e3);else try{this.sourceBuffer.appendBuffer(W),this.videoPlayStarted?(this.bufferStates.push({ts:Ot,buf:Ni}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(Nr){if(Nr.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),Ne=this.sourceBuffer.buffered.length,Ne!==0&&(Se=this.sourceBuffer.buffered.start(0),ve=ni,ve-Se>4&&this.sourceBuffer.remove(Se,ve-3)),xt(1e3);else throw Nr}}},w=()=>{P&&L&&(A([`Appending chunk, sz=${P.byteLength}:`,JSON.stringify(k)]),x(P,function(){P=null,R()}))},B=W=>e.fragUrlTemplate.replace("%%id%%",W.chunkIdx),ne=W=>{d()&&p(B(W),(ge,Se)=>{if(d()){if(Se/=1e3,P=ge,k=W,n=W.startTS,Se){let ve=Math.min(10,W.dur/Se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ve:ve}w()}},()=>this._handleNetworkError())},Fe=W=>{d()&&(Pa(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(B(W),!1)))},ie=W=>{d()&&(e.cachedHeader=W,x(W,()=>{L=!0,w()}))};s=!0,M.seek(W=>{if(d()){if(D=fe(),!W){T();return}V=W,!PM(I)||W.startTS>I?ne(W):(k=W,R())}},I),e.cachedHeader?ie(e.cachedHeader):f(e.headerUrl,ie,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),io(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Pa(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return io(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let f,p,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),h=d/this.bitrate,p>10&&h>.8||p>15&&h>.5||p>20&&h>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}f=this._selectQuality(d),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(f,p)=>{let h=fe();if(this.chunkRateEstimator.addInterval(f,h,p)){let b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:h-f,speed:b}),!0}},get:()=>{let f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&yc(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,f)=>{let p=s.updateChunk(d,f);return p&&l(),p},notifySwitch:d=>{let f=fe();d<o&&(n=f),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Sr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ro).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Ve(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,u.codecs))&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},RM))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var qv=O(er(),1);import{debounce as DM,filter as Nv,fromEvent as CM,interval as BM,isHigher as VM,isInvariantQuality as _M,isLower as OM,merge as FM,Subject as Uv,Subscription as NM}from"@vkontakte/videoplayer-shared/es2018";var Ec=class{constructor(){this.onDroopedVideoFramesLimit$=new Uv;this.subscription=new NM;this.playing=!1;this.tracks=[];this.forceChecker$=new Uv;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!_M(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&VM(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(CM(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=BM(this.droppedFramesChecker.checkTime).pipe(Nv(()=>this.playing),Nv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(DM(this.droppedFramesChecker.checkTime)),i=FM(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,qv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>OM(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},vr=Ec;import{map as UM,Observable as qM}from"@vkontakte/videoplayer-shared/es2018";import{fromEvent as jM}from"@vkontakte/videoplayer-shared/es2018";var Ra=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var HM=(a,e)=>new qM(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ra()))},{...i,...e});r.observe(a);let s=jM(document,"visibilitychange").pipe(UM(n=>!document.hidden||Ra())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),Je=HM;var JM=["paused","playing","ready"],ZM=["paused","playing","ready"],La=class{constructor(e){this.subscription=new KM;this.videoState=new q("stopped");this.representations$=new wc([]);this.droppedFramesManager=new vr;this.maxSeekBackTime$=new wc(1/0);this.zeroTime$=new wc(void 0);this.liveOffset=new wi;this._dashCb=e=>{var t,i,r,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Qv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(i=Kt(u.name))!=null?i:XM(u.video),d=u.bitrate/1e3,f={...u.video};if(!c)continue;let p={id:l,quality:c,bitrate:d,size:f};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),xc(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Ac.default)(ZM,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Ac.default)(JM,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(le(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(le(this.params.source.url,u))}return;default:return jv(e)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Qv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Wv(this.videoState.stateChangeStarted$.pipe(ao(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ao(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Be(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(ao(r=>r.map(({track:s})=>s)),Gv(r=>!!r.length),YM()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(WM(),ao(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(QM({zeroTime:this.zeroTime$.pipe(Gv(xc)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(bt(this.video,this.params.desiredState.isLooped,t)).add(Ce(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ke(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&zv(r),min:s&&zv(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return jv(r.to)}},t)).add(Wv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,zM(["init"])).pipe(GM(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),De(this.video)}createLiveDashPlayer(){let e=new ka({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,f,p,h;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(f=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?f:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&xc(t)?t:vt(e.map(({track:m})=>m),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let m=(h=e.find(({track:b})=>b.id===s))==null?void 0:h.representation;Hv(m,"Representations missing"),this.dash.startPlay(m,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Hv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(le(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Yv=La;var mI=O(Ye(),1);var me=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as NB,assertNonNullable as UB,debounce as qB,ErrorCategory as pI,filter as ld,filterChanged as Mo,fromEvent as jB,isNonNullable as hI,isNullable as HB,map as cd,merge as Do,observableFrom as dd,once as fI,Subscription as QB}from"@vkontakte/videoplayer-shared/es2018";var{NativeAbortSignal:x1,NativeAbortController:w1}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self!="undefined"?self:global);function Kv(a){let e;try{e=new Event("abort")}catch(t){typeof document!="undefined"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=a,e}function Xv(a){if(a===void 0)if(typeof document=="undefined")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch(e){a=new Error("This operation was aborted"),a.name="AbortError"}return a}var so=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},yr=class extends so{constructor(){super(),this.listeners||so.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}throwIfAborted(){let{aborted:e,reason:t="Aborted"}=this;if(e)throw t}static timeout(e){let t=new Pi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Pi;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},Pi=class{constructor(){Object.defineProperty(this,"signal",{value:new yr,writable:!0,configurable:!0})}abort(e){let t=Xv(e),i=Kv(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Pi.prototype[Symbol.toStringTag]="AbortController",yr.prototype[Symbol.toStringTag]="AbortSignal");function no(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function Pc(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!no({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let f=new t(l,c);return d&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),f},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let f=new Promise((p,h)=>{c.addEventListener("abort",()=>h(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([f,n(u,l)])}return n(u,l)},Request:s}}var eD=()=>"fetch"in window,$a=eD()&&no({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Jv=$a?Pc({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=$a?Jv.fetch:window.fetch,B1=$a?Jv.Request:window.Request,Z=$a?Pi:window.AbortController,V1=$a?yr:window.AbortSignal;var rd=O(Ma(),1);var Oy=O(_y(),1);import{ErrorCategory as Ca}from"@vkontakte/videoplayer-shared/es2018";var oo=a=>{if(!a)return{id:"EmptyResponse",category:Ca.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ca.NETWORK,message:`UV Error ${a}`};let e=(0,Oy.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ca.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ca.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ca.PARSER,message:"Response is valid XML, but parser failed"}};var Ie=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as ed,assertNonNullable as Lr,combine as $r,ErrorCategory as ct,filter as xo,filterChanged as ps,flattenObject as hs,fromEvent as Bt,getTraceSubscriptionMethod as IB,interval as td,isNonNullable as fs,isNullable as nI,map as Mr,merge as Mi,now as id,Subject as wo,Subscription as oI,tap as EB,throttle as xB,ValueSubject as ae}from"@vkontakte/videoplayer-shared/es2018";var po=O(Ye(),1),$i=O(ot(),1),ho=O(Ma(),1);var FD=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},ND=a=>window.clearTimeout(a),Fy=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),Ny=!Fy(window.requestIdleCallback)||!Fy(window.cancelIdleCallback),Tr=Ny?FD:window.requestIdleCallback,yt=Ny?ND:window.cancelIdleCallback;var XT=O($n(),1);import{assertNever as UD,ErrorCategory as Uy,Subject as qy}from"@vkontakte/videoplayer-shared/es2018";var qD=18,jy=!1;try{jy=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=qD}catch(a){console.error(a)}var Dc=class{constructor(e){this.bufferFull$=new qy;this.error$=new qy;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Uy.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};jy&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Uy.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:UD(t)}}},Hy=Dc;var Ir=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as Zt,assertNonNullable as _e,ErrorCategory as Mt,fromEvent as Wc,getExponentialDelay as zc,isNonNullable as Pr,isNullable as Ee,now as co,once as cB,Subject as dB,Subscription as pB,ValueSubject as Li}from"@vkontakte/videoplayer-shared/es2018";var Qy=O(ot(),1);var uo=a=>a.valid,Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Er=class extends Q{};import{assertNever as jD}from"@vkontakte/videoplayer-shared/es2018";var Ba=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readString(16),r=new DataView(this.content.buffer,this.content.byteOffset+16,this.content.byteLength-16);this.userData=this.parseData(i,r)}parseData(e,t){switch(e){case"ondemandlivejson":{let i=new TextDecoder("ascii").decode(t),r=JSON.parse(i);return{received:r["t-in"],prepared:r["t-out"]}}default:jD(e)}}};var Va=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var _a=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var re=class extends Q{constructor(e,t){if(super(e,t),!this.valid)return;let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215,this.content=new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)}};var Oa=class extends re{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var Fa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Na=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var ki=class extends re{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var Ua=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var qa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ja=class extends re{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ha=class extends re{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Qa=class extends re{constructor(e,t){super(e,t),this.valid&&(this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32())}};var Ga=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wa=class extends re{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var za=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ya=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ka=class extends re{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Xa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ja=class extends re{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var Za=class extends re{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var es=class extends re{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var ts=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var is=class extends re{constructor(e,t){super(e,t),this.valid&&(this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+4,this.content.byteLength-4)))}};var rs=class extends Q{constructor(e,t){super(e,t),this.valid&&(this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78)))}};var QD={ftyp:Va,moov:_a,mvhd:Oa,moof:Fa,mdat:Na,sidx:ki,trak:Ua,mdia:Ga,mfhd:Ka,tkhd:Wa,traf:Xa,tfhd:Ja,tfdt:Za,trun:es,minf:za,sv3d:qa,st3d:ja,prhd:Ha,proj:Ya,equi:Qa,uuid:Ba,stbl:ts,stsd:is,avc1:rs,unknown:Er},$t=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!uo(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=QD[e];return i?new i(t,new a):new Er(t,new a)}};var Jt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;uo(t)&&((s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children))})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var WD=new TextDecoder("ascii"),zD=a=>WD.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",YD=a=>{let e=new ki(a,new $t),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},KD=(a,e)=>{let i=new $t().parse(a),r=new Jt(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},XD=a=>{let t=new $t().parse(a),i=new Jt(t),r={},s=i.findAll("uuid"),n=(0,Qy.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},JD=a=>{var r;let t=new $t().parse(a);return(r=new Jt(t).find("sidx"))==null?void 0:r.timescale},ZD=(a,e)=>{let i=new $t().parse(a),s=new Jt(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,f)=>d+f,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},eC=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new $t().parse(a),r=new Jt(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Gy={validateData:zD,parseInit:eC,getIndexRange:()=>{},parseSegments:YD,parseFeedableSegmentChunk:KD,getChunkEndTime:ZD,getServerLatencyTimestamps:XD,getTimescaleFromIndex:JD};var ns=O(Ye(),1);import{assertNonNullable as Cc,isNonNullable as Ky,isNullable as iC}from"@vkontakte/videoplayer-shared/es2018";import{assertNever as tC}from"@vkontakte/videoplayer-shared/es2018";var Wy={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},zy=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ss(a,t),r=i in Wy,s=r?Wy[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ss(u),d=l*2**((o-1)*8)+c,f=t+o,p;return f+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+f):p=new DataView(a.buffer,a.byteOffset+f,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:f,tagSize:f+d,value:p,valueSize:d}},ss=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ut=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ss(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:tC(e)}},Ri=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=zy(i);if(!e(r))return;r.type==="master"&&Ri(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Yy=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=zy(a);return Ri(r.value,({tag:s,type:n,value:o})=>(s===17143?e=ut(o,n):s===17026?t=ut(o,n):s===17029&&(i=ut(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Xy=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],rC=[231,22612,22743,167,171,163,160,175],aC=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Ri(a,({tag:f,type:p,value:h,valueSize:m})=>{if(f===21419){let b=ut(h,p);l=ss(b)}else f!==21420&&(l=void 0);return f===408125543?(e=h.byteOffset,t=h.byteOffset+m):f===357149030?s=!0:f===290298740?n=!0:f===2807729?i=ut(h,p):f===17545?r=ut(h,p):f===21420&&l===475249515?u=ut(h,p):f===374648427?Ri(h,({tag:b,type:S,value:y})=>b===30321?(c=ut(y,S)===1,!1):!0):s&&n&&(0,ns.default)(Xy,f)&&(o=!0),!o}),Cc(e,"Failed to parse webm Segment start"),Cc(t,"Failed to parse webm Segment end"),Cc(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},sC=a=>{if(iC(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},nC=(a,e)=>{let t=!1,i=!1,r=o=>Ky(o.time)&&Ky(o.position),s=[],n;return Ri(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=ut(l,u));break;case 183:break;case 241:n&&(n.position=ut(l,u));break;default:t&&(0,ns.default)(Xy,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},oC=a=>{let e=0,t=!1;try{Ri(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,ns.default)(rC,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,ns.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Jy={validateData:Yy,parseInit:aC,getIndexRange:sC,parseSegments:nC,parseFeedableSegmentChunk:oC};var Tt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Jy;case"mp4":return Gy}}throw new ReferenceError(`Unsupported mime type ${a}`)};var It=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Uc=O(TT(),1),jT=O(er(),1),HT=O(_T(),1),QT=O(ot(),1),qc=O(pr(),1);var OT=O(Ye(),1),Nc=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,OT.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as oB,isNullable as UT}from"@vkontakte/videoplayer-shared/es2018";var FT=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var NT=a=>{var e;try{let t=nB(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function nB(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
118
118
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
119
119
  (-(?<script>[a-z]{4}))?
120
120
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
121
121
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
122
122
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
123
123
  (?:-(?<privateuse>(?:${e})))?
124
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var OT=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ut=(a,e)=>{let t=a;t=(0,Fc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,FT.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Fc.default)(t,n,(o,u)=>_T(s)?o:_T(u)?s:(0,NT.default)(s,parseInt(u,10),"0"))}return t},uo=(a,e)=>{var w,P,B,M,R,Q,O,A,_,k,E,C,ne,Fe,ie,Y,ge,Se,ve,Ne,xt,Ot,ni,Ni,Nr,Xd,Jd,Zd,ep,tp,ip,rp,ap,sp,np,op,up,lp,cp,dp,pp,hp,fp,mp,bp,gp,Sp,vp,yp,Tp,Ip,Ep,xp,wp,Ap,Pp,kp,Rp,Lp,$p,Mp;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(et=>{var te,oi;return(oi=(te=et.textContent)==null?void 0:te.trim())!=null?oi:""}),o=(w=(0,UT.default)(n,0))!=null?w:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=s.getAttribute("publishTime"),c=s.getElementsByTagName("vk:Attrs")[0],f=c==null?void 0:c.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=c==null?void 0:c.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=c==null?void 0:c.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c==null?void 0:c.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:d?new Date(d).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let S,v=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],I=y.reduce((et,te)=>({...et,[te.id]:te.children}),{}),T=y.reduce((et,te)=>({...et,[te.id]:te.getAttribute("duration")}),{});v?S=OT(v):(0,Nc.default)(T).filter(et=>et).length&&!u?S=(0,Nc.default)(T).reduce((et,te)=>{var oi;return et+((oi=OT(te))!=null?oi:0)},0):m&&(S=parseInt(m,10));let x=0,V=(B=(P=s.getAttribute("profiles"))==null?void 0:P.split(","))!=null?B:[];for(let et of y.map(te=>te.id))for(let te of I[et]){let oi=(M=te.getAttribute("id"))!=null?M:"id"+(x++).toString(10),Ur=(R=te.getAttribute("mimeType"))!=null?R:"",nu=(Q=te.getAttribute("codecs"))!=null?Q:"",ou=(O=te.getAttribute("contentType"))!=null?O:Ur==null?void 0:Ur.split("/")[0],$E=(_=(A=te.getAttribute("profiles"))==null?void 0:A.split(","))!=null?_:[],Dp=(E=VT((k=te.getAttribute("lang"))!=null?k:""))!=null?E:{},Vs=(Fe=(ne=(C=te.querySelector("Label"))==null?void 0:C.textContent)==null?void 0:ne.trim())!=null?Fe:void 0,ME=te.querySelectorAll("Representation"),DE=te.querySelector("SegmentTemplate"),CE=(Y=(ie=te.querySelector("Role"))==null?void 0:ie.getAttribute("value"))!=null?Y:void 0,Ui=ou,ce={id:oi,language:Dp.language,isDefault:CE==="main",label:Vs,codecs:nu,hdr:Ui==="video"&&Oc(nu),mime:Ur,representations:[]};for(let ee of ME){let Ft=(ge=ee.getAttribute("lang"))!=null?ge:void 0,qr=(ve=(Se=Vs!=null?Vs:te.getAttribute("label"))!=null?Se:ee.getAttribute("label"))!=null?ve:void 0,_s=(Ot=(xt=(Ne=ee.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:xt.trim())!=null?Ot:"",ui=new URL(_s||o,e).toString(),Nt=(ni=ee.getAttribute("mimeType"))!=null?ni:Ur,Os=(Nr=(Ni=ee.getAttribute("codecs"))!=null?Ni:nu)!=null?Nr:"",Fs;if(ou==="text"){let Ut=ee.getAttribute("id")||"",Ns=((Xd=Dp.privateuse)==null?void 0:Xd.includes("x-auto"))||Ut.includes("_auto"),li=ee.querySelector("SegmentTemplate");if(li){let jr={representationId:(Jd=ee.getAttribute("id"))!=null?Jd:void 0,bandwidth:(Zd=ee.getAttribute("bandwidth"))!=null?Zd:void 0},Us=parseInt((ep=ee.getAttribute("bandwidth"))!=null?ep:"",10)/1e3,qs=(ip=parseInt((tp=li.getAttribute("startNumber"))!=null?tp:"",10))!=null?ip:1,qi=parseInt((rp=li.getAttribute("timescale"))!=null?rp:"",10),uu=(ap=li.querySelectorAll("SegmentTimeline S"))!=null?ap:[],ji=li.getAttribute("media");if(!ji)continue;let js=[],Hs=0,Qs="",Hi=0,Hr=qs,we=0;for(let tt of uu){let ci=parseInt((sp=tt.getAttribute("d"))!=null?sp:"",10),ze=parseInt((np=tt.getAttribute("r"))!=null?np:"",10)||0,qt=parseInt((op=tt.getAttribute("t"))!=null?op:"",10);we=Number.isFinite(qt)?qt:we;let di=ci/qi*1e3,jt=we/qi*1e3;for(let dt=0;dt<ze+1;dt++){let Ht=ut(ji,{...jr,segmentNumber:Hr.toString(10),segmentTime:(we+dt*ci).toString(10)}),Qi=(jt!=null?jt:0)+dt*di,Gr=Qi+di;Hr++,js.push({time:{from:Qi,to:Gr},url:Ht})}we+=(ze+1)*ci,Hs+=(ze+1)*di}Hi=we/qi*1e3,Qs=ut(ji,{...jr,segmentNumber:Hr.toString(10),segmentTime:we.toString(10)});let Qr={time:{from:Hi,to:1/0},url:Qs},wt={type:"template",baseUrl:ui,segmentTemplateUrl:ji,initUrl:"",totalSegmentsDurationMs:Hs,segments:js,nextSegmentBeyondManifest:Qr,timescale:qi};Fs={id:Ut,kind:"text",segmentReference:wt,profiles:[],duration:S,bitrate:Us,mime:"",codecs:"",width:0,height:0,isAuto:Ns}}else Fs={id:Ut,isAuto:Ns,kind:"text",url:ui}}else{let Ut=(lp=(up=ee.getAttribute("contentType"))!=null?up:Nt==null?void 0:Nt.split("/")[0])!=null?lp:ou,Ns=(dp=(cp=te.getAttribute("profiles"))==null?void 0:cp.split(","))!=null?dp:[],li=parseInt((pp=ee.getAttribute("width"))!=null?pp:"",10),jr=parseInt((hp=ee.getAttribute("height"))!=null?hp:"",10),Us=parseInt((fp=ee.getAttribute("bandwidth"))!=null?fp:"",10)/1e3,qs=(mp=ee.getAttribute("frameRate"))!=null?mp:"",qi=(bp=ee.getAttribute("quality"))!=null?bp:void 0,uu=qs?BT(qs):void 0,ji=(gp=ee.getAttribute("id"))!=null?gp:"id"+(x++).toString(10),js=Ut==="video"?`${jr}p`:Ut==="audio"?`${Us}Kbps`:Os,Hs=`${ji}@${js}`,Qs=[...V,...$E,...Ns],Hi,Hr=ee.querySelector("SegmentBase"),we=(Sp=ee.querySelector("SegmentTemplate"))!=null?Sp:DE;if(Hr){let wt=(yp=(vp=ee.querySelector("SegmentBase Initialization"))==null?void 0:vp.getAttribute("range"))!=null?yp:"",[tt,ci]=wt.split("-").map(Ht=>parseInt(Ht,10)),ze={from:tt,to:ci},qt=(Tp=ee.querySelector("SegmentBase"))==null?void 0:Tp.getAttribute("indexRange"),[di,jt]=qt?qt.split("-").map(Ht=>parseInt(Ht,10)):[],dt=qt?{from:di,to:jt}:void 0;Hi={type:"byteRange",url:ui,initRange:ze,indexRange:dt}}else if(we){let wt={representationId:(Ip=ee.getAttribute("id"))!=null?Ip:void 0,bandwidth:(Ep=ee.getAttribute("bandwidth"))!=null?Ep:void 0},tt=parseInt((xp=we.getAttribute("timescale"))!=null?xp:"",10),ci=(wp=we.getAttribute("initialization"))!=null?wp:"",ze=we.getAttribute("media"),qt=(Pp=parseInt((Ap=we.getAttribute("startNumber"))!=null?Ap:"",10))!=null?Pp:1,di=ut(ci,wt);if(!ze)throw new ReferenceError("No media attribute in SegmentTemplate");let jt=(kp=we.querySelectorAll("SegmentTimeline S"))!=null?kp:[],dt=[],Ht=0,Qi="",Gr=0;if(jt.length){let Gs=qt,it=0;for(let Gi of jt){let pt=parseInt((Rp=Gi.getAttribute("d"))!=null?Rp:"",10),pi=parseInt((Lp=Gi.getAttribute("r"))!=null?Lp:"",10)||0,Ws=parseInt(($p=Gi.getAttribute("t"))!=null?$p:"",10);it=Number.isFinite(Ws)?Ws:it;let lu=pt/tt*1e3,cu=it/tt*1e3;for(let zs=0;zs<pi+1;zs++){let VE=ut(ze,{...wt,segmentNumber:Gs.toString(10),segmentTime:(it+zs*pt).toString(10)}),Cp=(cu!=null?cu:0)+zs*lu,_E=Cp+lu;Gs++,dt.push({time:{from:Cp,to:_E},url:VE})}it+=(pi+1)*pt,Ht+=(pi+1)*lu}Gr=it/tt*1e3,Qi=ut(ze,{...wt,segmentNumber:Gs.toString(10),segmentTime:it.toString(10)})}else if(rB(S)){let it=parseInt((Mp=we.getAttribute("duration"))!=null?Mp:"",10)/tt*1e3,Gi=Math.ceil(S/it),pt=0;for(let pi=1;pi<Gi;pi++){let Ws=ut(ze,{...wt,segmentNumber:pi.toString(10),segmentTime:pt.toString(10)});dt.push({time:{from:pt,to:pt+it},url:Ws}),pt+=it}Gr=pt,Qi=ut(ze,{...wt,segmentNumber:Gi.toString(10),segmentTime:pt.toString(10)})}let BE={time:{from:Gr,to:1/0},url:Qi};Hi={type:"template",baseUrl:ui,segmentTemplateUrl:ze,initUrl:di,totalSegmentsDurationMs:Ht,segments:dt,nextSegmentBeyondManifest:BE,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ut||!Nt)continue;let Qr={video:"video",audio:"audio",text:"text"}[Ut];if(!Qr)continue;Ui||(Ui=Qr),Fs={id:Hs,kind:Qr,segmentReference:Hi,profiles:Qs,duration:S,bitrate:Us,mime:Nt,codecs:Os,width:li,height:jr,fps:uu,quality:qi}}ce.language||(ce.language=Ft),ce.label||(ce.label=qr),ce.mime||(ce.mime=Nt),ce.codecs||(ce.codecs=Os),ce.hdr||(ce.hdr=Ui==="video"&&Oc(Os)),ce.representations.push(Fs)}if(Ui){let ee=r[Ui].find(Ft=>Ft.id===ce.id);if(ee&&ce.representations.every(Ft=>Ft.segmentReference.type==="template"))for(let Ft of ee.representations){let qr=ce.representations.find(Nt=>Nt.id===Ft.id),_s=qr==null?void 0:qr.segmentReference,ui=Ft.segmentReference;ui.segments.push(..._s.segments),ui.nextSegmentBeyondManifest=_s.nextSegmentBeyondManifest}else r[Ui].push(ce)}}return{duration:S,streams:r,baseUrls:n,live:g}};var Uc=N(St(),1);import{videoSizeToQuality as aB}from"@vkontakte/videoplayer-shared/es2018";var qT=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:aB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},jT=({id:a,bitrate:e})=>({id:a,bitrate:e}),HT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),QT=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),qc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Uc.default)(i.split("."),0),isDefault:r}),jc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Uc.default)(r.split("."),0)}),Hc=a=>"url"in a,Qe=a=>a.type==="template";import{isNonNullable as GT}from"@vkontakte/videoplayer-shared/es2018";var F=(a,e)=>GT(a)&&GT(e)&&a.readyState==="open"&&sB(a,e);function sB(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var os=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Li(0);this.currentLowLatencySegmentLength$=new Li(0);this.currentSegmentLength$=new Li(0);this.onLastSegment$=new Li(!1);this.fullyBuffered$=new Li(!1);this.playingRepresentation$=new Li(void 0);this.playingRepresentationInit$=new Li(void 0);this.error$=new oB;this.gaps=[];this.subscription=new uB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);_e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Uy(this.sourceBuffer),this.subscription.add(Qc(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Qc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!F(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ir(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);_e(i,"No init buffer for starting representation"),_e(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);_e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ee(s)||Ee(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),_e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Pr(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);_e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ee(s)||Ee(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),_e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Pr(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Zt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,po.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(h=>h.id===d);c&&this.representations.set(d,c);let f=this.representations.get(d);if(!f||!Qe(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);_e(r);let s=this.segments.get(i);_e(s,"No segments for starting representation");let n=this.initData.get(i);if(_e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,Zt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);_e(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ee(o)||Ee(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),_e(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Pr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!Ee(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ee(e)||Ee(this.downloadingRepresentationId)||Ee(this.playingRepresentationId)||Ee(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||Pr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(_e(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);Pr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(s=c)}if(isFinite(this.bufferLimit)&&Ir(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,co.default)(u,r))d="high";else{let c=(0,$i.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,$i.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;Pr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,po.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,po.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Qe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(s=(0,$i.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;_e(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,$i.default)(e,-1))==null?void 0:t.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Qe(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),d=ut(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let g=p<=i&&h>=i,S=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+v||r<v&&h-p>=v||h<=i+v;return(f==="none"||f==="partially_ejected"&&S&&y&&this.sourceBuffer&&F(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&S&&y});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let f=s;f<n.length&&(o<=d||u<=c);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Qe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Zt(o,async function*(){let d=Gc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=lo(),!d)return;let c=new DataView(d),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(c);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),It(d)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Zt(n,async function*(){let u=Gc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Qc(window,"online").pipe(nB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=lo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Qe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,$i.default)(e,0).byte.from,to:(0,$i.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=lo(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Qe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=lo();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,co.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!F(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!F(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let d=l.byte.from-i,c=l.byte.to-i,f=c-d+1,p=d<r,h=c<=r;if(!p)continue;let m=Tt(o.mime);if(l.status==="downloading"&&h){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,f);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===f?g:m.parseFeedableSegmentChunk(g);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(Ee(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer))){!this.isLive&&U.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Mt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Hc(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Tr(()=>(0,WT.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Zt(this.destroyAbortController.signal,async function*(){let o=Gc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let f=d;this.isLive&&Qe(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Mt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ee(e))return!1;let r=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:f}=u[d],p=l[l.length-1];p.to>=c?p.to=Math.max(p.to,f):l.push(u[d])}return l},o=u=>{var d;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Hc(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let f of this.segments.values())for(let p of f)(0,co.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let f={time:{from:l,to:d},url:"",status:"none"};o(f)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ee(e)?0:me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Tr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ee(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||Ee(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Mt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ei=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var ho=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as us,assertNever as zT,fromEvent as YT,merge as lB,now as ls,Subscription as cB,Subject as KT,ValueSubject as Wc,flattenObject as kr,ErrorCategory as cs}from"@vkontakte/videoplayer-shared/es2018";var fo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var bo=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Wc(void 0);this.lastConnectionReused$=new Wc(void 0);this.lastRequestFirstBytes$=new Wc(void 0);this.recoverableError$=new KT;this.error$=new KT;this.abortAllController=new Z;this.subscription=new cB;this.fetchManifest=us(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=fo(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(mo);return r?(t.log("success",kr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",kr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=us(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var B,M;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let R=new URL(l,location.href);R.searchParams.append("bytes",`${i.from}-${i.to}`),l=R.toString();break}default:zT(t)}this.requestQuic&&(l=ei(l));let f=this.abortAllController.signal,p;if(n){let R=new Z;if(p=lB(YT(this.abortAllController.signal,"abort"),YT(n,"abort")).subscribe(()=>{try{R.abort()}catch(Q){mo(Q)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch(Q){mo(Q)}f=R.signal}let h=ls();c.log("startRequest",kr({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:h}));let m=yield this.doFetch(l,{priority:s,headers:d,signal:f}),g=ls();if(!m)return c.error("error",{message:"No response in request"}),c.end(),p==null||p.unsubscribe(),null;if((B=this.throughputEstimator)==null||B.addRawRtt(g-h),!m.ok||!m.body){p==null||p.unsubscribe();let R=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:R}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){p==null||p.unsubscribe();let R=ls(),Q={requestStartedAt:h,requestEndedAt:R,duration:R-h};return c.log("endRequest",kr(Q)),c.end(),m.arrayBuffer()}let[S,v]=m.body.tee(),y=S.getReader();o&&((M=this.throughputEstimator)==null||M.trackStream(v,u));let I=0,T=new Uint8Array(0),x=!1,V=R=>{p==null||p.unsubscribe(),x=!0,mo(R)},$=us(f,async function*({done:R,value:Q}){if(I===0&&this.lastRequestFirstBytes$.next(ls()-h),f.aborted){p==null||p.unsubscribe();return}if(!R&&Q){let O=new Uint8Array(T.length+Q.length);O.set(T),O.set(Q,T.length),T=O,I+=Q.byteLength,r==null||r(new DataView(T.buffer),I),yield y==null?void 0:y.read().then($,V)}}.bind(this));yield y==null?void 0:y.read().then($,V),p==null||p.unsubscribe();let w=ls(),P={failed:x,requestStartedAt:h,requestEndedAt:w,duration:w-h};return x?(c.error("endRequest",kr(P)),c.end(),null):(c.log("endRequest",kr(P)),c.end(),T.buffer)}.bind(this));this.fetchByteRangeRepresentation=us(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let f=new DataView(c,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,h.from-n,h.to-h.from+1);else{let v=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=us(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=ho(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:zT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ze(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:cs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:cs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:cs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:cs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:cs.FATAL})}}},mo=a=>{if(!It(a))throw a};var Dt=(a,e,t)=>t*e+(1-t)*a,zc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,XT=(a,e,t,i)=>{let r=0,s=t,n=zc(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as dB,ValueSubject as JT}from"@vkontakte/videoplayer-shared/es2018";var ti=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new JT(e.initial),this.debounced$=new JT(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ke(`raw_${t}`),this.smoothedSeries$=new ke(`smoothed_${t}`),this.reportedSeries$=new ke(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(dB(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 go=class extends ti{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Dt(this.slow,e,this.params.emaAlphaSlow),this.fast=Dt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var So=class extends ti{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=zc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);let i=XT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var vo=class extends ti{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Ct=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new go({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new So({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 vo({initial:e,label:"liveEdgeDelay",...t})}};var Rr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as pB,ValueSubject as hB}from"@vkontakte/videoplayer-shared/es2018";var ds=class a{constructor(e,t){this.currentRepresentation$=new hB(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(!pB(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Qe(t.segmentReference))}};var To=N(St(),1);import{assertNever as Io}from"@vkontakte/videoplayer-shared/es2018";var ZT=(a,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:n}=U.video,o=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return a.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return u&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return Io(l)}})},yo=a=>{let{webmDecodingInfo:e}=U.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Io(a)}return[t,i]},eI=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...yo(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(U.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...yo(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...yo(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...yo(a),...r,"HLS","HLS_ONDEMAND"];default:Io(e)}return U.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},tI=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=U.device.isMac&&U.browser.isSafari;if(U.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Io(a)}else U.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Yc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Eo=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,To.default)(t.value.split("."),0)}for(let t of a){let i=(0,To.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,To.default)(e.value.split("."),0)};var TB=["timeupdate","progress","play","seeked","stalled","waiting"],IB=["timeupdate","progress","loadeddata","playing","seeked"];var Ao=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new aI;this.representationSubscription=new aI;this.state$=new j("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentAudioRepresentation$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new wo;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.currentLiveTextRepresentation$=new ae(null);this.isLive$=new ae(!1);this.isActiveLive$=new ae(!1);this.isLowLatency$=new ae(!1);this.liveDuration$=new ae(0);this.liveSeekableDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(0);this.liveStreamStatus$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLatency$=new ae(void 0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.currentStallDuration$=new ae(0);this.videoLastDataObtainedTimestamp$=new ae(0);this.fetcherRecoverableError$=new wo;this.fetcherError$=new wo;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new wo;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=Xc(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:lt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Xc(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:lt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=uo(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=oo(e))!=null?n:{id:"ManifestParsing",category:lt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,f,p,h;return!!((f=(c=this.element)==null?void 0:c.canPlayType)!=null&&f.call(c,l)&&((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),c=new Set(d.map(({codecs:p})=>p)),f=Eo(c);if(f&&(r[u]=d.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);U.display.isHDR&&p&&h?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",hs(s)),s}.bind(this));this.initRepresentations=Xc(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",hs({initialVideo:e,initialAudio:t,sourceHls:i})),Lr(this.manifest),Lr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Bt(p,"error").pipe(xo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:lt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?_n():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&hr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new os("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],fs(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new os("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ds.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ds(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Mi(...IB.map(p=>Bt(this.element,p))).pipe(Mr(p=>this.element?me(this.element.buffered,this.element.currentTime*1e3):0),ps(),vB(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Mi(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ps()).subscribe(h=>this.liveStreamEndTimestamp=Zc())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Jc(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Bt(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add($r({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Mr(({isActiveLive:h,isLowLatency:m})=>h&&m),ps()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Rr(this.element,1)})),this.representationSubscription.add($r({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(xo(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add($r({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(xo(({isLive:h})=>h),ps((h,m)=>m.bufferLength<h.bufferLength),Mr(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let S=zt(this.manifestUrlString,2);return(h/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add($r({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>v&&(T=1+Math.sign(I)*y),Rr(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var T,x;return(x=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?x:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add($r({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(yB(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=zt(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,x=isFinite(h)?h:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(V?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&x<y?w="live_forward_buffering":x<y+T&&(w="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let P=p-(y+I),B=this.normolizeLiveOffset(Math.trunc(S+P/g)),M=Math.abs(B-S),R=0;!h||M<=this.tuning.dashCmafLive.offsetCalculationError?R=S:B>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(R=B),this.manifestUrlString=le(this.manifestUrlString,R,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:lt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Mi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Mr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Mi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Mr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=$r({allBuffersFull:l,someBufferEnded:d}).pipe(ps(),Mr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),xo(p=>p));if(this.representationSubscription.add(Mi(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:lt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Mi(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:lt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,ed.default)((0,ed.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Qe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&fs(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Jc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:lt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new bo({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;Lr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Zc()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Lr(this.element),this.state$.setState("running"),this.subscription.add(Mi(...TB.map(e=>Bt(this.element,e)),Bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:lt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Bt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,m,g,S,v,y,I,T,x,V;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=Zc(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?S:0,l=(y=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?y:0,d=(T=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?T:0,c=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&d<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||f)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let $=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive($).catch(w=>{this.error$.next({id:"stallIntervalCallback",category:lt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:w})}),r.liveLastOffset=$}else{let $=this.element.currentTime*1e3;(x=this.videoBufferManager)==null||x.maintain($),(V=this.audioBufferManager)==null||V.maintain($),r.position=$}this.tracer.log("stallIntervalCallback",hs(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Jc(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:lt.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;Lr(this.element),Lr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(rI(this.element)||rI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",hs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;fs(this.element)&&fs(this.source)&&fs(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=SB(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",hs(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var Po=class{constructor(e,t){this.fov=e,this.orientation=t}};var ko=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var nI=`attribute vec2 a_vertex;
124
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var qT=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},lt=(a,e)=>{let t=a;t=(0,Uc.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,jT.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Uc.default)(t,n,(o,u)=>UT(s)?o:UT(u)?s:(0,HT.default)(s,parseInt(u,10),"0"))}return t},lo=(a,e)=>{var P,k,V,D,_,Y,J,T,R,x,w,B,ne,Fe,ie,W,ge,Se,ve,Ne,xt,Ot,ni,Ni,Nr,ep,tp,ip,rp,ap,sp,np,op,up,lp,cp,dp,pp,hp,fp,mp,bp,gp,Sp,vp,yp,Tp,Ip,Ep,xp,wp,Ap,Pp,kp,Rp,Lp,$p,Mp,Dp,Cp,Bp;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(et=>{var te,oi;return(oi=(te=et.textContent)==null?void 0:te.trim())!=null?oi:""}),o=(P=(0,QT.default)(n,0))!=null?P:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],f=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,h=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b;u&&(b={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:f?new Date(f).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:h==="yes"});let S,y=s.getAttribute("mediaPresentationDuration"),v=[...s.getElementsByTagName("Period")],I=v.reduce((et,te)=>({...et,[te.id]:te.children}),{}),E=v.reduce((et,te)=>({...et,[te.id]:te.getAttribute("duration")}),{});y?S=qT(y):(0,qc.default)(E).filter(et=>et).length&&!u?S=(0,qc.default)(E).reduce((et,te)=>{var oi;return et+((oi=qT(te))!=null?oi:0)},0):m&&(S=parseInt(m,10));let A=0,M=(V=(k=s.getAttribute("profiles"))==null?void 0:k.split(","))!=null?V:[];for(let et of v.map(te=>te.id))for(let te of I[et]){let oi=(D=te.getAttribute("id"))!=null?D:"id"+(A++).toString(10),Ur=(_=te.getAttribute("mimeType"))!=null?_:"",nu=(Y=te.getAttribute("codecs"))!=null?Y:"",ou=(J=te.getAttribute("contentType"))!=null?J:Ur==null?void 0:Ur.split("/")[0],CE=(R=(T=te.getAttribute("profiles"))==null?void 0:T.split(","))!=null?R:[],Vp=(w=NT((x=te.getAttribute("lang"))!=null?x:""))!=null?w:{},Vs=(Fe=(ne=(B=te.querySelector("Label"))==null?void 0:B.textContent)==null?void 0:ne.trim())!=null?Fe:void 0,BE=te.querySelectorAll("Representation"),VE=te.querySelector("SegmentTemplate"),_E=(W=(ie=te.querySelector("Role"))==null?void 0:ie.getAttribute("value"))!=null?W:void 0,Ui=ou,ce={id:oi,language:Vp.language,isDefault:_E==="main",label:Vs,codecs:nu,hdr:Ui==="video"&&Nc(nu),mime:Ur,representations:[]};for(let ee of BE){let Ft=(ge=ee.getAttribute("lang"))!=null?ge:void 0,qr=(ve=(Se=Vs!=null?Vs:te.getAttribute("label"))!=null?Se:ee.getAttribute("label"))!=null?ve:void 0,_s=(Ot=(xt=(Ne=ee.querySelector("BaseURL"))==null?void 0:Ne.textContent)==null?void 0:xt.trim())!=null?Ot:"",ui=new URL(_s||o,e).toString(),Nt=(ni=ee.getAttribute("mimeType"))!=null?ni:Ur,Os=(Nr=(Ni=ee.getAttribute("codecs"))!=null?Ni:nu)!=null?Nr:"",Fs;if(ou==="text"){let Ut=ee.getAttribute("id")||"",Ns=((ep=Vp.privateuse)==null?void 0:ep.includes("x-auto"))||Ut.includes("_auto"),li=ee.querySelector("SegmentTemplate");if(li){let jr={representationId:(tp=ee.getAttribute("id"))!=null?tp:void 0,bandwidth:(ip=ee.getAttribute("bandwidth"))!=null?ip:void 0},Us=parseInt((rp=ee.getAttribute("bandwidth"))!=null?rp:"",10)/1e3,qs=(sp=parseInt((ap=li.getAttribute("startNumber"))!=null?ap:"",10))!=null?sp:1,qi=parseInt((np=li.getAttribute("timescale"))!=null?np:"",10),uu=(op=li.querySelectorAll("SegmentTimeline S"))!=null?op:[],ji=li.getAttribute("media");if(!ji)continue;let js=[],Hs=0,Qs="",Hi=0,Hr=qs,we=0;for(let tt of uu){let ci=parseInt((up=tt.getAttribute("d"))!=null?up:"",10),ze=parseInt((lp=tt.getAttribute("r"))!=null?lp:"",10)||0,qt=parseInt((cp=tt.getAttribute("t"))!=null?cp:"",10);we=Number.isFinite(qt)?qt:we;let di=ci/qi*1e3,jt=we/qi*1e3;for(let pt=0;pt<ze+1;pt++){let Ht=lt(ji,{...jr,segmentNumber:Hr.toString(10),segmentTime:(we+pt*ci).toString(10)}),Qi=(jt!=null?jt:0)+pt*di,Gr=Qi+di;Hr++,js.push({time:{from:Qi,to:Gr},url:Ht})}we+=(ze+1)*ci,Hs+=(ze+1)*di}Hi=we/qi*1e3,Qs=lt(ji,{...jr,segmentNumber:Hr.toString(10),segmentTime:we.toString(10)});let Qr={time:{from:Hi,to:1/0},url:Qs},wt={type:"template",baseUrl:ui,segmentTemplateUrl:ji,initUrl:"",totalSegmentsDurationMs:Hs,segments:js,nextSegmentBeyondManifest:Qr,timescale:qi};Fs={id:Ut,kind:"text",segmentReference:wt,profiles:[],duration:S,bitrate:Us,mime:"",codecs:"",width:0,height:0,isAuto:Ns}}else Fs={id:Ut,isAuto:Ns,kind:"text",url:ui}}else{let Ut=(pp=(dp=ee.getAttribute("contentType"))!=null?dp:Nt==null?void 0:Nt.split("/")[0])!=null?pp:ou,Ns=(fp=(hp=te.getAttribute("profiles"))==null?void 0:hp.split(","))!=null?fp:[],li=parseInt((mp=ee.getAttribute("width"))!=null?mp:"",10),jr=parseInt((bp=ee.getAttribute("height"))!=null?bp:"",10),Us=parseInt((gp=ee.getAttribute("bandwidth"))!=null?gp:"",10)/1e3,qs=(Sp=ee.getAttribute("frameRate"))!=null?Sp:"",qi=(vp=ee.getAttribute("quality"))!=null?vp:void 0,uu=qs?FT(qs):void 0,ji=(yp=ee.getAttribute("id"))!=null?yp:"id"+(A++).toString(10),js=Ut==="video"?`${jr}p`:Ut==="audio"?`${Us}Kbps`:Os,Hs=`${ji}@${js}`,Qs=[...M,...CE,...Ns],Hi,Hr=ee.querySelector("SegmentBase"),we=(Tp=ee.querySelector("SegmentTemplate"))!=null?Tp:VE;if(Hr){let wt=(Ep=(Ip=ee.querySelector("SegmentBase Initialization"))==null?void 0:Ip.getAttribute("range"))!=null?Ep:"",[tt,ci]=wt.split("-").map(Ht=>parseInt(Ht,10)),ze={from:tt,to:ci},qt=(xp=ee.querySelector("SegmentBase"))==null?void 0:xp.getAttribute("indexRange"),[di,jt]=qt?qt.split("-").map(Ht=>parseInt(Ht,10)):[],pt=qt?{from:di,to:jt}:void 0;Hi={type:"byteRange",url:ui,initRange:ze,indexRange:pt}}else if(we){let wt={representationId:(wp=ee.getAttribute("id"))!=null?wp:void 0,bandwidth:(Ap=ee.getAttribute("bandwidth"))!=null?Ap:void 0},tt=parseInt((Pp=we.getAttribute("timescale"))!=null?Pp:"",10),ci=(kp=we.getAttribute("initialization"))!=null?kp:"",ze=we.getAttribute("media"),qt=(Lp=parseInt((Rp=we.getAttribute("startNumber"))!=null?Rp:"",10))!=null?Lp:1,di=lt(ci,wt);if(!ze)throw new ReferenceError("No media attribute in SegmentTemplate");let jt=($p=we.querySelectorAll("SegmentTimeline S"))!=null?$p:[],pt=[],Ht=0,Qi="",Gr=0;if(jt.length){let Gs=qt,it=0;for(let Gi of jt){let ht=parseInt((Mp=Gi.getAttribute("d"))!=null?Mp:"",10),pi=parseInt((Dp=Gi.getAttribute("r"))!=null?Dp:"",10)||0,Ws=parseInt((Cp=Gi.getAttribute("t"))!=null?Cp:"",10);it=Number.isFinite(Ws)?Ws:it;let lu=ht/tt*1e3,cu=it/tt*1e3;for(let zs=0;zs<pi+1;zs++){let FE=lt(ze,{...wt,segmentNumber:Gs.toString(10),segmentTime:(it+zs*ht).toString(10)}),_p=(cu!=null?cu:0)+zs*lu,NE=_p+lu;Gs++,pt.push({time:{from:_p,to:NE},url:FE})}it+=(pi+1)*ht,Ht+=(pi+1)*lu}Gr=it/tt*1e3,Qi=lt(ze,{...wt,segmentNumber:Gs.toString(10),segmentTime:it.toString(10)})}else if(oB(S)){let it=parseInt((Bp=we.getAttribute("duration"))!=null?Bp:"",10)/tt*1e3,Gi=Math.ceil(S/it),ht=0;for(let pi=1;pi<Gi;pi++){let Ws=lt(ze,{...wt,segmentNumber:pi.toString(10),segmentTime:ht.toString(10)});pt.push({time:{from:ht,to:ht+it},url:Ws}),ht+=it}Gr=ht,Qi=lt(ze,{...wt,segmentNumber:Gi.toString(10),segmentTime:ht.toString(10)})}let OE={time:{from:Gr,to:1/0},url:Qi};Hi={type:"template",baseUrl:ui,segmentTemplateUrl:ze,initUrl:di,totalSegmentsDurationMs:Ht,segments:pt,nextSegmentBeyondManifest:OE,timescale:tt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ut||!Nt)continue;let Qr={video:"video",audio:"audio",text:"text"}[Ut];if(!Qr)continue;Ui||(Ui=Qr),Fs={id:Hs,kind:Qr,segmentReference:Hi,profiles:Qs,duration:S,bitrate:Us,mime:Nt,codecs:Os,width:li,height:jr,fps:uu,quality:qi}}ce.language||(ce.language=Ft),ce.label||(ce.label=qr),ce.mime||(ce.mime=Nt),ce.codecs||(ce.codecs=Os),ce.hdr||(ce.hdr=Ui==="video"&&Nc(Os)),ce.representations.push(Fs)}if(Ui){let ee=r[Ui].find(Ft=>Ft.id===ce.id);if(ee&&ce.representations.every(Ft=>Ft.segmentReference.type==="template"))for(let Ft of ee.representations){let qr=ce.representations.find(Nt=>Nt.id===Ft.id),_s=qr==null?void 0:qr.segmentReference,ui=Ft.segmentReference;ui.segments.push(..._s.segments),ui.nextSegmentBeyondManifest=_s.nextSegmentBeyondManifest}else r[Ui].push(ce)}}return{duration:S,streams:r,baseUrls:n,live:b}};var jc=O(ot(),1);import{videoSizeToQuality as uB}from"@vkontakte/videoplayer-shared/es2018";var GT=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:uB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},WT=({id:a,bitrate:e})=>({id:a,bitrate:e}),zT=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),YT=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Hc=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,jc.default)(i.split("."),0),isDefault:r}),Qc=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,jc.default)(r.split("."),0)}),Gc=a=>"url"in a,Qe=a=>a.type==="template";import{isNonNullable as KT}from"@vkontakte/videoplayer-shared/es2018";var N=(a,e)=>KT(a)&&KT(e)&&a.readyState==="open"&&lB(a,e);function lB(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var os=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Li(0);this.currentLowLatencySegmentLength$=new Li(0);this.currentSegmentLength$=new Li(0);this.onLastSegment$=new Li(!1);this.fullyBuffered$=new Li(!1);this.playingRepresentation$=new Li(void 0);this.playingRepresentationInit$=new Li(void 0);this.error$=new dB;this.gaps=[];this.subscription=new pB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);_e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Hy(this.sourceBuffer),this.subscription.add(Wc(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Wc(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!N(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ir(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);_e(i,"No init buffer for starting representation"),_e(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);_e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ee(s)||Ee(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),_e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Pr(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);_e(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Ee(s)||Ee(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),_e(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Pr(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Zt(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,ho.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!Qe(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);_e(r);let s=this.segments.get(i);_e(s,"No segments for starting representation");let n=this.initData.get(i);if(_e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,Zt(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);_e(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Ee(o)||Ee(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),_e(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Pr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!Ee(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Ee(e)||Ee(this.downloadingRepresentationId)||Ee(this.playingRepresentationId)||Ee(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||Pr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(_e(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Pr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Ir(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,po.default)(u,r))c="high";else{let d=(0,$i.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,$i.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;Pr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,ho.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,ho.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Qe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,$i.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;_e(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,$i.default)(e,-1))==null?void 0:t.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!Qe(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=lt(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let b=p<=i&&h>=i,S=p>i||b||m===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=i+y||r<y&&h-p>=y||h<=i+y;return(f==="none"||f==="partially_ejected"&&S&&v&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&S&&v});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=s;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Qe(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Zt(o,async function*(){let c=zc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=co(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Qe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Zt(n,async function*(){let u=zc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Wc(window,"online").pipe(cB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=co(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Qe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,$i.default)(e,0).byte.from,to:(0,$i.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=co(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Qe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=co();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,po.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,f=d-c+1,p=c<r,h=d<=r;if(!p)continue;let m=Tt(o.mime);if(l.status==="downloading"&&h){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-c),u.loadedBytes>u.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===f?b:m.parseFeedableSegmentChunk(b);S!=null&&S.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){var i;if(!(Ee(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Mt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Gc(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Tr(()=>(0,XT.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Zt(this.destroyAbortController.signal,async function*(){let o=zc(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&Qe(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Mt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Ee(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:f}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,f):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Gc(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let f of this.segments.values())for(let p of f)(0,po.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let f={time:{from:l,to:c},url:"",status:"none"};o(f)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Ee(e)?0:me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Tr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ee(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||Ee(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Mt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ei=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var fo=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as us,assertNever as JT,fromEvent as ZT,merge as hB,now as ls,Subscription as fB,Subject as eI,ValueSubject as Yc,flattenObject as kr,ErrorCategory as cs}from"@vkontakte/videoplayer-shared/es2018";var mo=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var go=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Yc(void 0);this.lastConnectionReused$=new Yc(void 0);this.lastRequestFirstBytes$=new Yc(void 0);this.recoverableError$=new eI;this.error$=new eI;this.abortAllController=new Z;this.subscription=new fB;this.fetchManifest=us(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=mo(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(bo);return r?(t.log("success",kr({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",kr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=us(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var _,Y,J;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(c,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),c=T.toString();break}default:JT(t)}this.requestQuic&&(c=ei(c));let p=this.abortAllController.signal,h;if(n){let T=new Z;if(h=hB(ZT(this.abortAllController.signal,"abort"),ZT(n,"abort")).subscribe(()=>{try{T.abort()}catch(R){bo(R)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(R){bo(R)}p=T.signal}let m=ls();f.log("startRequest",kr({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(c,{priority:s,headers:d,signal:p}),S=ls();if(!b)return f.error("error",{message:"No response in request"}),f.end(),h==null||h.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(S-m),!b.ok||!b.body){h==null||h.unsubscribe();let T=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:T}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){h==null||h.unsubscribe();let T=ls(),R={requestStartedAt:m,requestEndedAt:T,duration:T-m};return f.log("endRequest",kr(R)),f.end(),b.arrayBuffer()}let y=b.body;if(o){let T;[y,T]=b.body.tee(),(Y=this.throughputEstimator)==null||Y.trackStream(T,u)}let v=y.getReader(),I,E=parseInt((J=b.headers.get("content-length"))!=null?J:"",10);Number.isFinite(E)&&(I=E),!I&&i&&(I=i.to-i.from+1);let A=0,M=I?new Uint8Array(I):new Uint8Array(0),L=!1,P=T=>{h==null||h.unsubscribe(),L=!0,bo(T)},k=us(p,async function*({done:T,value:R}){if(A===0&&this.lastRequestFirstBytes$.next(ls()-m),p.aborted){h==null||h.unsubscribe();return}if(!T&&R){if(l&&I)M.set(R,A),A+=R.byteLength;else{let x=new Uint8Array(M.length+R.length);x.set(M),x.set(R,M.length),M=x,A+=R.byteLength}r==null||r(new DataView(M.buffer),A),yield v==null?void 0:v.read().then(k,P)}}.bind(this));yield v==null?void 0:v.read().then(k,P),h==null||h.unsubscribe();let V=ls(),D={failed:L,requestStartedAt:m,requestEndedAt:V,duration:V-m};return L?(f.error("endRequest",kr(D)),f.end(),null):(f.log("endRequest",kr(D)),f.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=us(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let y=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!y)return null;m=new DataView(y)}let b=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=us(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=fo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:JT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ze(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:cs.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:cs.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:cs.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:cs.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:cs.FATAL})}}},bo=a=>{if(!It(a))throw a};var Dt=(a,e,t)=>t*e+(1-t)*a,Kc=(a,e)=>a.reduce((t,i)=>t+i,0)/e,tI=(a,e,t,i)=>{let r=0,s=t,n=Kc(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as mB,ValueSubject as iI}from"@vkontakte/videoplayer-shared/es2018";var ti=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new iI(e.initial),this.debounced$=new iI(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ke(`raw_${t}`),this.smoothedSeries$=new ke(`smoothed_${t}`),this.reportedSeries$=new ke(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(mB(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var So=class extends ti{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Dt(this.slow,e,this.params.emaAlphaSlow),this.fast=Dt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var vo=class extends ti{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Kc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Dt(this.emaSmoothed,e,this.params.emaAlpha);let i=tI(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var yo=class extends ti{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Dt(this.smoothed,t,this.params.emaAlpha):t}};var Ct=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new So({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new vo({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new yo({initial:e,label:"liveEdgeDelay",...t})}};var Rr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as bB,ValueSubject as gB}from"@vkontakte/videoplayer-shared/es2018";var ds=class a{constructor(e,t){this.currentRepresentation$=new gB(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!bB(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Qe(t.segmentReference))}};var Io=O(ot(),1);import{assertNever as Xc}from"@vkontakte/videoplayer-shared/es2018";var To=a=>{let{webmDecodingInfo:e}=F.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:Xc(a)}return[t,i]},rI=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...To(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(F.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...To(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...To(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...To(a),...r,"HLS","HLS_ONDEMAND"];default:Xc(e)}return F.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},aI=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=F.device.isMac&&F.browser.isSafari;if(F.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Xc(a)}else F.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Jc=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Eo=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Io.default)(t.value.split("."),0)}for(let t of a){let i=(0,Io.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Io.default)(e.value.split("."),0)};var wB=["timeupdate","progress","play","seeked","stalled","waiting"],AB=["timeupdate","progress","loadeddata","playing","seeked"];var Ao=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new oI;this.representationSubscription=new oI;this.state$=new q("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentAudioRepresentation$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new wo;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.currentLiveTextRepresentation$=new ae(null);this.isLive$=new ae(!1);this.isActiveLive$=new ae(!1);this.isLowLatency$=new ae(!1);this.liveDuration$=new ae(0);this.liveSeekableDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(0);this.liveStreamStatus$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLatency$=new ae(void 0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.currentStallDuration$=new ae(0);this.videoLastDataObtainedTimestamp$=new ae(0);this.fetcherRecoverableError$=new wo;this.fetcherError$=new wo;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new wo;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=ed(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=ed(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=lo(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=oo(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,f,p,h;return!!((f=(d=this.element)==null?void 0:d.canPlayType)!=null&&f.call(d,l)&&((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),d=new Set(c.map(({codecs:p})=>p)),f=Eo(d);if(f&&(r[u]=c.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);F.display.isHDR&&p&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",hs(s)),s}.bind(this));this.initRepresentations=ed(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",hs({initialVideo:e,initialAudio:t,sourceHls:i})),Lr(this.manifest),Lr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Bt(p,"error").pipe(xo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Vn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&cr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new os("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],fs(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new os("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ds.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ds(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Mi(...AB.map(p=>Bt(this.element,p))).pipe(Mr(p=>this.element?me(this.element.buffered,this.element.currentTime*1e3):0),ps(),EB(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Mi(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(ps()).subscribe(h=>this.liveStreamEndTimestamp=id())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=td(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Bt(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add($r({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Mr(({isActiveLive:h,isLowLatency:m})=>h&&m),ps()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Rr(this.element,1)})),this.representationSubscription.add($r({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(xo(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add($r({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(xo(({isLive:h})=>h),ps((h,m)=>m.bufferLength<h.bufferLength),Mr(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=zt(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add($r({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-S;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(I)>y&&(E=1+Math.sign(I)*v),Rr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let y=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var E,A;return(A=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?A:y}))-y}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add($r({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(xB(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=zt(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,A=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let P="none";if(M?P="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(k=>k.proceedLowLatencyLive()),P="active_low_latency"):S!==0&&A<v?P="live_forward_buffering":A<v+E&&(P="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let k=p-(v+I),V=this.normolizeLiveOffset(Math.trunc(S+k/b)),D=Math.abs(V-S),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=S:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=le(this.manifestUrlString,_,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Mi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Mr(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Mi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Mr(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=$r({allBuffersFull:l,someBufferEnded:c}).pipe(ps(),Mr(({allBuffersFull:p,someBufferEnded:h})=>p&&h),xo(p=>p));if(this.representationSubscription.add(Mi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Mi(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var b;if(((b=this.source)==null?void 0:b.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,rd.default)((0,rd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Qe(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&fs(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=td(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new go({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;Lr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?id()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Lr(this.element),this.state$.setState("running"),this.subscription.add(Mi(...wB.map(e=>Bt(this.element,e)),Bt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Bt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Bt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,h,m,b,S,y,v,I,E,A,M;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=id(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(S=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?S:0,l=(v=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?v:0,c=(E=(I=this.audioBufferManager)==null?void 0:I.getForwardBufferDuration())!=null?E:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,f=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||f)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let L=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(L).catch(P=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:P})}),r.liveLastOffset=L}else{let L=this.element.currentTime*1e3;(A=this.videoBufferManager)==null||A.maintain(L),(M=this.audioBufferManager)==null||M.maintain(L),r.position=L}this.tracer.log("stallIntervalCallback",hs(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=td(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;Lr(this.element),Lr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(nI(this.element)||nI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",hs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;fs(this.element)&&fs(this.source)&&fs(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=IB(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",hs(i)))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};var Po=class{constructor(e,t){this.fov=e,this.orientation=t}};var ko=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var lI=`attribute vec2 a_vertex;
125
125
  attribute vec2 a_texel;
126
126
 
127
127
  varying vec2 v_texel;
@@ -132,7 +132,7 @@ void main(void) {
132
132
  // save texel vector to pass to fragment shader
133
133
  v_texel = a_texel;
134
134
  }
135
- `;var oI=`#ifdef GL_ES
135
+ `;var cI=`#ifdef GL_ES
136
136
  precision highp float;
137
137
  precision highp int;
138
138
  #else
@@ -175,6 +175,6 @@ void main(void) {
175
175
  // sample using new coordinates
176
176
  gl_FragColor = texture2D(u_texture, tc);
177
177
  }
178
- `;var Dr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Po(this.params.fov,this.params.orientation),this.cameraRotationManager=new ko(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(nI,this.gl.VERTEX_SHADER),i=this.createShader(oI,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,d=t+r,c=e-i,f=t+r;return[s,n,o,u,l,d,c,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as wB,now as ms,once as AB,Subscription as PB,ValueSubject as td,isNonNullable as kB,safeStorage as id,filterChanged as RB}from"@vkontakte/videoplayer-shared/es2018";var Ro="stalls_manager_metrics",rd="stalls_manager_abr_params",uI="stalls_manager_default_tuning_abr_params",ad=class{constructor(){this.isSeeked$=new td(!1);this.isBuffering$=new td(!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 PB;this.severeStallOccurred$=new td(!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(rd):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=ms(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(ms()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(uI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(rd),this.setStoredData(uI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ro,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Ro,[]),this.setStoredData(rd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),d=this.abrTuningParams;return e<i-r?d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(d={bitrateFactorAtEmptyBuffer:Math.min(d.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(d.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(d.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(d={bitrateFactorAtEmptyBuffer:Math.max(d.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(d.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(d.containerSizeFactor,this.abrParams.containerSizeFactor)}),d}getStoredData(e,t="{}"){var i;return JSON.parse((i=id.get(e))!=null?i:t)}setStoredData(e,t){id.set(e,JSON.stringify(t))}removeStoredData(e){id.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ro,"[]"),r=t/e,s=i.length?Dt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ro,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(AB()).subscribe(t=>this.providerStartWatchingTimestamp=ms())),this.subscription.add(this.currentStallDuration$.pipe(RB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(wB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),d=ms(),c=r&&this.currentStallsCount>=r,f=i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&d-l>=i+o&&t>=i;(c||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,kB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&ms()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Lo=ad;import{combine as LB,map as $B,observeElementSize as MB,Subscription as DB,ValueSubject as sd,noop as CB}from"@vkontakte/videoplayer-shared/es2018";var $o=class{constructor(){this.subscription=new DB;this.pipSize$=new sd(void 0);this.videoSize$=new sd(void 0);this.elementSize$=new sd(void 0);this.pictureInPictureWindowRemoveEventListener=CB}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(MB(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(LB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe($B(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Di=class{constructor(e){this.subscription=new UB;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new vr;this.stallsManager=new Lo;this.elementSizeManager=new $o;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&L(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return VB(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Dr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ao({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;NB(this.observableVideo)&&(this.observableVideo=Be(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:lI.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(nd(l=>!!l.length),dI()).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(od(l=>l.to.state!=="none"),Mo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(nd(cI),dI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(od(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(mt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(_B(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let p of d.audio){f.push(qc(p));let h=[];for(let m of p.representations){let g=jT(m);h.push(g),this.audioTracksMap.set(g,{stream:p,representation:m})}this.audioStreamsMap.set(p,h)}this.params.output.availableAudioStreams$.next(f)}let c=[];for(let f of d.video){c.push(jc(f));let p=[];for(let h of f.representations){let m=qT({...h,streamId:f.id});m&&(p.push(m),this.videoTracksMap.set(m,{stream:f,representation:h}))}this.videoStreamsMap.set(f,p)}this.params.output.availableVideoStreams$.next(c);for(let f of d.text)for(let p of f.representations){let h=HT(f,p);this.textTracksMap.set(h,{stream:f,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(Do(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,FB(this.video,"progress")).pipe(nd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,pI.default)(["manifest_ready","running"],l)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoAudioRepresentations();if(!c)return;let[f,p]=c,h=[...this.videoTracksMap.keys()].find(g=>{var S;return((S=this.videoTracksMap.get(g))==null?void 0:S.representation.id)===f.id});cI(h)&&(this.stallsManager.lastVideoTrackSelected=h);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")await this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),p){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,g)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Mo()).subscribe(l=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[c,{stream:f}]=d,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(c),e.currentVideoStream$.next(jc(f));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Mo()).subscribe(l=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!d){e.currentAudioStream$.next(void 0);return}let[c,{stream:f}]=d,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(qc(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var d,c;if(l!=null&&l.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(od(({to:l})=>l==="ready"),Mo());this.subscription.add(Do(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ud(["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(Do(o,this.player.state$.stateChangeEnded$,ud(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Do(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ud(["init"])).pipe(OB(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var P,B,M,R,Q,O,A,_,k,E,C,ne,Fe;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?xa:Ea,t=this.params.tuning.useNewAutoSelectVideoTrack?eo:Zn,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:Jn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(P=r.videoTrack.getState())==null?void 0:P.id,l=[...this.videoTracksMap.keys()].find(({id:ie})=>ie===o),d=s.currentVideoTrack$.getValue(),c=((R=(M=r.videoStream.getState())!=null?M:l&&((B=this.videoTracksMap.get(l))==null?void 0:B.stream))!=null?R:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let f=[...this.videoStreamsMap.keys()].find(({id:ie})=>ie===c.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=me(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,g||1/0),1),v=(Q=r.audioStream.getState())!=null?Q:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(O=[...this.audioStreamsMap.keys()].find(({id:ie})=>ie===(v==null?void 0:v.id)))!=null?O:this.audioStreamsMap.keys().next().value,I=0;if(y){if(l&&!n){let ie=e(l,p,(A=this.audioStreamsMap.get(y))!=null?A:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(_=ie==null?void 0:ie.bitrate)!=null?_:-1/0)}if(d){let ie=e(d,p,(k=this.audioStreamsMap.get(y))!=null?k:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(E=ie==null?void 0:ie.bitrate)!=null?E:-1/0)}}let T=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:S,current:d,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),x=n?T!=null?T:l:l!=null?l:T,V=y&&t(x,p,(C=this.audioStreamsMap.get(y))!=null?C:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),$=(ne=this.videoTracksMap.get(x))==null?void 0:ne.representation,w=V&&((Fe=this.audioTracksMap.get(V))==null?void 0:Fe.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(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lI.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),De(this.video),this.tracer.end()}};var bs=class extends Di{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as ld,merge as hI,filter as fI,filterChanged as mI,isNullable as cd,map as bI,ValueSubject as dd,isNonNullable as qB}from"@vkontakte/videoplayer-shared/es2018";var gs=class extends Di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new dd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(mI()).subscribe(u=>{let l=i.position$.getValue(),d=i.volume$.getValue(),c=!d.volume||d.muted;!u&&!l&&c?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(bI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(ld({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(bI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(fI(u=>qB(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(ld({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:hI(r.playbackRateState$,new dd(1))}).pipe(fI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let d=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-f||this.video.paused||cd(d)||(t=u-d)})).add(ld({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:hI(r.playbackRateState$,new dd(1))}).pipe(mI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:d})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&d>=1-f||cd(u)||cd(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=QT(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as f0,assertNonNullable as m0,debounce as b0,ErrorCategory as CI,filter as Pd,filterChanged as Qo,fromEvent as g0,isNonNullable as BI,isNullable as S0,map as kd,merge as Go,observableFrom as Rd,once as VI,Subscription as v0}from"@vkontakte/videoplayer-shared/es2018";var wd=N(Ma(),1);import{abortable as Td,assertNonNullable as Vr,combine as _r,ErrorCategory as ct,filter as Uo,filterChanged as Es,flattenObject as xs,fromEvent as Et,getTraceSubscriptionMethod as a0,interval as Id,isNonNullable as ws,isNullable as MI,map as Or,merge as Oi,now as Ed,Subject as qo,Subscription as xd,tap as s0,throttle as DI,ValueSubject as se}from"@vkontakte/videoplayer-shared/es2018";var _o=N(Ye(),1),_i=N(St(),1),Oo=N(Ma(),1);var PI=N($n(),1);import{assertNever as jB,ErrorCategory as gI,Subject as SI}from"@vkontakte/videoplayer-shared/es2018";var HB=18,vI=!1;try{vI=U.browser.isSafari&&!!U.browser.safariVersion&&U.browser.safariVersion<=HB}catch(a){console.error(a)}var pd=class{constructor(e){this.bufferFull$=new SI;this.error$=new SI;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:gI.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};vI&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:gI.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:jB(t)}}},yI=pd;import{abortable as ii,assertNonNullable as Oe,ErrorCategory as Bi,fromEvent as gd,getExponentialDelay as Sd,isNonNullable as Cr,isNullable as xe,now as Vo,once as YB,Subject as KB,Subscription as XB,ValueSubject as Vi}from"@vkontakte/videoplayer-shared/es2018";var hd=N(St(),1);import{videoSizeToQuality as QB,throttleFn as GB}from"@vkontakte/videoplayer-shared/es2018";var TI=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:QB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},II=({id:a,bitrate:e})=>({id:a,bitrate:e}),EI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),xI=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),fd=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,hd.default)(i.split("."),0),isDefault:r}),md=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,hd.default)(r.split("."),0)}),bd=a=>"url"in a,Ge=a=>a.type==="template";var wI=a=>{a.sort((t,i)=>t.from-i.from);let e=[a[0]];for(let t=1;t<a.length;t++){let{from:i,to:r}=a[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(a[t])}return e},Ci=(a,e)=>{for(let t of a)if(e(t))return t;return null},AI=a=>{let e=!1,t=GB(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as WB,Subscription as zB}from"@vkontakte/videoplayer-shared/es2018";var Co=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var Bo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new zB;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(WB(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!F(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Co(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],n=t[i],o=t[i+1];if(n>r||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Ss=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Vi(0);this.currentLowLatencySegmentLength$=new Vi(0);this.currentSegmentLength$=new Vi(0);this.onLastSegment$=new Vi(!1);this.fullyBuffered$=new Vi(!1);this.playingRepresentation$=new Vi(void 0);this.playingRepresentationInit$=new Vi(void 0);this.error$=new KB;this.gaps=[];this.subscription=new XB;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=ii(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Oe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new yI(this.sourceBuffer),this.sourceBufferBufferedDiff=new Bo(this.mediaSource,this.sourceBuffer),this.subscription.add(gd(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(gd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Bi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!F(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ir(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=me(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Oe(i,"No init buffer for starting representation"),Oe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=ii(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Oe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Oe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Cr(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=ii(this.destroyAbortController.signal,async function*(e,t=!1){if(!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Oe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Oe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Cr(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=ii(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Oo.default)(e,d=>d.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let d of this.representations.keys()){let c=t.find(h=>h.id===d);c&&this.representations.set(d,c);let f=this.representations.get(d);if(!f||!Ge(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Oe(r);let s=this.segments.get(i);Oe(s,"No segments for starting representation");let n=this.initData.get(i);if(Oe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var d;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(d=l==null?void 0:l.baseUrls)!=null?d:[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!F(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,ii(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Oe(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(xe(o)||xe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Oe(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Cr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!xe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(xe(e)||xe(this.downloadingRepresentationId)||xe(this.playingRepresentationId)||xe(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||Cr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Oe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(d=>e>=d.time.from&&e<d.time.to);Cr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=me(this.sourceBuffer.buffered,e),c=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=r.time.to-e+n&&(s=c)}if(isFinite(this.bufferLimit)&&Ir(this.sourceBuffer.buffered)>=this.bufferLimit){let d=me(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<c).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u!=null&&u.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,_o.default)(u,r))d="high";else{let c=(0,_i.default)(u,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(u,t,d).catch(c=>{this.handleAsyncError(c,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&me(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,_i.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-me(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Cr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Oo.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,Oo.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ge(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,d=(r=this.segments.get(o.id))!=null?r:[],c=(n=(s=(0,_i.default)(d,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>c>=p.time.from+l&&c<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...d,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Oe(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ge(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=ut(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let g=p<=i&&h>=i,S=p>i||g||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+v||r<v&&h-p>=v||h<=i+v;return(f==="none"||f==="partially_ejected"&&S&&y&&this.sourceBuffer&&F(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&S&&y});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let f=s;f<n.length&&(o<=d||u<=c);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Ge(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ii(o,async function*(){let d=Sd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Vo(),!d)return;let c=new DataView(d),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(c);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),It(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())Ge(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ii(n,async function*(){let u=Sd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),gd(window,"online").pipe(YB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Vo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ge(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,_i.default)(e,0).byte.from,to:(0,_i.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Vo(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Bi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ge(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Vo();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Bi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,_o.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!F(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),d=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);d!=null&&d.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!F(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=u,d=l.byte.from-i,c=l.byte.to-i,f=c-d+1,p=d<r,h=c<=r;if(p){if(l.status==="downloading"&&h){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+d,f);await this.sourceBufferTaskQueue.append(m,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-d),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===f?m:Tt(o.mime).parseFeedableSegmentChunk(m);g!=null&&g.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(xe(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer))){!this.isLive&&U.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Bi.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",bd(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Tr(()=>(0,PI.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ii(this.destroyAbortController.signal,async function*(){let o=Sd(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let f=d;this.isLive&&Ge(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Bi.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||xe(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=o=>{var l;if(s>=t)return;r.push({...o.time});let u=bd(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||d)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let f of c)(0,_o.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(l)&&d++;if(d===this.segments.size){let c={time:{from:u,to:l},url:"",status:"none"};n(c)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=wI(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||xe(e)?0:me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,o=i.end(s)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!F(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Tr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Bi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(xe(this.sourceBuffer)||!F(this.mediaSource,this.sourceBuffer)||xe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Co(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let d=0;d<e.length;d+=2){let c=e[d],f=e[d+1];u||(u=c-t<=n&&f+t>=o),(n>=c&&n<f-t||o>c+t&&o<=f)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(d=>d.from===r.time.from||d.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Bi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,_i.default)(e,-1))==null?void 0:t.time.to:0)||0}};import{abortable as vs,assertNever as kI,fromEvent as RI,merge as JB,now as ys,Subject as LI,ValueSubject as vd,flattenObject as Br,ErrorCategory as Ts,SubscriptionRemovable as ZB}from"@vkontakte/videoplayer-shared/es2018";var No=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new vd(void 0);this.lastConnectionReused$=new vd(void 0);this.lastRequestFirstBytes$=new vd(void 0);this.recoverableError$=new LI;this.error$=new LI;this.abortAllController=new Z;this.subscription=new ZB;this.fetchManifest=vs(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=fo(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Fo);return r?(t.log("success",Br({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Br({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=vs(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var M,R,Q;let l=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let O=new URL(l,location.href);O.searchParams.append("bytes",`${i.from}-${i.to}`),l=O.toString();break}default:kI(t)}this.requestQuic&&(l=ei(l));let f=this.abortAllController.signal,p;if(n){let O=new Z;if(p=JB(RI(this.abortAllController.signal,"abort"),RI(n,"abort")).subscribe(()=>{try{O.abort()}catch(A){Fo(A)}}),this.subscription.add(p),this.abortAllController.signal.aborted||n.aborted)try{O.abort()}catch(A){Fo(A)}f=O.signal}let h=ys();c.log("startRequest",Br({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:h}));let m=yield this.doFetch(l,{priority:s,headers:d,signal:f}),g=ys();if(!m)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(p),null;if((M=this.throughputEstimator)==null||M.addRawRtt(g-h),!m.ok||!m.body){this.unsubscribeAbortSubscription(p);let O=`Fetch error ${m.status}: ${m.statusText}`;return c.error("error",{message:O}),c.end(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`))}if(this.onHeadersReceived(m.headers),!r&&!o){this.unsubscribeAbortSubscription(p);let O=ys(),A={requestStartedAt:h,requestEndedAt:O,duration:O-h};return c.log("endRequest",Br(A)),c.end(),m.arrayBuffer()}let S=m.body;if(o){let O;[S,O]=m.body.tee(),(R=this.throughputEstimator)==null||R.trackStream(O,u)}let v=S.getReader(),y,I=parseInt((Q=m.headers.get("content-length"))!=null?Q:"",10);Number.isFinite(I)&&(y=I),!y&&i&&(y=i.to-i.from+1);let T=0,x=y?new Uint8Array(y):new Uint8Array(0),V=!1,$=O=>{this.unsubscribeAbortSubscription(p),V=!0,Fo(O)},w=vs(f,async function*({done:O,value:A}){if(T===0&&this.lastRequestFirstBytes$.next(ys()-h),f.aborted){this.unsubscribeAbortSubscription(p);return}if(!O&&A){if(y)x.set(A,T),T+=A.byteLength;else{let _=new Uint8Array(x.length+A.length);_.set(x),_.set(A,x.length),x=_,T+=A.byteLength}r==null||r(new DataView(x.buffer),T),yield v==null?void 0:v.read().then(w,$)}}.bind(this));yield v==null?void 0:v.read().then(w,$),this.unsubscribeAbortSubscription(p);let P=ys(),B={failed:V,requestStartedAt:h,requestEndedAt:P,duration:P-h};return V?(c.error("endRequest",Br(B)),c.end(),null):(c.log("endRequest",Br(B)),c.end(),x.buffer)}.bind(this));this.fetchByteRangeRepresentation=vs(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let f=new DataView(c,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,h.from-n,h.to-h.from+1);else{let v=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!v)return null;m=new DataView(v)}let g=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=vs(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=ho(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:kI(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Ze(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ts.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ts.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ts.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ts.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ts.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Fo=a=>{if(!It(a))throw a};import{isNullable as e0,ValueSubject as t0}from"@vkontakte/videoplayer-shared/es2018";var Is=class a{constructor(e,t){this.currentRepresentation$=new t0(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(!e0(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(d=>d.time.from<=e&&d.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ge(t.segmentReference))}};var n0=["progress","play","seeked","stalled","waiting"],o0=["timeupdate","progress","loadeddata","playing","seeked"];var jo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new xd;this.representationSubscription=new xd;this.state$=new j("none");this.currentVideoRepresentation$=new se(void 0);this.currentVideoRepresentationInit$=new se(void 0);this.currentAudioRepresentation$=new se(void 0);this.currentVideoSegmentLength$=new se(0);this.currentAudioSegmentLength$=new se(0);this.error$=new qo;this.lastConnectionType$=new se(void 0);this.lastConnectionReused$=new se(void 0);this.lastRequestFirstBytes$=new se(void 0);this.currentLiveTextRepresentation$=new se(null);this.isLive$=new se(!1);this.isActiveLive$=new se(!1);this.isLowLatency$=new se(!1);this.liveDuration$=new se(0);this.liveSeekableDuration$=new se(0);this.liveAvailabilityStartTime$=new se(0);this.liveStreamStatus$=new se(void 0);this.bufferLength$=new se(0);this.liveLatency$=new se(void 0);this.liveLoadBufferLength$=new se(0);this.livePositionFromPlayer$=new se(0);this.currentStallDuration$=new se(0);this.videoLastDataObtainedTimestamp$=new se(0);this.fetcherRecoverableError$=new qo;this.fetcherError$=new qo;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new qo;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=Td(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Td(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=uo(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=oo(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,d)=>{var c,f,p,h;return!!((f=(c=this.element)==null?void 0:c.canPlayType)!=null&&f.call(c,l)&&((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${d}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:d,streamIsAlive:c}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";c||(p=d?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let d=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),c=new Set(d.map(({codecs:p})=>p)),f=Eo(c);if(f&&(r[u]=d.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);U.display.isHDR&&p&&h?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",xs(s)),s}.bind(this));this.initRepresentations=Td(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",xs({initialVideo:e,initialAudio:t,sourceHls:i})),Vr(this.manifest),Vr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new xd,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Et(p,"error").pipe(Uo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?_n():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&hr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ss("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],ws(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Ss("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Is.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Is(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Oi(...o0.map(p=>Et(this.element,p))).pipe(Or(p=>this.element?me(this.element.buffered,this.element.currentTime*1e3):0),Es(),s0(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Oi(Et(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Es()).subscribe(h=>this.liveStreamEndTimestamp=Ed())),this.subscription.add(Et(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Id(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Et(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(_r({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Or(({isActiveLive:h,isLowLatency:m})=>h&&m),Es()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Rr(this.element,1)})),this.representationSubscription.add(_r({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Uo(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(_r({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Uo(({isLive:h})=>h),Es((h,m)=>m.bufferLength<h.bufferLength),Or(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let S=zt(this.manifestUrlString,2);return(h/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(_r({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-S;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(I)>v&&(T=1+Math.sign(I)*y),Rr(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var g,S;let m=0;if(h){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var T,x;return(x=(T=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:T.to)!=null?x:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(_r({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(DI(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=zt(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,x=isFinite(h)?h:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),$=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next($);let w="none";if(V?w="active_low_latency":this.isLowLatency$.getValue()&&$?(this.bufferManagers.forEach(P=>P.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&x<y?w="live_forward_buffering":x<y+T&&(w="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let P=p-(y+I),B=this.normolizeLiveOffset(Math.trunc(S+P/g)),M=Math.abs(B-S),R=0;!h||M<=this.tuning.dashCmafLive.offsetCalculationError?R=S:B>0&&M>this.tuning.dashCmafLive.offsetCalculationError&&(R=B),this.manifestUrlString=le(this.manifestUrlString,R,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Oi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Or(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),d=Oi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Or(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),c=_r({allBuffersFull:l,someBufferEnded:d}).pipe(Es(),Or(({allBuffersFull:p,someBufferEnded:h})=>p&&h),Uo(p=>p));if(this.representationSubscription.add(Oi(this.forceEnded$,c).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Oi(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var g;if(((g=this.source)==null?void 0:g.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,wd.default)((0,wd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Ge(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&ws(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Id(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new No({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;Vr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Ed()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Vr(this.element),this.state$.setState("running");let e=Et(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(DI(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Oi(...n0.map(t=>Et(this.element,t)),Et(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Et(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Et(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,m,g,S,v,y,I,T,x,V,$;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let s={timeInWaiting:r},n=Ed(),o=100,u=(g=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?g:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(v=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?v:0,d=(I=(y=this.videoBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,c=(x=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?x:0,f=d<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let w=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(w).catch(P=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:P})}),s.liveLastOffset=w}else{let w=this.element.currentTime*1e3;(V=this.videoBufferManager)==null||V.maintain(w),($=this.audioBufferManager)==null||$.maintain(w),s.position=w}this.tracer.log("stallIntervalCallback",xs(s))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=Id(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;Vr(this.element),Vr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(MI(this.element)||MI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",xs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;ws(this.element)&&ws(this.source)&&ws(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=a0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=s&&l.to+o>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",xs({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};import{combine as u0,map as l0,observeElementSize as c0,Subscription as d0,ValueSubject as Ad,noop as p0}from"@vkontakte/videoplayer-shared/es2018";var Ho=class{constructor(){this.subscription=new d0;this.pipSize$=new Ad(void 0);this.videoSize$=new Ad(void 0);this.elementSize$=new Ad(void 0);this.pictureInPictureWindowRemoveEventListener=p0}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(c0(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(u0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(l0(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Fi=class{constructor(e){this.subscription=new v0;this.videoState=new j("stopped");this.observableVideo=null;this.droppedFramesManager=new vr;this.stallsManager=new Lo;this.elementSizeManager=new Ho;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&L(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return f0(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Dr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new jo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;S0(this.observableVideo)&&(this.observableVideo=Be(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:CI.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Pd(c=>!!c.length),VI()).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(kd(c=>c.to.state!=="none"),Qo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Pd(BI),VI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(kd(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(mt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams();if(m0(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of f.audio){h.push(fd(m));let g=[];for(let S of m.representations){let v=II(S);g.push(v),this.audioTracksMap.set(v,{stream:m,representation:S})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of f.video){p.push(md(h));let m=[];for(let g of h.representations){let S=TI({...g,streamId:h.id});S&&(m.push(S),this.videoTracksMap.set(S,{stream:h,representation:g}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of f.text)for(let m of h.representations){let g=EI(h,m);this.textTracksMap.set(g,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&AI(o)||null;this.subscription.add(Go(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,g0(this.video,"progress")).pipe(Pd(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),f=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||f||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let m=Ci(this.videoTracksMap.keys(),S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});BI(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Qo()).subscribe(c=>{let f=Ci(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(md(h));let g=this.player.calculateDurationFromSegments();g&&this.params.output.duration$.next(g/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Qo()).subscribe(c=>{let f=Ci(this.audioTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(fd(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var f,p;if(c!=null&&c.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe(kd(({to:c})=>c==="ready"),Qo());this.subscription.add(Go(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Rd(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Go(l,this.player.state$.stateChangeEnded$,Rd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let d=Go(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Rd(["init"])).pipe(b0(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var $,w,P,B,M,R,Q,O,A,_,k,E;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?xa:Ea,t=this.params.tuning.useNewAutoSelectVideoTrack?eo:Zn,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:Jn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=($=r.videoTrack.getState())==null?void 0:$.id,u=Ci(this.videoTracksMap.keys(),C=>C.id===o),l=s.currentVideoTrack$.getValue(),d=((B=(P=r.videoStream.getState())!=null?P:u&&((w=this.videoTracksMap.get(u))==null?void 0:w.stream))!=null?B:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let c=Ci(this.videoStreamsMap.keys(),C=>C.id===d.id),f=c&&this.videoStreamsMap.get(c);if(!f)return;let p=me(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,g=Math.min(p/Math.min(h,m||1/0),1),S=(M=r.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(S==null?void 0:S.id)&&Ci(this.audioStreamsMap.keys(),C=>C.id===S.id)||this.audioStreamsMap.keys().next().value,y=0;if(v){if(u&&!n){let C=e(u,f,(R=this.audioStreamsMap.get(v))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(Q=C==null?void 0:C.bitrate)!=null?Q:-1/0)}if(l){let C=e(l,f,(O=this.audioStreamsMap.get(v))!=null?O:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);y=Math.max(y,(A=C==null?void 0:C.bitrate)!=null?A:-1/0)}}let I=u;(n||!I)&&(I=i(f,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:y,forwardBufferHealth:g,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let T=v&&t(I,f,(_=this.audioStreamsMap.get(v))!=null?_:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:g,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),x=(k=this.videoTracksMap.get(I))==null?void 0:k.representation,V=T&&((E=this.audioTracksMap.get(T))==null?void 0:E.representation);x&&V?(this.selectedRepresentations.video=x,this.selectedRepresentations.audio=V):x&&!V&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=x,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:CI.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),De(this.video),this.tracer.end()}};var As=class extends Fi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Ld,merge as _I,filter as OI,filterChanged as FI,isNullable as $d,map as NI,ValueSubject as Md,isNonNullable as y0}from"@vkontakte/videoplayer-shared/es2018";var Ps=class extends Fi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Md(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(FI()).subscribe(u=>{let l=i.position$.getValue(),d=i.volume$.getValue(),c=!d.volume||d.muted;!u&&!l&&c?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(NI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Ld({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(NI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(OI(u=>y0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Ld({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:_I(r.playbackRateState$,new Md(1))}).pipe(OI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let d=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-f||this.video.paused||$d(d)||(t=u-d)})).add(Ld({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:_I(r.playbackRateState$,new Md(1))}).pipe(FI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:d})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&d>=1-f||$d(u)||$d(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=xI(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var UI="X-Playback-Duration",Dd=async a=>{var r;let e=await Ze(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(UI)?parseInt(e.headers.get(UI),10):void 0};import{assertNever as $0,combine as M0,debounce as D0,ErrorCategory as Yo,filter as C0,filterChanged as B0,isNonNullable as HI,isNullable as Ko,map as QI,merge as V0,observableFrom as _0,Subscription as O0,ValueSubject as Vd,VideoQuality as F0}from"@vkontakte/videoplayer-shared/es2018";var Bd=N(Sl(),1);import{videoSizeToQuality as T0,getExponentialDelay as I0}from"@vkontakte/videoplayer-shared/es2018";var E0=a=>{let e=null;if(a.QUALITY&&(e=Kt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=T0({width:t,height:i})}return e!=null?e:null},x0=(a,e)=>{var s,n;let t=a.split(`
179
- `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),d=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!d)){if(l){let c=(0,Bd.default)(l[1].split(",").map(v=>v.split("="))),f=(s=c.QUALITY)!=null?s:`stream-${c.BANDWIDTH}`,p=E0(c),h;c.BANDWIDTH&&(h=parseInt(c.BANDWIDTH,10)/1e3||void 0),!h&&c["AVERAGE-BANDWIDTH"]&&(h=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,g;if(c.RESOLUTION){let[v,y]=c.RESOLUTION.split("x").map(I=>parseInt(I,10));v&&y&&(g={width:v,height:y})}let S=new URL(t[++o],e).toString();p&&i.push({id:f,quality:p,url:S,bandwidth:h,size:g,fps:m})}if(d){let c=(0,Bd.default)(d[1].split(",").map(m=>{let g=m.indexOf("=");return[m.substring(0,g),m.substring(g+1)]}).map(([m,g])=>[m,g.replace(/^"|"$/g,"")])),f=(n=c.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=c.LANGUAGE,h=c.NAME;f&&p&&r.push({type:"internal",id:p,label:h,language:p,url:f,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},w0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Cd=0,qI=async(a,e=a,t,i)=>{let s=await(await Ze(a,i)).text();Cd+=1;try{let{qualityManifests:n,textTracks:o}=x0(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Cd<=t.manifestRetryMaxCount)return await w0(I0(Cd-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),qI(a,e,t)}return{qualityManifests:[],textTracks:[]}},Wo=qI;import{isNonNullable as A0,Subscription as P0,throttle as k0,ValueSubject as jI,Subject as R0,ErrorCategory as L0}from"@vkontakte/videoplayer-shared/es2018";var zo=class{constructor(e,t,i,r,s){this.subscription=new P0;this.abortControllers={destroy:new Z,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new jI(null);this.getCurrentTime$=new jI(null);this.error$=new R0;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(k0(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await Ze(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
180
- `),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(A0(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new Z;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:L0.WTF,thrown:t,message:e})}};var ks=class{constructor(e){this.subscription=new O0;this.videoState=new j("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Vd([]);this.liveOffset=new wi;this.manifestStartTime$=new Vd(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),L(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(L(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return $0(t)}};var i;this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:F0.INVARIANT,url:this.params.source.url};let t=(r,s)=>Wo(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new zo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Xe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Yo.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Yo.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Vd((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Yo.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(Je(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(B0(),QI(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&HI(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===c);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Te(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,d;let o=(d=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:d.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(M0({startTime:this.manifestStartTime$.pipe(C0(HI)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(QI(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:f})=>({id:u,quality:l,size:d,fps:f,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=V0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,_0(["init"])).pipe(D0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),De(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Ko(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[d,"mq"],[c,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=le(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Dd(n).then(d=>{var c;if(!Ko(d))this.maxSeekBackTime$.next(d);else{let f=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();(Ko(f)||!isFinite(f))&&Ze(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let g=new URL(h,n).toString();Dd(g).then(S=>{Ko(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Yo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=le(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as N0,debounce as U0,ErrorCategory as _d,fromEvent as Od,isNonNullable as q0,isNullable as j0,map as GI,merge as WI,observableFrom as zI,Subscription as H0,ValueSubject as Q0,VideoQuality as G0}from"@vkontakte/videoplayer-shared/es2018";var Rs=class{constructor(e){this.subscription=new H0;this.videoState=new j("stopped");this.manifests$=new Q0([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?L(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return N0(t)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:G0.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Wo(le(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:_d.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,d,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(c=(d=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?d:(l=t.getState())==null?void 0:l.id)!=null?c:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:_d.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(GI(o=>o.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&q0(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Te(m.url)))}let c=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(c!==f){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(GI(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:f})=>({id:u,quality:l,size:d,fps:f,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!U.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(WI(Od(o,"addtrack"),Od(o,"removetrack"),Od(o,"change"),zI(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=WI(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,zI(["init"])).pipe(U0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),De(this.video)}prepare(){var s,n;let e=this.selectManifest();if(j0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&r.searchParams.set(d,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_d.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var XI=N(er(),1),Fd=N(dr(),1),JI=N(St(),1);import{assertNever as W0,assertNonNullable as YI,debounce as z0,ErrorCategory as KI,isHigherOrEqual as Y0,isLowerOrEqual as K0,isNonNullable as X0,merge as J0,observableFrom as Z0,Subscription as eV,map as tV}from"@vkontakte/videoplayer-shared/es2018";var Ls=class{constructor(e){this.subscription=new eV;this.videoState=new j("stopped");this.trackUrls={};this.textTracksManager=new Xe;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?L(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return W0(e)}};this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),(0,XI.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Fd.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:KI.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(tV(o=>o.to)),this.params.output.playbackState$),this.subscription.add(mt(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(Je(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),L(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),L(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&X0(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let d=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(d!==c){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=J0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Z0(["init"])).pipe(z0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),De(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;YI(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];YI(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ei(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Te(t))}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:KI.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,d;this.params.output.autoVideoTrackLimits$.next(e);let t=c=>{this.params.output.currentVideoTrack$.next(c),this.params.desiredState.videoTrack.startTransitionTo(c)},i=c=>{let f=vt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:c,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,Fd.default)(this.trackUrls).map(c=>c.track);if(!r||!s||fr(e,n[0].quality,(d=(0,JI.default)(n,-1))==null?void 0:d.quality)){i();return}let o=e.max?K0(r,e.max):!0,u=e.min?Y0(r,e.min):!0;o&&u||i(e)}};import{assertNever as eE,debounce as sV,merge as tE,observableFrom as nV,Subscription as oV,map as iE,ValueSubject as uV,ErrorCategory as Ud,VideoQuality as lV}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as iV}from"@vkontakte/videoplayer-shared/es2018";var ZI=["stun:videostun.mycdn.me:80"],rV=1e3,aV=3,Nd=()=>null,Xo=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Nd;this.externalStopCallback=Nd;this.externalErrorCallback=Nd;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:ZI}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:iV.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),rV)}normalizeOptions(e={}){let t={stunServerList:ZI,maxRetryNumber:aV,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var $s=class{constructor(e){this.videoState=new j("stopped");this.maxSeekBackTime$=new uV(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),L(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&L(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&L(this.params.desiredState.playbackState,"paused");return;default:return eE(e)}};this.subscription=new oV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Me(e.container,e.tuning),this.liveStreamClient=new Xo(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),De(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ud.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(tE(this.videoState.stateChangeStarted$.pipe(iE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(iE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Je(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ce(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return eE(n.to)}},i)).add(tE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,nV(["init"])).pipe(sV(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:lV.INVARIANT}),this.video.srcObject=e,L(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ud.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),L(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ud.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ms=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Cs,assertNonNullable as ri,ErrorCategory as Jo,filter as uE,isNonNullable as lE,isNullable as bV,map as gV,merge as SV,once as vV,Subject as be,Subscription as cE,ValueSubject as H,flattenObject as qd}from"@vkontakte/videoplayer-shared/es2018";import{Observable as cV,map as rE,Subscription as dV,Subject as pV}from"@vkontakte/videoplayer-shared/es2018";var aE=a=>new cV(e=>{let t=new dV,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(rE(({from:l,to:d})=>`${l}-${d}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(rE(({type:l})=>l!==void 0)),n=new pV,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as hV,Subscription as fV,combine as mV,filter as nE,once as oE}from"@vkontakte/videoplayer-shared/es2018";function sE(){return new(window.AudioContext||window.webkitAudioContext)}var Ds=class Ds{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Z;this.subscriptions=new fV;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(nE(s=>!!s.type),oE()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){U.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(mV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(nE(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),oE()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=sE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Ds.errorId,category:hV.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ds.errorId} exception`,thrown:e})}};Ds.errorId="VolumeMultiplierManager";var Fr=Ds;var yV={chunkDuration:5e3,maxParallelRequests:5},Bs=class{constructor(e){this.current$=new H({type:void 0});this.providerError$=new be;this.noAvailableProvidersError$=new be;this.volumeMultiplierError$=new be;this.providerOutput={position$:new H(0),duration$:new H(1/0),volume$:new H({muted:!1,volume:1}),availableVideoStreams$:new H([]),currentVideoStream$:new H(void 0),availableVideoTracks$:new H([]),currentVideoTrack$:new H(void 0),availableAudioStreams$:new H([]),currentAudioStream$:new H(void 0),availableAudioTracks$:new H([]),currentVideoSegmentLength$:new H(0),currentAudioSegmentLength$:new H(0),isAudioAvailable$:new H(!0),autoVideoTrackLimitingAvailable$:new H(!1),autoVideoTrackLimits$:new H(void 0),currentBuffer$:new H(void 0),isBuffering$:new H(!0),error$:new be,fetcherError$:new be,fetcherRecoverableError$:new be,warning$:new be,willSeekEvent$:new be,soundProhibitedEvent$:new be,seekedEvent$:new be,loopedEvent$:new be,endedEvent$:new be,firstBytesEvent$:new be,loadedMetadataEvent$:new be,firstFrameEvent$:new be,canplay$:new be,isLive$:new H(void 0),isLiveEnded$:new H(null),isLowLatency$:new H(!1),canChangePlaybackSpeed$:new H(!0),liveTime$:new H(void 0),liveBufferTime$:new H(void 0),liveLatency$:new H(void 0),severeStallOccurred$:new be,availableTextTracks$:new H([]),currentTextTrack$:new H(void 0),hostname$:new H(void 0),httpConnectionType$:new H(void 0),httpConnectionReused$:new H(void 0),inPiP$:new H(!1),inFullscreen$:new H(!1),element$:new H(void 0),elementVisible$:new H(!0),availableSources$:new H(void 0),is3DVideo$:new H(!1),playbackState$:new H(""),getCurrentTime$:new H(null)};this.subscription=new cE;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=ZT([...tI(this.params.tuning),...eI(this.params.tuning)],this.params.tuning).filter(l=>lE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,jd.default)(r,l)),...t.filter(l=>(0,jd.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",qd(s)),this.screenFormatsIterator=new Ms(s);let n=[...Yc(!0),...Yc(!1)];this.chromecastFormatsIterator=new Ms(n.filter(l=>lE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Fr.isSupported()&&(this.volumeMultiplierManager=new Fr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(bV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Jo.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Cs(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ri(u),this.params.tuning.useNewDashProvider?new As({...o,source:u,sourceHls:l}):new bs({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ri(u),this.params.tuning.useNewDashProvider?new Ps({...o,source:u}):new gs({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return ri(u),new Rs({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ri(u),new ks({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return ri(u),new Ls({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return ri(u),new Gv({...o,source:u,config:{...yV,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return ri(u),new $s({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Cs(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ri(o),new ga({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Cs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Cs(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Cs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,pE.default)((0,dE.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new cE,t=!1,i=0;return e.add(SV(this.providerOutput.error$.pipe(uE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),aE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(gV(r=>({id:`ProviderHangup:${r}`,category:Jo.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(uE(({to:s})=>s==="playing"),vV()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Jo.NETWORK,u=r.category===Jo.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",qd(n)):this.tracer.error("providerError",qd(n))})),e}};import{fromEvent as Zo,once as TV,combine as IV,Subscription as hE,ValueSubject as Hd,map as EV,filter as xV,isNonNullable as eu,now as We,safeStorage as Qd}from"@vkontakte/videoplayer-shared/es2018";var wV=5e3,fE="one_video_throughput",mE="one_video_rtt",Vt=window.navigator.connection,bE=()=>{let a=Vt==null?void 0:Vt.downlink;if(eu(a)&&a!==10)return a*1e3},gE=()=>{let a=Vt==null?void 0:Vt.rtt;if(eu(a)&&a!==3e3)return a},SE=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Gd=class a{constructor(e){this.subscription=new hE;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(fE)||(e.useBrowserEstimation?bE():void 0)||wV,i=(s=(r=a.load(mE))!=null?r:e.useBrowserEstimation?gE():void 0)!=null?s:0;if(this.throughput$=new Hd(t),this.rtt$=new Hd(i),this.rttAdjustedThroughput$=new Hd(SE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ct.getSmoothedValue(t,-1,e),this.rtt=Ct.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=bE();u&&this.throughput.next(u);let l=gE();eu(l)&&this.rtt.next(l)};Vt&&"onchange"in Vt&&this.subscription.add(Zo(Vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Qd.set(fE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Qd.set(mE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(IV({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(EV(({throughput:n,rtt:o})=>SE(n,o,e.rttPenaltyRequestSize)),xV(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=We(),r=new hE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Zo(e,"progress").pipe(TV()).subscribe(s=>{t=s.loaded,i=We()}));break;case 1:case 0:r.add(Zo(e,"loadstart").subscribe(()=>{t=0,i=We()}));break}r.add(Zo(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=We(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=We(),n=0,o=We(),u=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,We()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let f=We();if(f-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||f-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let h=o-s;h&&this.addRawSpeed(n,h,1,t),n=c.byteLength,s=We()}else n+=c.byteLength;o=We()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&We()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,We()-o,this.concurrentDownloads.size),n=0,o=We());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=Qd.get(e);if(eu(t))return(i=parseInt(t,10))!=null?i:void 0}},vE=Gd;import{fillWithDefault as AV,VideoQuality as tu}from"@vkontakte/videoplayer-shared/es2018";var yE={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:tu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:tu.Q_720P,trafficSavingLimit:tu.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:tu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},TE=a=>{var e;return{...AV(a,yE),configName:[...(e=a.configName)!=null?e:[],...yE.configName]}};import{assertNonNullable as iu,combine as _t,ErrorCategory as ru,filter as q,filterChanged as K,fromEvent as zd,isNonNullable as wE,isNullable as DV,Logger as CV,map as z,mapTo as AE,merge as ai,now as au,once as G,Subject as X,Subscription as PE,tap as Yd,ValueSubject as D,isHigher as BV,isInvariantQuality as kE,flattenObject as si,throttle as Kd,getTraceSubscriptionMethod as RE,TracerFactory as VV,InternalsExposure as _V}from"@vkontakte/videoplayer-shared/es2018";import{merge as PV,map as kV,filter as IE,isNonNullable as RV}from"@vkontakte/videoplayer-shared/es2018";var Wd=({seekState:a,position$:e})=>PV(a.stateChangeEnded$.pipe(kV(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),IE(RV)),e.pipe(IE(()=>a.getState().state==="none")));import{assertNonNullable as LV}from"@vkontakte/videoplayer-shared/es2018";var EE=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return LV(e,`Wrong container or containerId {${a.container}}`),e};import{filter as $V,once as MV}from"@vkontakte/videoplayer-shared/es2018";var xE=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe($V(r=>r.length>0),MV()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var su=class{constructor(e={configName:[]},t=VV.createRootTracer(!1)){this.subscription=new PE;this.logger=new CV;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 j("stopped"),seekState:new j({state:"none"}),volume:new j({volume:1,muted:!1}),videoTrack:new j(void 0),videoStream:new j(void 0),audioStream:new j(void 0),autoVideoTrackSwitching:new j(!0),autoVideoTrackLimits:new j({}),isLooped:new j(!1),isLowLatency:new j(!1),playbackRate:new j(1),externalTextTracks:new j([]),internalTextTracks:new j([]),currentTextTrack:new j(void 0),textTrackCuesSettings:new j({}),cameraOrientation:new j({x:0,y:0})};this.info={playbackState$:new D(void 0),position$:new D(0),duration$:new D(1/0),muted$:new D(!1),volume$:new D(1),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableQualities$:new D([]),availableQualitiesFps$:new D({}),currentQuality$:new D(void 0),isAutoQualityEnabled$:new D(!0),autoQualityLimitingAvailable$:new D(!1),autoQualityLimits$:new D({}),predefinedQualityLimitType$:new D("unknown"),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),isAudioAvailable$:new D(!0),currentPlaybackRate$:new D(1),currentBuffer$:new D({start:0,end:0}),isBuffering$:new D(!0),isStalled$:new D(!1),isEnded$:new D(!1),isLooped$:new D(!1),isLive$:new D(void 0),isLiveEnded$:new D(null),canChangePlaybackSpeed$:new D(void 0),atLiveEdge$:new D(void 0),atLiveDurationEdge$:new D(void 0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),currentFormat$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),throughputEstimation$:new D(void 0),rttEstimation$:new D(void 0),videoBitrate$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),surface$:new D("none"),chromecastState$:new D("NOT_AVAILABLE"),chromecastDeviceName$:new D(void 0),intrinsicVideoSize$:new D(void 0),availableSources$:new D(void 0),is3DVideo$:new D(!1),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0)};this.events={inited$:new X,ready$:new X,started$:new X,playing$:new X,paused$:new X,stopped$:new X,willReady$:new X,willStart$:new X,willResume$:new X,willPause$:new X,willStop$:new X,willDestruct$:new X,watchCoverageRecord$:new X,watchCoverageLive$:new X,managedError$:new X,fatalError$:new X,fetcherRecoverableError$:new X,ended$:new X,looped$:new X,seeked$:new X,willSeek$:new X,autoplaySoundProhibited$:new X,firstBytes$:new X,loadedMetadata$:new X,firstFrame$:new X,canplay$:new X,log$:new X,fetcherError$:new X,severeStallOccured$:new X};this.experimental={element$:new D(void 0),tuningConfigName$:new D([]),enableDebugTelemetry$:new D(!1),dumpTelemetry:Sv,getCurrentTime$:new D(null)};if(this.initLogs(),this.tuning=TE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new rn({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new vE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new _V("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(f=>JSON.stringify(f,(p,h)=>{let m=typeof h;return(0,LE.default)(["number","string","boolean"],m)?h:h===null?null:`<${m}>`})),d=`Player.${String(r)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:ru.WTF,message:c,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,d;let{container:n,...o}=e;this.tracer.log("initVideo",si(o)),this.domContainer=EE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Bs({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?U.isInited$.pipe(q(n=>!!n),G()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),zd(document,"visibilitychange").pipe(G()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(q(e=>!!e),G()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(q(e=>!!e),G()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(q(e=>!!e),G()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(q(e=>!!e),G()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(q(i=>!!i),G()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(q(i=>!!i),G()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(q(i=>!!i),G()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{iu(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(q(i=>i.length>0),G()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",si(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{var i;iu(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",si(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{var t;xE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(q(i=>!!i),G()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(q(t=>!!t),G()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(q(i=>!!i),G()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(q(e=>e),G()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(q(e=>!!e),G()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(DV(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return wE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ai(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(bc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(q(({from:e})=>e==="stopped"),G()).subscribe(()=>{this.initedAt=au(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",si(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:ru.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(G()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",si(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(z(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(z(n=>n.destination),K()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(_t({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(z(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>kE(u)?1:kE(l)?-1:BV(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(K()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(q(n=>wE(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(K((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(K()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(K()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(K()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(z(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Yd(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(_t({hasLiveOffsetByPaused:ai(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(z(n=>n.to),K(),z(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(_t({atLiveEdge:_t({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Wd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(z(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),K(),Yd(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(z(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(_t({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(z(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),K(),Yd(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(z(n=>n.muted),K()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(z(n=>n.volume),K()).subscribe(this.info.volume$)).add(Wd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ai(e.providerOutput.endedEvent$.pipe(AE(!0)),e.providerOutput.seekedEvent$.pipe(AE(!1))).pipe(K()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(z(n=>({id:n?`No${n}`:"NoProviders",category:ru.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(G(),z(n=>n!=null?n:au()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(G(),z(()=>au()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(G(),z(()=>au()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new D(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new D(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(q(({to:n})=>n==="playing"),G()).subscribe(()=>i.next(!1)));let r=0,s=ai(e.providerOutput.isBuffering$,t,i).pipe(z(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),K());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ai(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ai(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(z(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new PE;this.subscription.add(t),this.subscription.add(e.current$.pipe(K((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(q(i=>i.length>0),G()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=vt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(ai(this.desiredState.videoTrack.stateChangeStarted$.pipe(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;iu(this.providerContainer),iu(e),gv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>bv(i)),this.providerContainer.current$.subscribe(({type:i})=>Ia("provider",i)),e.duration$.subscribe(i=>Ia("duration",i)),e.availableVideoTracks$.pipe(q(i=>!!i.length),G()).subscribe(i=>Ia("tracks",i)),this.events.fatalError$.subscribe(new ke("fatalError")),this.events.managedError$.subscribe(new ke("managedError")),e.position$.subscribe(new ke("position")),e.currentVideoTrack$.pipe(z(i=>i==null?void 0:i.quality)).subscribe(new ke("quality")),this.info.currentBuffer$.subscribe(new ke("buffer")),e.isBuffering$.subscribe(new ke("isBuffering"))].forEach(i=>this.subscription.add(i)),Ia("codecs",U.video.supportedCodecs)}initTracerSubscription(){let e=RE(this.tracer.log.bind(this.tracer)),t=RE(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(K()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(_t({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(q(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),K((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(q(i=>i>0),K()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(q(i=>i>0),K()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(_t({currentBuffer:this.info.currentBuffer$.pipe(q(i=>i.end>0),K((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(K())}).pipe(Kd(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(K()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(K()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(K()).subscribe(e("canChangePlaybackSpeed"))).add(_t({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(q(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Kd(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(K(),q(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(K(),q(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(K()).subscribe(e("muted"))).add(this.info.volume$.pipe(K()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(K(),q(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(_t({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(q(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Kd(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(K(),q(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:ru.DOM,message:String(r)})})};this.subscription.add(ai(zd(document,"visibilitychange"),zd(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",si({quality:t,availableTracks:si(e),track:si(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ra()}};import{Subscription as q9,Observable as j9,Subject as H9,ValueSubject as Q9,VideoQuality as G9}from"@vkontakte/videoplayer-shared/es2018";var W9=`@vkontakte/videoplayer-core@${Vp}`;export{Ys as ChromecastState,du as HttpConnectionType,j9 as Observable,Le as PlaybackState,su as Player,Ks as PredefinedQualityLimits,W9 as SDK_VERSION,H9 as Subject,q9 as Subscription,pu as Surface,Vp as VERSION,Q9 as ValueSubject,At as VideoFormat,G9 as VideoQuality,U as clientChecker,Ta as isMobile};
178
+ `;var Dr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Po(this.params.fov,this.params.orientation),this.cameraRotationManager=new ko(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(lI,this.gl.VERTEX_SHADER),i=this.createShader(cI,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,f=t+r;return[s,n,o,u,l,c,d,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as RB,now as ms,once as LB,Subscription as $B,ValueSubject as ad,isNonNullable as MB,safeStorage as sd,filterChanged as DB}from"@vkontakte/videoplayer-shared/es2018";var Ro="stalls_manager_metrics",nd="stalls_manager_abr_params",dI="stalls_manager_default_tuning_abr_params",od=class{constructor(){this.isSeeked$=new ad(!1);this.isBuffering$=new ad(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new $B;this.severeStallOccurred$=new ad(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(nd):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=ms(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(ms()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(dI)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(nd),this.setStoredData(dI,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ro,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Ro,[]),this.setStoredData(nd,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){var i;return JSON.parse((i=sd.get(e))!=null?i:t)}setStoredData(e,t){sd.set(e,JSON.stringify(t))}removeStoredData(e){sd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ro,"[]"),r=t/e,s=i.length?Dt(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ro,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(LB()).subscribe(t=>this.providerStartWatchingTimestamp=ms())),this.subscription.add(this.currentStallDuration$.pipe(DB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if(RB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=ms(),d=r&&this.currentStallsCount>=r,f=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||f)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,MB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&ms()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Lo=od;import{combine as CB,map as BB,observeElementSize as VB,Subscription as _B,ValueSubject as ud,noop as OB}from"@vkontakte/videoplayer-shared/es2018";var $o=class{constructor(){this.subscription=new _B;this.pipSize$=new ud(void 0);this.videoSize$=new ud(void 0);this.elementSize$=new ud(void 0);this.pictureInPictureWindowRemoveEventListener=OB}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(VB(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(CB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(BB(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Di=class{constructor(e){this.subscription=new QB;this.videoState=new q("stopped");this.observableVideo=null;this.droppedFramesManager=new vr;this.stallsManager=new Lo;this.elementSizeManager=new $o;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&$(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return NB(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Dr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Ao({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;HB(this.observableVideo)&&(this.observableVideo=Be(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:pI.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ld(l=>!!l.length),fI()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(cd(l=>l.to.state!=="none"),Mo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(ld(hI),fI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(cd(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(UB(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let f=[];for(let p of c.audio){f.push(Hc(p));let h=[];for(let m of p.representations){let b=WT(m);h.push(b),this.audioTracksMap.set(b,{stream:p,representation:m})}this.audioStreamsMap.set(p,h)}this.params.output.availableAudioStreams$.next(f)}let d=[];for(let f of c.video){d.push(Qc(f));let p=[];for(let h of f.representations){let m=GT({...h,streamId:f.id});m&&(p.push(m),this.videoTracksMap.set(m,{stream:f,representation:h}))}this.videoStreamsMap.set(f,p)}this.params.output.availableVideoStreams$.next(d);for(let f of c.text)for(let p of f.representations){let h=zT(f,p);this.textTracksMap.set(h,{stream:f,representation:p})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(Do(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,jB(this.video,"progress")).pipe(ld(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,mI.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[f,p]=d,h=[...this.videoTracksMap.keys()].find(b=>{var S;return((S=this.videoTracksMap.get(b))==null?void 0:S.representation.id)===f.id});hI(h)&&(this.stallsManager.lastVideoTrackSelected=h);let m=this.params.desiredState.autoVideoTrackLimits.getTransition();if(m&&this.params.output.autoVideoTrackLimits$.next(m.to),l==="manifest_ready")await this.player.initRepresentations(f.id,p==null?void 0:p.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),p){let b=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",p.id,b)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Mo()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Qc(f));let h=this.player.calculateDurationFromSegments();h&&this.params.output.duration$.next(h/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Mo()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:h}])=>h.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:f}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===f.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Hc(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(cd(({to:l})=>l==="ready"),Mo());this.subscription.add(Do(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,dd(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Do(o,this.player.state$.stateChangeEnded$,dd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=Do(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dd(["init"])).pipe(qB(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var k,V,D,_,Y,J,T,R,x,w,B,ne,Fe;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?xa:Ea,t=this.params.tuning.useNewAutoSelectVideoTrack?eo:Zn,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:Jn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(k=r.videoTrack.getState())==null?void 0:k.id,l=[...this.videoTracksMap.keys()].find(({id:ie})=>ie===o),c=s.currentVideoTrack$.getValue(),d=((_=(D=r.videoStream.getState())!=null?D:l&&((V=this.videoTracksMap.get(l))==null?void 0:V.stream))!=null?_:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let f=[...this.videoStreamsMap.keys()].find(({id:ie})=>ie===d.id),p=f&&this.videoStreamsMap.get(f);if(!p)return;let h=me(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),y=(Y=r.audioStream.getState())!=null?Y:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,v=(J=[...this.audioStreamsMap.keys()].find(({id:ie})=>ie===(y==null?void 0:y.id)))!=null?J:this.audioStreamsMap.keys().next().value,I=0;if(v){if(l&&!n){let ie=e(l,p,(T=this.audioStreamsMap.get(v))!=null?T:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(R=ie==null?void 0:ie.bitrate)!=null?R:-1/0)}if(c){let ie=e(c,p,(x=this.audioStreamsMap.get(v))!=null?x:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,(w=ie==null?void 0:ie.bitrate)!=null?w:-1/0)}}let E=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:S,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),A=n?E!=null?E:l:l!=null?l:E,M=v&&t(A,p,(B=this.audioStreamsMap.get(v))!=null?B:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:S,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),L=(ne=this.videoTracksMap.get(A))==null?void 0:ne.representation,P=M&&((Fe=this.audioTracksMap.get(M))==null?void 0:Fe.representation);if(L&&P)return[L,P];if(L&&!P&&this.audioTracksMap.size===0)return[L,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pI.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),De(this.video),this.tracer.end()}};var bs=class extends Di{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as pd,merge as bI,filter as gI,filterChanged as SI,isNullable as hd,map as vI,ValueSubject as fd,isNonNullable as GB}from"@vkontakte/videoplayer-shared/es2018";var gs=class extends Di{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new fd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(SI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(vI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(pd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(vI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(gI(u=>GB(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(pd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:bI(r.playbackRateState$,new fd(1))}).pipe(gI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||hd(c)||(t=u-c)})).add(pd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:bI(r.playbackRateState$,new fd(1))}).pipe(SI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||hd(u)||hd(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=YT(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as S0,assertNonNullable as v0,debounce as y0,ErrorCategory as _I,filter as Ld,filterChanged as Qo,fromEvent as T0,isNonNullable as OI,isNullable as I0,map as $d,merge as Go,observableFrom as Md,once as FI,Subscription as E0}from"@vkontakte/videoplayer-shared/es2018";var kd=O(Ma(),1);import{abortable as xd,assertNonNullable as Vr,combine as _r,ErrorCategory as dt,filter as Uo,filterChanged as Es,flattenObject as xs,fromEvent as Et,getTraceSubscriptionMethod as u0,interval as wd,isNonNullable as ws,isNullable as BI,map as Or,merge as Oi,now as Ad,Subject as qo,Subscription as Pd,tap as l0,throttle as VI,ValueSubject as se}from"@vkontakte/videoplayer-shared/es2018";var _o=O(Ye(),1),_i=O(ot(),1),Oo=O(Ma(),1);var LI=O($n(),1);import{assertNever as WB,ErrorCategory as yI,Subject as TI}from"@vkontakte/videoplayer-shared/es2018";var zB=18,II=!1;try{II=F.browser.isSafari&&!!F.browser.safariVersion&&F.browser.safariVersion<=zB}catch(a){console.error(a)}var md=class{constructor(e){this.bufferFull$=new TI;this.error$=new TI;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:yI.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};II&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:yI.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:WB(t)}}},EI=md;import{abortable as ii,assertNonNullable as Oe,ErrorCategory as Bi,fromEvent as yd,getExponentialDelay as Td,isNonNullable as Cr,isNullable as xe,now as Vo,once as ZB,Subject as e0,Subscription as t0,ValueSubject as Vi}from"@vkontakte/videoplayer-shared/es2018";var bd=O(ot(),1);import{videoSizeToQuality as YB,throttleFn as KB}from"@vkontakte/videoplayer-shared/es2018";var xI=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?Kt(s):void 0)!=null?u:YB({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},wI=({id:a,bitrate:e})=>({id:a,bitrate:e}),AI=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),PI=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),gd=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,bd.default)(i.split("."),0),isDefault:r}),Sd=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,bd.default)(r.split("."),0)}),vd=a=>"url"in a,Ge=a=>a.type==="template";var kI=a=>{a.sort((t,i)=>t.from-i.from);let e=[a[0]];for(let t=1;t<a.length;t++){let{from:i,to:r}=a[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(a[t])}return e},Ci=(a,e)=>{for(let t of a)if(e(t))return t;return null},RI=a=>{let e=!1,t=KB(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as XB,Subscription as JB}from"@vkontakte/videoplayer-shared/es2018";var Co=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var Bo=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new JB;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(XB(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!N(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Co(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],n=t[i],o=t[i+1];if(n>r||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Ss=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Vi(0);this.currentLowLatencySegmentLength$=new Vi(0);this.currentSegmentLength$=new Vi(0);this.onLastSegment$=new Vi(!1);this.fullyBuffered$=new Vi(!1);this.playingRepresentation$=new Vi(void 0);this.playingRepresentationInit$=new Vi(void 0);this.error$=new e0;this.gaps=[];this.subscription=new t0;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Z;this.switchAbortController=new Z;this.destroyAbortController=new Z;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=ii(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Oe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new EI(this.sourceBuffer),this.sourceBufferBufferedDiff=new Bo(this.mediaSource,this.sourceBuffer),this.subscription.add(yd(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(yd(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Bi.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!N(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ir(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=me(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);Oe(i,"No init buffer for starting representation"),Oe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=ii(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Oe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Oe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Cr(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=ii(this.destroyAbortController.signal,async function*(e,t=!1){if(!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);Oe(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),Oe(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Cr(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=ii(this.destroyAbortController.signal,async function*(e){var u,l;let t=(u=(0,Oo.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(h=>h.id===c);d&&this.representations.set(c,d);let f=this.representations.get(c);if(!f||!Ge(f.segmentReference))return;let p=this.getActualLiveStartingSegments(f.segmentReference);this.segments.set(f.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);Oe(r);let s=this.segments.get(i);Oe(s,"No segments for starting representation");let n=this.initData.get(i);if(Oe(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!N(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Z,ii(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);Oe(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(xe(o)||xe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),Oe(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Cr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!xe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Z,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(xe(e)||xe(this.downloadingRepresentationId)||xe(this.playingRepresentationId)||xe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||Cr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(Oe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);Cr(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=me(this.sourceBuffer.buffered,e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Ir(this.sourceBuffer.buffered)>=this.bufferLimit){let c=me(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u!=null&&u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,_o.default)(u,r))c="high";else{let d=(0,_i.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!(u!=null&&u.length)&&me(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,_i.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-me(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;Cr(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,Oo.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,Oo.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Ge(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,_i.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,f=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(f===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(f+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Oe(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!Ge(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=lt(r.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e,t;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),(t=this.sourceBufferBufferedDiff)==null||t.destroy(),this.gapDetectionIdleCallback&&yt&&yt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&yt&&yt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(i){if(!(i instanceof DOMException&&i.name==="NotFoundError"))throw i}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),s=e.findIndex(({status:f,time:{from:p,to:h}},m)=>{let b=p<=i&&h>=i,S=p>i||b||m===0&&i===0,y=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=i+y||r<y&&h-p>=y||h<=i+y;return(f==="none"||f==="partially_ejected"&&S&&v&&this.sourceBuffer&&N(this.mediaSource,this.sourceBuffer)&&!(Ie(this.sourceBuffer.buffered,p)&&Ie(this.sourceBuffer.buffered,h)))&&S&&v});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let f=s;f<n.length&&(o<=c||u<=d);f++){let p=n[f];if(o+=p.byte.to+1-p.byte.from,u+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")l.push(p);else break}return l}async loadSegments(e,t,i="auto"){Ge(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ii(o,async function*(){let c=Td(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=Vo(),!c)return;let d=new DataView(c),f=Tt(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=f.getChunkEndTime(d,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:h}=f.getServerLatencyTimestamps(d);p&&h&&this.currentLiveSegmentServerLatency$.next(h-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),It(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ge(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ii(n,async function*(){let u=Td(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),yd(window,"online").pipe(ZB()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=Vo(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),It(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ge(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,_i.default)(e,0).byte.from,to:(0,_i.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Vo(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Bi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ge(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Vo();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Bi.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,_o.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Tt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c!=null&&c.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!N(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=u,c=l.byte.from-i,d=l.byte.to-i,f=d-c+1,p=c<r,h=d<=r;if(p){if(l.status==="downloading"&&h){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+c,f);await this.sourceBufferTaskQueue.append(m,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(f,r-c),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),b=u.loadedBytes===f?m:Tt(o.mime).parseFeedableSegmentChunk(m);b!=null&&b.byteLength&&(l.status="partially_fed",u.feedingBytes+=b.byteLength,await this.sourceBufferTaskQueue.append(b,s)&&!s.aborted?(u.fedBytes+=b.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(xe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer))){!this.isLive&&F.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ie(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ie(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Bi.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",vd(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Tr(()=>(0,LI.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ii(this.destroyAbortController.signal,async function*(){let o=Td(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Tt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let f=c;this.isLive&&Ge(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Bi.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||xe(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=o=>{var l;if(s>=t)return;r.push({...o.time});let u=vd(o)?(l=o.size)!=null?l:0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let d of this.segments.values())for(let f of d)(0,_o.default)(["none","partially_ejected"],f.status)&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let d={time:{from:u,to:l},url:"",status:"none"};n(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=kI(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||xe(e)?0:me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,o=i.end(s)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!N(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Tr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Bi.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(xe(this.sourceBuffer)||!N(this.mediaSource,this.sourceBuffer)||xe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Co(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let c=0;c<e.length;c+=2){let d=e[c],f=e[c+1];u||(u=d-t<=n&&f+t>=o),(n>=d&&n<f-t||o>d+t&&o<=f)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Bi.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){var t;if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(t=(0,_i.default)(e,-1))==null?void 0:t.time.to:0)||0}};import{abortable as vs,assertNever as $I,fromEvent as MI,merge as i0,now as ys,Subject as DI,ValueSubject as Id,flattenObject as Br,ErrorCategory as Ts,SubscriptionRemovable as r0}from"@vkontakte/videoplayer-shared/es2018";var No=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Id(void 0);this.lastConnectionReused$=new Id(void 0);this.lastRequestFirstBytes$=new Id(void 0);this.recoverableError$=new DI;this.error$=new DI;this.abortAllController=new Z;this.subscription=new r0;this.fetchManifest=vs(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ei(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=mo(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Fo);return r?(t.log("success",Br({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Br({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=vs(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){var _,Y,J;let c=e,d=new Headers,f=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(c,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),c=T.toString();break}default:$I(t)}this.requestQuic&&(c=ei(c));let p=this.abortAllController.signal,h;if(n){let T=new Z;if(h=i0(MI(this.abortAllController.signal,"abort"),MI(n,"abort")).subscribe(()=>{try{T.abort()}catch(R){Fo(R)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(R){Fo(R)}p=T.signal}let m=ys();f.log("startRequest",Br({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let b=yield this.doFetch(c,{priority:s,headers:d,signal:p}),S=ys();if(!b)return f.error("error",{message:"No response in request"}),f.end(),this.unsubscribeAbortSubscription(h),null;if((_=this.throughputEstimator)==null||_.addRawRtt(S-m),!b.ok||!b.body){this.unsubscribeAbortSubscription(h);let T=`Fetch error ${b.status}: ${b.statusText}`;return f.error("error",{message:T}),f.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let T=ys(),R={requestStartedAt:m,requestEndedAt:T,duration:T-m};return f.log("endRequest",Br(R)),f.end(),b.arrayBuffer()}let y=b.body;if(o){let T;[y,T]=b.body.tee(),(Y=this.throughputEstimator)==null||Y.trackStream(T,u)}let v=y.getReader(),I,E=parseInt((J=b.headers.get("content-length"))!=null?J:"",10);Number.isFinite(E)&&(I=E),!I&&i&&(I=i.to-i.from+1);let A=0,M=I?new Uint8Array(I):new Uint8Array(0),L=!1,P=T=>{this.unsubscribeAbortSubscription(h),L=!0,Fo(T)},k=vs(p,async function*({done:T,value:R}){if(A===0&&this.lastRequestFirstBytes$.next(ys()-m),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!T&&R){if(l&&I)M.set(R,A),A+=R.byteLength;else{let x=new Uint8Array(M.length+R.length);x.set(M),x.set(R,M.length),M=x,A+=R.byteLength}r==null||r(new DataView(M.buffer),A),yield v==null?void 0:v.read().then(k,P)}}.bind(this));yield v==null?void 0:v.read().then(k,P),this.unsubscribeAbortSubscription(h);let V=ys(),D={failed:L,requestStartedAt:m,requestEndedAt:V,duration:V-m};return L?(f.error("endRequest",Br(D)),f.end(),null):(f.log("endRequest",Br(D)),f.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=vs(this.abortAllController.signal,async function*(e,t,i){var S;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let f=new DataView(d,r-n,s-n+1);if(!t.validateData(f))throw new Error("Invalid media file");let p=t.parseInit(f),h=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!h)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(d,h.from-n,h.to-h.from+1);else{let y=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!y)return null;m=new DataView(y)}let b=t.parseSegments(m,p,h);return{init:p,dataView:new DataView(d),segments:b}}.bind(this));this.fetchTemplateRepresentation=vs(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=fo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,i))!=null?n:null;default:$I(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Ze(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Ts.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Ts.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Ts.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Ts.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Ts.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Fo=a=>{if(!It(a))throw a};import{isNullable as a0,ValueSubject as s0}from"@vkontakte/videoplayer-shared/es2018";var Is=class a{constructor(e,t){this.currentRepresentation$=new s0(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!a0(e))for(let i of this.representations)for(let r of i){let s=r.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ge(t.segmentReference))}};var c0=["progress","play","seeked","stalled","waiting"],d0=["timeupdate","progress","loadeddata","playing","seeked"];var jo=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Pd;this.representationSubscription=new Pd;this.state$=new q("none");this.currentVideoRepresentation$=new se(void 0);this.currentVideoRepresentationInit$=new se(void 0);this.currentAudioRepresentation$=new se(void 0);this.currentVideoSegmentLength$=new se(0);this.currentAudioSegmentLength$=new se(0);this.error$=new qo;this.lastConnectionType$=new se(void 0);this.lastConnectionReused$=new se(void 0);this.lastRequestFirstBytes$=new se(void 0);this.currentLiveTextRepresentation$=new se(null);this.isLive$=new se(!1);this.isActiveLive$=new se(!1);this.isLowLatency$=new se(!1);this.liveDuration$=new se(0);this.liveSeekableDuration$=new se(0);this.liveAvailabilityStartTime$=new se(0);this.liveStreamStatus$=new se(void 0);this.bufferLength$=new se(0);this.liveLatency$=new se(void 0);this.liveLoadBufferLength$=new se(0);this.livePositionFromPlayer$=new se(0);this.currentStallDuration$=new se(0);this.videoLastDataObtainedTimestamp$=new se(0);this.fetcherRecoverableError$=new qo;this.fetcherError$=new qo;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new qo;this.gapWatchdogActive=!1;this.destroyController=new Z;this.initManifest=xd(this.destroyController.signal,async function*(e,t,i){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=le(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:dt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=xd(this.destroyController.signal,async function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:dt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=lo(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=oo(e))!=null?n:{id:"ManifestParsing",category:dt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,f,p,h;return!!((f=(d=this.element)==null?void 0:d.canPlayType)!=null&&f.call(d,l)&&((h=(p=He())==null?void 0:p.isTypeSupported)!=null&&h.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,f=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*f),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:h})=>i(u,p,h)),d=new Set(c.map(({codecs:p})=>p)),f=Eo(d);if(f&&(r[u]=c.filter(({codecs:p})=>p.startsWith(f))),u==="video"){let p=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);F.display.isHDR&&p&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",xs(s)),s}.bind(this));this.initRepresentations=xd(this.destroyController.signal,async function*(e,t,i){var f;this.tracer.log("initRepresentationsStart",xs({initialVideo:e,initialAudio:t,sourceHls:i})),Vr(this.manifest),Vr(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Pd,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(Et(p,"error").pipe(Uo(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Vn():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&cr())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ss("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],ws(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Ss("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Is.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Is(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Oi(...d0.map(p=>Et(this.element,p))).pipe(Or(p=>this.element?me(this.element.buffered,this.element.currentTime*1e3):0),Es(),l0(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Oi(Et(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(Es()).subscribe(h=>this.liveStreamEndTimestamp=Ad())),this.subscription.add(Et(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=wd(1e3).subscribe(h=>{let m=zt(this.manifestUrlString,2);this.manifestUrlString=le(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Et(this.element,"play").subscribe(h=>{var m;return(m=this.livePauseWatchdogSubscription)==null?void 0:m.unsubscribe()})),this.representationSubscription.add(_r({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Or(({isActiveLive:h,isLowLatency:m})=>h&&m),Es()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Rr(this.element,1)})),this.representationSubscription.add(_r({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Uo(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(_r({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Uo(({isLive:h})=>h),Es((h,m)=>m.bufferLength<h.bufferLength),Or(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=zt(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(_r({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-S;if(this.isManualDecreasePlaybackInLive())return;let E=1;Math.abs(I)>y&&(E=1+Math.sign(I)*v),Rr(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let y=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(I=>{var E,A;return(A=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?A:y}))-y}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(_r({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(VI(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=zt(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,A=isFinite(h)?h:m,M=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),L=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(L);let P="none";if(M?P="active_low_latency":this.isLowLatency$.getValue()&&L?(this.bufferManagers.forEach(k=>k.proceedLowLatencyLive()),P="active_low_latency"):S!==0&&A<v?P="live_forward_buffering":A<v+E&&(P="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),P==="live_forward_buffering"||P==="live_with_target_offset"){let k=p-(v+I),V=this.normolizeLiveOffset(Math.trunc(S+k/b)),D=Math.abs(V-S),_=0;!h||D<=this.tuning.dashCmafLive.offsetCalculationError?_=S:V>0&&D>this.tuning.dashCmafLive.offsetCalculationError&&(_=V),this.manifestUrlString=le(this.manifestUrlString,_,2)}(P==="live_with_target_offset"||P==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:dt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=Oi(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Or(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Oi(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Or(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=_r({allBuffersFull:l,someBufferEnded:c}).pipe(Es(),Or(({allBuffersFull:p,someBufferEnded:h})=>p&&h),Uo(p=>p));if(this.representationSubscription.add(Oi(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Oi(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{var m;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var b;if(((b=this.source)==null?void 0:b.readyState)==="open"){h();return}this.error$.next({id:"OpenOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),(m=this.source)==null||m.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(f=this.manifest.duration)!=null?f:0,...(0,kd.default)((0,kd.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Ge(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&ws(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{var t,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=wd(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:dt.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new No({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=Ct.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){var r,s,n;Vr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Ad()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=le(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio)),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))}initBuffer(){Vr(this.element),this.state$.setState("running");let e=Et(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(VI(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(Oi(...c0.map(t=>Et(this.element,t)),Et(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:dt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Et(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Et(this.element,"waiting").subscribe(()=>{var i;this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Ie(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{var h,m,b,S,y,v,I,E,A,M,L;if(!this.element||((h=this.source)==null?void 0:h.readyState)!=="open")return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let s={timeInWaiting:r},n=Ad(),o=100,u=(b=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(u);let l=(y=(S=this.audioBufferManager)==null?void 0:S.lastDataObtainedTimestamp)!=null?y:0,c=(I=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?I:0,d=(A=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?A:0,f=c<o&&n-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&d<o&&n-l>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((f||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%2e3===0){let P=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(P).catch(k=>{this.error$.next({id:"stallIntervalCallback",category:dt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:k})}),s.liveLastOffset=P}else{let P=this.element.currentTime*1e3;(M=this.videoBufferManager)==null||M.maintain(P),(L=this.audioBufferManager)==null||L.maintain(P),s.position=P}this.tracer.log("stallIntervalCallback",xs(s))};(i=this.stallWatchdogSubscription)==null||i.unsubscribe(),this.stallWatchdogSubscription=wd(50).subscribe(t,r=>{this.error$.next({id:"StallWatchdogCallback",category:dt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)}async seek(e,t){var r,s,n,o,u;Vr(this.element),Vr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ie(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()]),!(BI(this.element)||BI(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",xs({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;ws(this.element)&&ws(this.source)&&ws(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=u0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e,t;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=s&&l.to+o>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",xs({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){var e,t;return Math.max(((e=this.videoBufferManager)==null?void 0:e.calculateDurationFromSegments())||0,((t=this.audioBufferManager)==null?void 0:t.calculateDurationFromSegments())||0)}};import{combine as p0,map as h0,observeElementSize as f0,Subscription as m0,ValueSubject as Rd,noop as b0}from"@vkontakte/videoplayer-shared/es2018";var Ho=class{constructor(){this.subscription=new m0;this.pipSize$=new Rd(void 0);this.videoSize$=new Rd(void 0);this.elementSize$=new Rd(void 0);this.pictureInPictureWindowRemoveEventListener=b0}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(f0(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(p0({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(h0(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Fi=class{constructor(e){this.subscription=new E0;this.videoState=new q("stopped");this.observableVideo=null;this.droppedFramesManager=new vr;this.stallsManager=new Lo;this.elementSizeManager=new Ho;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Xt;this.audioTrackSwitchHistory=new Xt;this.selectedRepresentations={audio:null,video:null};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&$(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return S0(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Dr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new jo({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;I0(this.observableVideo)&&(this.observableVideo=Be(this.video),this.subscription.add(()=>{var n;return(n=this.observableVideo)==null?void 0:n.destroy()}));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:_I.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Ld(d=>!!d.length),FI()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe($d(d=>d.to.state!=="none"),Qo());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Ld(OI),FI()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe($d(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(this.video,t.isLooped,r)),this.subscription.add(Ce(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ke(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(Je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let f=this.player.getStreams();if(v0(f,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of f.audio){h.push(gd(m));let b=[];for(let S of m.representations){let y=wI(S);b.push(y),this.audioTracksMap.set(y,{stream:m,representation:S})}this.audioStreamsMap.set(m,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of f.video){p.push(Sd(h));let m=[];for(let b of h.representations){let S=xI({...b,streamId:h.id});S&&(m.push(S),this.videoTracksMap.set(S,{stream:h,representation:b}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of f.text)for(let m of h.representations){let b=AI(h,m);this.textTracksMap.set(b,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&RI(o)||null;this.subscription.add(Go(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,T0(this.video,"progress")).pipe(Ld(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),f=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||f||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:p,audio:h}=this.selectedRepresentations;if(!p)return;let m=Ci(this.videoTracksMap.keys(),S=>{var y;return((y=this.videoTracksMap.get(S))==null?void 0:y.representation.id)===p.id});OI(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),d==="manifest_ready")await this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Qo()).subscribe(d=>{let f=Ci(this.videoTracksMap.entries(),([,{representation:S}])=>S.id===d);if(!f){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Sd(h));let b=this.player.calculateDurationFromSegments();b&&this.params.output.duration$.next(b/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Qo()).subscribe(d=>{let f=Ci(this.audioTracksMap.entries(),([,{representation:b}])=>b.id===d);if(!f){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=f,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(gd(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var f,p;if(d!=null&&d.is3dVideo&&((f=this.params.tuning.spherical)!=null&&f.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let l=t.playbackState.stateChangeStarted$.pipe($d(({to:d})=>d==="ready"),Qo());this.subscription.add(Go(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Md(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Go(l,this.player.state$.stateChangeEnded$,Md(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=Go(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Md(["init"])).pipe(y0(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var L,P,k,V,D,_,Y,J,T,R,x,w;if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?xa:Ea,t=this.params.tuning.useNewAutoSelectVideoTrack?eo:Zn,i=this.params.tuning.useNewAutoSelectVideoTrack?vt:Jn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=(L=r.videoTrack.getState())==null?void 0:L.id,u=Ci(this.videoTracksMap.keys(),B=>B.id===o),l=s.currentVideoTrack$.getValue(),c=((V=(k=r.videoStream.getState())!=null?k:u&&((P=this.videoTracksMap.get(u))==null?void 0:P.stream))!=null?V:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=Ci(this.videoStreamsMap.keys(),B=>B.id===c.id),f=d&&this.videoStreamsMap.get(d);if(!f)return;let p=me(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,b=Math.min(p/Math.min(h,m||1/0),1),S=(D=r.audioStream.getState())!=null?D:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,y=(S==null?void 0:S.id)&&Ci(this.audioStreamsMap.keys(),B=>B.id===S.id)||this.audioStreamsMap.keys().next().value,v=0;if(y){if(u&&!n){let B=e(u,f,(_=this.audioStreamsMap.get(y))!=null?_:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(Y=B==null?void 0:B.bitrate)!=null?Y:-1/0)}if(l){let B=e(l,f,(J=this.audioStreamsMap.get(y))!=null?J:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(T=B==null?void 0:B.bitrate)!=null?T:-1/0)}}let I=u;(n||!I)&&(I=i(f,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:b,current:l,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}));let E=y&&t(I,f,(R=this.audioStreamsMap.get(y))!=null?R:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:b,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=(x=this.videoTracksMap.get(I))==null?void 0:x.representation,M=E&&((w=this.audioTracksMap.get(E))==null?void 0:w.representation);A&&M?(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=M):A&&!M&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_I.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),De(this.video),this.tracer.end()}};var As=class extends Fi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Dd,merge as NI,filter as UI,filterChanged as qI,isNullable as Cd,map as jI,ValueSubject as Bd,isNonNullable as x0}from"@vkontakte/videoplayer-shared/es2018";var Ps=class extends Fi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Bd(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(qI()).subscribe(u=>{let l=i.position$.getValue(),c=i.volume$.getValue(),d=!c.volume||c.muted;!u&&!l&&d?e=!0:u&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe(jI(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Dd({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(jI(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(UI(u=>x0(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Dd({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:NI(r.playbackRateState$,new Bd(1))}).pipe(UI(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-f||this.video.paused||Cd(c)||(t=u-c)})).add(Dd({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:NI(r.playbackRateState$,new Bd(1))}).pipe(qI((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:c})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:f}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&c>=1-f||Cd(u)||Cd(l))return;let p=-1*(l-u-t);i.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=PI(u);this.params.output.availableTextTracks$.next([l])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var HI="X-Playback-Duration",Vd=async a=>{var r;let e=await Ze(a),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(HI)?parseInt(e.headers.get(HI),10):void 0};import{assertNever as B0,combine as V0,debounce as _0,ErrorCategory as Yo,filter as O0,filterChanged as F0,isNonNullable as WI,isNullable as Ko,map as zI,merge as N0,observableFrom as U0,Subscription as q0,ValueSubject as Fd,VideoQuality as j0}from"@vkontakte/videoplayer-shared/es2018";var Od=O(Sl(),1);import{videoSizeToQuality as w0,getExponentialDelay as A0}from"@vkontakte/videoplayer-shared/es2018";var P0=a=>{let e=null;if(a.QUALITY&&(e=Kt(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=w0({width:t,height:i})}return e!=null?e:null},k0=(a,e)=>{var s,n;let t=a.split(`
179
+ `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Od.default)(l[1].split(",").map(y=>y.split("="))),f=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=P0(d),h;d.BANDWIDTH&&(h=parseInt(d.BANDWIDTH,10)/1e3||void 0),!h&&d["AVERAGE-BANDWIDTH"]&&(h=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let m=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,b;if(d.RESOLUTION){let[y,v]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));y&&v&&(b={width:y,height:v})}let S=new URL(t[++o],e).toString();p&&i.push({id:f,quality:p,url:S,bandwidth:h,size:b,fps:m})}if(c){let d=(0,Od.default)(c[1].split(",").map(m=>{let b=m.indexOf("=");return[m.substring(0,b),m.substring(b+1)]}).map(([m,b])=>[m,b.replace(/^"|"$/g,"")])),f=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,h=d.NAME;f&&p&&r.push({type:"internal",id:p,label:h,language:p,url:f,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},R0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),_d=0,QI=async(a,e=a,t,i)=>{let s=await(await Ze(a,i)).text();_d+=1;try{let{qualityManifests:n,textTracks:o}=k0(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(_d<=t.manifestRetryMaxCount)return await R0(A0(_d-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),QI(a,e,t)}return{qualityManifests:[],textTracks:[]}},Wo=QI;import{isNonNullable as L0,Subscription as $0,throttle as M0,ValueSubject as GI,Subject as D0,ErrorCategory as C0}from"@vkontakte/videoplayer-shared/es2018";var zo=class{constructor(e,t,i,r,s){this.subscription=new $0;this.abortControllers={destroy:new Z,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new GI(null);this.getCurrentTime$=new GI(null);this.error$=new D0;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(M0(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=await this.fetchManifestData();await this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let i=await this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}}async parseTextTracks(e,t){for(let i of e){let r=new URL(i.url,t).toString(),n=await(await Ze(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
180
+ `),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),f=new Date(i.programDateTime).valueOf();i.segmentStartTime=f-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(L0(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new Z;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return await this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:C0.WTF,thrown:t,message:e})}};var ks=class{constructor(e){this.subscription=new q0;this.videoState=new q("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Fd([]);this.liveOffset=new wi;this.manifestStartTime$=new Fd(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?$(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),$(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&($(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return B0(t)}};var i;this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:j0.INVARIANT,url:this.params.source.url};let t=(r,s)=>Wo(r,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new zo(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Xe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Yo.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Yo.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Fd((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Yo.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(Je(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(F0(),zI(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&WI(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(p=>p.id===d);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Te(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(V0({startTime:this.manifestStartTime$.pipe(O0(WI)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(zI(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=N0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,U0(["init"])).pipe(_0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),De(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Ko(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[f,p]of[[c,"mq"],[d,"lq"]]){let h=String(parseFloat(f||""));p&&f&&r.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=le(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),Vd(n).then(c=>{var d;if(!Ko(c))this.maxSeekBackTime$.next(c);else{let f=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Ko(f)||!isFinite(f))&&Ze(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let b=new URL(h,n).toString();Vd(b).then(S=>{Ko(S)||this.maxSeekBackTime$.next(S)})}}).catch(()=>{})}})}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Yo.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=le(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as H0,debounce as Q0,ErrorCategory as Nd,fromEvent as Ud,isNonNullable as G0,isNullable as W0,map as YI,merge as KI,observableFrom as XI,Subscription as z0,ValueSubject as Y0,VideoQuality as K0}from"@vkontakte/videoplayer-shared/es2018";var Rs=class{constructor(e){this.subscription=new z0;this.videoState=new q("stopped");this.manifests$=new Y0([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?$(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return H0(t)}};this.textTracksManager=new Xe(e.source.url),this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:K0.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Wo(le(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Nd.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(f=>f.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Nd.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(YI(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&G0(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(b=>b.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Te(m.url)))}let d=this.params.desiredState.playbackRate.getState(),f=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==f){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(YI(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:f})=>({id:u,quality:l,size:c,fps:f,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!F.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(KI(Ud(o,"addtrack"),Ud(o,"removetrack"),Ud(o,"change"),XI(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=KI(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,XI(["init"])).pipe(Q0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),De(this.video)}prepare(){var s,n;let e=this.selectManifest();if(W0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nd.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var eE=O(er(),1),qd=O(pr(),1),tE=O(ot(),1);import{assertNever as X0,assertNonNullable as JI,debounce as J0,ErrorCategory as ZI,isHigherOrEqual as Z0,isLowerOrEqual as eV,isNonNullable as tV,merge as iV,observableFrom as rV,Subscription as aV,map as sV}from"@vkontakte/videoplayer-shared/es2018";var Ls=class{constructor(e){this.subscription=new aV;this.videoState=new q("stopped");this.trackUrls={};this.textTracksManager=new Xe;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?$(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return X0(e)}};this.params=e,this.video=Me(e.container,e.tuning),this.params.output.element$.next(this.video),(0,eE.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,qd.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:ZI.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(sV(o=>o.to)),this.params.output.playbackState$),this.subscription.add(bt(this.video,t.isLooped,i)),this.subscription.add(Ce(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ke(this.video,t.playbackRate,r.playbackRateState$,i)),s(Je(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),$(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),$(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&tV(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(c),f.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=iV(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,rV(["init"])).pipe(J0(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),De(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;JI(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];JI(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ei(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Te(t))}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ZI.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let f=vt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(f)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,qd.default)(this.trackUrls).map(d=>d.track);if(!r||!s||fr(e,n[0].quality,(c=(0,tE.default)(n,-1))==null?void 0:c.quality)){i();return}let o=e.max?eV(r,e.max):!0,u=e.min?Z0(r,e.min):!0;o&&u||i(e)}};import{assertNever as rE,debounce as lV,merge as aE,observableFrom as cV,Subscription as dV,map as sE,ValueSubject as pV,ErrorCategory as Hd,VideoQuality as hV}from"@vkontakte/videoplayer-shared/es2018";import{ErrorCategory as nV}from"@vkontakte/videoplayer-shared/es2018";var iE=["stun:videostun.mycdn.me:80"],oV=1e3,uV=3,jd=()=>null,Xo=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=jd;this.externalStopCallback=jd;this.externalErrorCallback=jd;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:iE}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:nV.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),oV)}normalizeOptions(e={}){let t={stunServerList:iE,maxRetryNumber:uV,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var $s=class{constructor(e){this.videoState=new q("stopped");this.maxSeekBackTime$=new pV(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),$(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&$(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&$(this.params.desiredState.playbackState,"paused");return;default:return rE(e)}};this.subscription=new dV,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Me(e.container,e.tuning),this.liveStreamClient=new Xo(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),De(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Hd.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(aE(this.videoState.stateChangeStarted$.pipe(sE(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(sE(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Be(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(Je(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ce(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return rE(n.to)}},i)).add(aE(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,cV(["init"])).pipe(lV(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Te(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:hV.INVARIANT}),this.video.srcObject=e,$(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Hd.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),$(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Hd.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ms=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Cs,assertNonNullable as ri,ErrorCategory as Jo,filter as dE,isNonNullable as pE,isNullable as yV,map as TV,merge as IV,once as EV,Subject as be,Subscription as hE,ValueSubject as j,flattenObject as Qd}from"@vkontakte/videoplayer-shared/es2018";import{Observable as fV,map as nE,Subscription as mV,Subject as bV}from"@vkontakte/videoplayer-shared/es2018";var oE=a=>new fV(e=>{let t=new mV,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(nE(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(nE(({type:l})=>l!==void 0)),n=new bV,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as gV,Subscription as SV,combine as vV,filter as lE,once as cE}from"@vkontakte/videoplayer-shared/es2018";function uE(){return new(window.AudioContext||window.webkitAudioContext)}var Ds=class Ds{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new Z;this.subscriptions=new SV;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(lE(s=>!!s.type),cE()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){F.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(vV({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(lE(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),cE()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,i=uE();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Ds.errorId,category:gV.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ds.errorId} exception`,thrown:e})}};Ds.errorId="VolumeMultiplierManager";var Fr=Ds;var xV={chunkDuration:5e3,maxParallelRequests:5},Bs=class{constructor(e){this.current$=new j({type:void 0});this.providerError$=new be;this.noAvailableProvidersError$=new be;this.volumeMultiplierError$=new be;this.providerOutput={position$:new j(0),duration$:new j(1/0),volume$:new j({muted:!1,volume:1}),availableVideoStreams$:new j([]),currentVideoStream$:new j(void 0),availableVideoTracks$:new j([]),currentVideoTrack$:new j(void 0),availableAudioStreams$:new j([]),currentAudioStream$:new j(void 0),availableAudioTracks$:new j([]),currentVideoSegmentLength$:new j(0),currentAudioSegmentLength$:new j(0),isAudioAvailable$:new j(!0),autoVideoTrackLimitingAvailable$:new j(!1),autoVideoTrackLimits$:new j(void 0),currentBuffer$:new j(void 0),isBuffering$:new j(!0),error$:new be,fetcherError$:new be,fetcherRecoverableError$:new be,warning$:new be,willSeekEvent$:new be,soundProhibitedEvent$:new be,seekedEvent$:new be,loopedEvent$:new be,endedEvent$:new be,firstBytesEvent$:new be,loadedMetadataEvent$:new be,firstFrameEvent$:new be,canplay$:new be,isLive$:new j(void 0),isLiveEnded$:new j(null),canPlayLiveTailBuffer$:new j(!1),isLowLatency$:new j(!1),canChangePlaybackSpeed$:new j(!0),liveTime$:new j(void 0),liveBufferTime$:new j(void 0),liveLatency$:new j(void 0),severeStallOccurred$:new be,availableTextTracks$:new j([]),currentTextTrack$:new j(void 0),hostname$:new j(void 0),httpConnectionType$:new j(void 0),httpConnectionReused$:new j(void 0),inPiP$:new j(!1),inFullscreen$:new j(!1),element$:new j(void 0),elementVisible$:new j(!0),availableSources$:new j(void 0),is3DVideo$:new j(!1),playbackState$:new j(""),getCurrentTime$:new j(null)};this.subscription=new hE;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=sc([...aI(this.params.tuning),...rI(this.params.tuning)],this.params.tuning).filter(l=>pE(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Gd.default)(r,l)),...t.filter(l=>(0,Gd.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Qd(s)),this.screenFormatsIterator=new Ms(s);let n=[...Jc(!0),...Jc(!1)];this.chromecastFormatsIterator=new Ms(n.filter(l=>pE(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Fr.isSupported()&&(this.volumeMultiplierManager=new Fr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(yV(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Jo.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Cs(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return ri(u),this.params.tuning.useNewDashProvider?new As({...o,source:u,sourceHls:l}):new bs({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ri(u),this.params.tuning.useNewDashProvider?new Ps({...o,source:u}):new gs({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return ri(u),new Rs({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return ri(u),new ks({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return ri(u),new Ls({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return ri(u),new Yv({...o,source:u,config:{...xV,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return ri(u),new $s({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Cs(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return ri(o),new Sa({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Cs(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Cs(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Cs(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,mE.default)((0,fE.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new hE,t=!1,i=0;return e.add(IV(this.providerOutput.error$.pipe(dE(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),oE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(TV(r=>({id:`ProviderHangup:${r}`,category:Jo.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(dE(({to:s})=>s==="playing"),EV()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===Jo.NETWORK,u=r.category===Jo.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",Qd(n)):this.tracer.error("providerError",Qd(n))})),e}};import{fromEvent as Zo,once as wV,combine as AV,Subscription as bE,ValueSubject as Wd,map as PV,filter as kV,isNonNullable as eu,now as We,safeStorage as zd}from"@vkontakte/videoplayer-shared/es2018";var RV=5e3,gE="one_video_throughput",SE="one_video_rtt",Vt=window.navigator.connection,vE=()=>{let a=Vt==null?void 0:Vt.downlink;if(eu(a)&&a!==10)return a*1e3},yE=()=>{let a=Vt==null?void 0:Vt.rtt;if(eu(a)&&a!==3e3)return a},TE=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Yd=class a{constructor(e){this.subscription=new bE;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(gE)||(e.useBrowserEstimation?vE():void 0)||RV,i=(s=(r=a.load(SE))!=null?r:e.useBrowserEstimation?yE():void 0)!=null?s:0;if(this.throughput$=new Wd(t),this.rtt$=new Wd(i),this.rttAdjustedThroughput$=new Wd(TE(t,i,e.rttPenaltyRequestSize)),this.throughput=Ct.getSmoothedValue(t,-1,e),this.rtt=Ct.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=vE();u&&this.throughput.next(u);let l=yE();eu(l)&&this.rtt.next(l)};Vt&&"onchange"in Vt&&this.subscription.add(Zo(Vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{zd.set(gE,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{zd.set(SE,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(AV({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(PV(({throughput:n,rtt:o})=>TE(n,o,e.rttPenaltyRequestSize)),kV(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=We(),r=new bE;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Zo(e,"progress").pipe(wV()).subscribe(s=>{t=s.loaded,i=We()}));break;case 1:case 0:r.add(Zo(e,"loadstart").subscribe(()=>{t=0,i=We()}));break}r.add(Zo(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=We(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=We(),n=0,o=We(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,We()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let f=We();if(f-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||f-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let h=o-s;h&&this.addRawSpeed(n,h,1,t),n=d.byteLength,s=We()}else n+=d.byteLength;o=We()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&We()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,We()-o,this.concurrentDownloads.size),n=0,o=We());await(i==null?void 0:i.read().then(l,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=zd.get(e);if(eu(t))return(i=parseInt(t,10))!=null?i:void 0}},IE=Yd;import{fillWithDefault as LV,VideoQuality as tu}from"@vkontakte/videoplayer-shared/es2018";var EE={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:tu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:tu.Q_720P,trafficSavingLimit:tu.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:tu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},xE=a=>{var e;return{...LV(a,EE),configName:[...(e=a.configName)!=null?e:[],...EE.configName]}};import{assertNonNullable as iu,combine as _t,ErrorCategory as ru,filter as U,filterChanged as z,fromEvent as Xd,isNonNullable as kE,isNullable as _V,Logger as OV,map as G,mapTo as RE,merge as ai,now as au,once as H,Subject as K,Subscription as LE,tap as Jd,ValueSubject as C,isHigher as FV,isInvariantQuality as $E,flattenObject as si,throttle as Zd,getTraceSubscriptionMethod as ME,TracerFactory as NV,InternalsExposure as UV}from"@vkontakte/videoplayer-shared/es2018";import{merge as $V,map as MV,filter as wE,isNonNullable as DV}from"@vkontakte/videoplayer-shared/es2018";var Kd=({seekState:a,position$:e})=>$V(a.stateChangeEnded$.pipe(MV(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),wE(DV)),e.pipe(wE(()=>a.getState().state==="none")));import{assertNonNullable as CV}from"@vkontakte/videoplayer-shared/es2018";var AE=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return CV(e,`Wrong container or containerId {${a.container}}`),e};import{filter as BV,once as VV}from"@vkontakte/videoplayer-shared/es2018";var PE=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(BV(r=>r.length>0),VV()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var su=class{constructor(e={configName:[]},t=NV.createRootTracer(!1)){this.subscription=new LE;this.logger=new OV;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new C(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new C(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new q("stopped"),seekState:new q({state:"none"}),volume:new q({volume:1,muted:!1}),videoTrack:new q(void 0),videoStream:new q(void 0),audioStream:new q(void 0),autoVideoTrackSwitching:new q(!0),autoVideoTrackLimits:new q({}),isLooped:new q(!1),isLowLatency:new q(!1),playbackRate:new q(1),externalTextTracks:new q([]),internalTextTracks:new q([]),currentTextTrack:new q(void 0),textTrackCuesSettings:new q({}),cameraOrientation:new q({x:0,y:0})};this.info={playbackState$:new C(void 0),position$:new C(0),duration$:new C(1/0),muted$:new C(!1),volume$:new C(1),availableVideoStreams$:new C([]),currentVideoStream$:new C(void 0),availableQualities$:new C([]),availableQualitiesFps$:new C({}),currentQuality$:new C(void 0),isAutoQualityEnabled$:new C(!0),autoQualityLimitingAvailable$:new C(!1),autoQualityLimits$:new C({}),predefinedQualityLimitType$:new C("unknown"),availableAudioStreams$:new C([]),currentAudioStream$:new C(void 0),availableAudioTracks$:new C([]),isAudioAvailable$:new C(!0),currentPlaybackRate$:new C(1),currentBuffer$:new C({start:0,end:0}),isBuffering$:new C(!0),isStalled$:new C(!1),isEnded$:new C(!1),isLooped$:new C(!1),isLive$:new C(void 0),isLiveEnded$:new C(null),canPlayLiveTailBuffer$:new C(!1),canChangePlaybackSpeed$:new C(void 0),atLiveEdge$:new C(void 0),atLiveDurationEdge$:new C(void 0),liveTime$:new C(void 0),liveBufferTime$:new C(void 0),liveLatency$:new C(void 0),currentFormat$:new C(void 0),availableTextTracks$:new C([]),currentTextTrack$:new C(void 0),throughputEstimation$:new C(void 0),rttEstimation$:new C(void 0),videoBitrate$:new C(void 0),hostname$:new C(void 0),httpConnectionType$:new C(void 0),httpConnectionReused$:new C(void 0),surface$:new C("none"),chromecastState$:new C("NOT_AVAILABLE"),chromecastDeviceName$:new C(void 0),intrinsicVideoSize$:new C(void 0),availableSources$:new C(void 0),is3DVideo$:new C(!1),currentVideoSegmentLength$:new C(0),currentAudioSegmentLength$:new C(0)};this.events={inited$:new K,ready$:new K,started$:new K,playing$:new K,paused$:new K,stopped$:new K,willReady$:new K,willStart$:new K,willResume$:new K,willPause$:new K,willStop$:new K,willDestruct$:new K,watchCoverageRecord$:new K,watchCoverageLive$:new K,managedError$:new K,fatalError$:new K,fetcherRecoverableError$:new K,ended$:new K,looped$:new K,seeked$:new K,willSeek$:new K,autoplaySoundProhibited$:new K,firstBytes$:new K,loadedMetadata$:new K,firstFrame$:new K,canplay$:new K,log$:new K,fetcherError$:new K,severeStallOccured$:new K};this.experimental={element$:new C(void 0),tuningConfigName$:new C([]),enableDebugTelemetry$:new C(!1),dumpTelemetry:Tv,getCurrentTime$:new C(null)};if(this.initLogs(),this.tuning=xE(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new rn({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new IE(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new UV("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(f=>JSON.stringify(f,(p,h)=>{let m=typeof h;return(0,DE.default)(["number","string","boolean"],m)?h:h===null?null:`<${m}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:ru.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{var u,l,c;let{container:n,...o}=e;this.tracer.log("initVideo",si(o)),this.domContainer=AE(e),this.chromecastInitializer.contentId=(u=e.meta)==null?void 0:u.videoId,this.providerContainer=new Bs({sources:e.sources,meta:(l=e.meta)!=null?l:{},failoverHosts:(c=e.failoverHosts)!=null?c:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?F.isInited$.pipe(U(n=>!!n),H()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Xd(document,"visibilitychange").pipe(H()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{var o;let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,s=i.getTransition(),n=(o=s==null?void 0:s.to.volume)!=null?o:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{iu(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(U(i=>i.length>0),H()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",si(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{var i;iu(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",si(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{var t;PE(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(U(t=>!!t),H()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(U(i=>!!i),H()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(U(e=>e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(U(e=>!!e),H()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(_V(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return kE(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ai(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Sc(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(U(({from:e})=>e==="stopped"),H()).subscribe(()=>{this.initedAt=au(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",si(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:ru.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(H()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",si(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),z()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(_t({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>$E(u)?1:$E(l)?-1:FV(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(z()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(U(n=>kE(n))).subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(z((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(z((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(z()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(z()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(z()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(G(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(Jd(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(_t({hasLiveOffsetByPaused:ai(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),z(),G(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(_t({atLiveEdge:_t({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Kd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),z(),Jd(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(_t({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),z(),Jd(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),z()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),z()).subscribe(this.info.volume$)).add(Kd({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ai(e.providerOutput.endedEvent$.pipe(RE(!0)),e.providerOutput.seekedEvent$.pipe(RE(!1))).pipe(z()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(G(n=>({id:n?`No${n}`:"NoProviders",category:ru.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(H(),G(n=>n!=null?n:au()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(H(),G(()=>au()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(H(),G(()=>au()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new C(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new C(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(U(({to:n})=>n==="playing"),H()).subscribe(()=>i.next(!1)));let r=0,s=ai(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),z());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ai(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ai(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(G(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new LE;this.subscription.add(t),this.subscription.add(e.current$.pipe(z((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(U(i=>i.length>0),H()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=vt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(ai(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;iu(this.providerContainer),iu(e),yv(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>vv(i)),this.providerContainer.current$.subscribe(({type:i})=>Ia("provider",i)),e.duration$.subscribe(i=>Ia("duration",i)),e.availableVideoTracks$.pipe(U(i=>!!i.length),H()).subscribe(i=>Ia("tracks",i)),this.events.fatalError$.subscribe(new ke("fatalError")),this.events.managedError$.subscribe(new ke("managedError")),e.position$.subscribe(new ke("position")),e.currentVideoTrack$.pipe(G(i=>i==null?void 0:i.quality)).subscribe(new ke("quality")),this.info.currentBuffer$.subscribe(new ke("buffer")),e.isBuffering$.subscribe(new ke("isBuffering"))].forEach(i=>this.subscription.add(i)),Ia("codecs",F.video.supportedCodecs)}initTracerSubscription(){let e=ME(this.tracer.log.bind(this.tracer)),t=ME(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(z()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(_t({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(U(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),z((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(U(i=>i>0),z()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(U(i=>i>0),z()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(_t({currentBuffer:this.info.currentBuffer$.pipe(U(i=>i.end>0),z((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(z())}).pipe(Zd(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(z()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(z()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(z()).subscribe(e("canChangePlaybackSpeed"))).add(_t({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(U(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Zd(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(z(),U(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(z(),U(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(z()).subscribe(e("muted"))).add(this.info.volume$.pipe(z()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(z(),U(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(_t({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(U(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Zd(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(z(),U(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:ru.DOM,message:String(r)})})};this.subscription.add(ai(Xd(document,"visibilitychange"),Xd(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",si({quality:t,availableTracks:si(e),track:si(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ra()}};import{Subscription as Z9,Observable as eJ,Subject as tJ,ValueSubject as iJ,VideoQuality as rJ}from"@vkontakte/videoplayer-shared/es2018";var aJ=`@vkontakte/videoplayer-core@${Fp}`;export{Ys as ChromecastState,du as HttpConnectionType,eJ as Observable,Le as PlaybackState,su as Player,Ks as PredefinedQualityLimits,aJ as SDK_VERSION,tJ as Subject,Z9 as Subscription,pu as Surface,Fp as VERSION,iJ as ValueSubject,At as VideoFormat,rJ as VideoQuality,V$ as areValidLiveRecordSources,F as clientChecker,ga as isMobile};