@vkontakte/videoplayer-core 2.0.149-dev.e6e86083.0 → 2.0.150-dev.31e6196f.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/esnext.esm.js CHANGED
@@ -1,19 +1,19 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.149-dev.e6e86083.0
3
- * Wed, 17 Dec 2025 14:34:56 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-149/doc/
2
+ * @vkontakte/videoplayer-core v2.0.150-dev.31e6196f.0
3
+ * Fri, 19 Dec 2025 10:49:43 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-150/doc/
5
5
  */
6
- var Yw=Object.create;var mh=Object.defineProperty;var Kw=Object.getOwnPropertyDescriptor;var Xw=Object.getOwnPropertyNames;var Jw=Object.getPrototypeOf,Zw=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var ex=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Xw(e))!Zw.call(s,r)&&r!==t&&mh(s,r,{get:()=>e[r],enumerable:!(i=Kw(e,r))||i.enumerable});return s};var D=(s,e,t)=>(t=s!=null?Yw(Jw(s)):{},ex(e||!s||!s.__esModule?mh(t,"default",{value:s,enumerable:!0}):t,s));var se=b((il,gh)=>{"use strict";var Ps=function(s){return s&&s.Math===Math&&s};gh.exports=Ps(typeof globalThis=="object"&&globalThis)||Ps(typeof window=="object"&&window)||Ps(typeof self=="object"&&self)||Ps(typeof global=="object"&&global)||Ps(typeof il=="object"&&il)||function(){return this}()||Function("return this")()});var ge=b((CN,Sh)=>{"use strict";Sh.exports=function(s){try{return!!s()}catch{return!0}}});var ks=b((VN,vh)=>{"use strict";var tx=ge();vh.exports=!tx(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var rl=b((_N,Eh)=>{"use strict";var ix=ks(),Ih=Function.prototype,yh=Ih.apply,Th=Ih.call;Eh.exports=typeof Reflect=="object"&&Reflect.apply||(ix?Th.bind(yh):function(){return Th.apply(yh,arguments)})});var Se=b((ON,Ph)=>{"use strict";var wh=ks(),xh=Function.prototype,sl=xh.call,rx=wh&&xh.bind.bind(sl,sl);Ph.exports=wh?rx:function(s){return function(){return sl.apply(s,arguments)}}});var Ri=b((NN,Ah)=>{"use strict";var kh=Se(),sx=kh({}.toString),ax=kh("".slice);Ah.exports=function(s){return ax(sx(s),8,-1)}});var al=b((FN,Rh)=>{"use strict";var nx=Ri(),ox=Se();Rh.exports=function(s){if(nx(s)==="Function")return ox(s)}});var ae=b((UN,$h)=>{"use strict";var nl=typeof document=="object"&&document.all;$h.exports=typeof nl>"u"&&nl!==void 0?function(s){return typeof s=="function"||s===nl}:function(s){return typeof s=="function"}});var Je=b((qN,Mh)=>{"use strict";var ux=ge();Mh.exports=!ux(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ze=b((jN,Lh)=>{"use strict";var lx=ks(),qn=Function.prototype.call;Lh.exports=lx?qn.bind(qn):function(){return qn.apply(qn,arguments)}});var ol=b(Ch=>{"use strict";var Dh={}.propertyIsEnumerable,Bh=Object.getOwnPropertyDescriptor,cx=Bh&&!Dh.call({1:2},1);Ch.f=cx?function(e){var t=Bh(this,e);return!!t&&t.enumerable}:Dh});var As=b((WN,Vh)=>{"use strict";Vh.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var Oh=b((zN,_h)=>{"use strict";var dx=Se(),px=ge(),hx=Ri(),ul=Object,fx=dx("".split);_h.exports=px(function(){return!ul("z").propertyIsEnumerable(0)})?function(s){return hx(s)==="String"?fx(s,""):ul(s)}:ul});var Rs=b((QN,Nh)=>{"use strict";Nh.exports=function(s){return s==null}});var ri=b((GN,Fh)=>{"use strict";var mx=Rs(),bx=TypeError;Fh.exports=function(s){if(mx(s))throw new bx("Can't call method on "+s);return s}});var $i=b((YN,Uh)=>{"use strict";var gx=Oh(),Sx=ri();Uh.exports=function(s){return gx(Sx(s))}});var We=b((KN,qh)=>{"use strict";var vx=ae();qh.exports=function(s){return typeof s=="object"?s!==null:vx(s)}});var Mi=b((XN,jh)=>{"use strict";jh.exports={}});var _t=b((JN,Wh)=>{"use strict";var ll=Mi(),cl=se(),yx=ae(),Hh=function(s){return yx(s)?s:void 0};Wh.exports=function(s,e){return arguments.length<2?Hh(ll[s])||Hh(cl[s]):ll[s]&&ll[s][e]||cl[s]&&cl[s][e]}});var $s=b((ZN,zh)=>{"use strict";var Tx=Se();zh.exports=Tx({}.isPrototypeOf)});var Li=b((eF,Yh)=>{"use strict";var Ix=se(),Qh=Ix.navigator,Gh=Qh&&Qh.userAgent;Yh.exports=Gh?String(Gh):""});var pl=b((tF,tf)=>{"use strict";var ef=se(),dl=Li(),Kh=ef.process,Xh=ef.Deno,Jh=Kh&&Kh.versions||Xh&&Xh.version,Zh=Jh&&Jh.v8,bt,jn;Zh&&(bt=Zh.split("."),jn=bt[0]>0&&bt[0]<4?1:+(bt[0]+bt[1]));!jn&&dl&&(bt=dl.match(/Edge\/(\d+)/),(!bt||bt[1]>=74)&&(bt=dl.match(/Chrome\/(\d+)/),bt&&(jn=+bt[1])));tf.exports=jn});var hl=b((iF,sf)=>{"use strict";var rf=pl(),Ex=ge(),wx=se(),xx=wx.String;sf.exports=!!Object.getOwnPropertySymbols&&!Ex(function(){var s=Symbol("symbol detection");return!xx(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&rf&&rf<41})});var fl=b((rF,af)=>{"use strict";var Px=hl();af.exports=Px&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ml=b((sF,nf)=>{"use strict";var kx=_t(),Ax=ae(),Rx=$s(),$x=fl(),Mx=Object;nf.exports=$x?function(s){return typeof s=="symbol"}:function(s){var e=kx("Symbol");return Ax(e)&&Rx(e.prototype,Mx(s))}});var Ms=b((aF,of)=>{"use strict";var Lx=String;of.exports=function(s){try{return Lx(s)}catch{return"Object"}}});var kt=b((nF,uf)=>{"use strict";var Dx=ae(),Bx=Ms(),Cx=TypeError;uf.exports=function(s){if(Dx(s))return s;throw new Cx(Bx(s)+" is not a function")}});var Ls=b((oF,lf)=>{"use strict";var Vx=kt(),_x=Rs();lf.exports=function(s,e){var t=s[e];return _x(t)?void 0:Vx(t)}});var df=b((uF,cf)=>{"use strict";var bl=Ze(),gl=ae(),Sl=We(),Ox=TypeError;cf.exports=function(s,e){var t,i;if(e==="string"&&gl(t=s.toString)&&!Sl(i=bl(t,s))||gl(t=s.valueOf)&&!Sl(i=bl(t,s))||e!=="string"&&gl(t=s.toString)&&!Sl(i=bl(t,s)))return i;throw new Ox("Can't convert object to primitive value")}});var gt=b((lF,pf)=>{"use strict";pf.exports=!0});var mf=b((cF,ff)=>{"use strict";var hf=se(),Nx=Object.defineProperty;ff.exports=function(s,e){try{Nx(hf,s,{value:e,configurable:!0,writable:!0})}catch{hf[s]=e}return e}});var Ds=b((dF,Sf)=>{"use strict";var Fx=gt(),Ux=se(),qx=mf(),bf="__core-js_shared__",gf=Sf.exports=Ux[bf]||qx(bf,{});(gf.versions||(gf.versions=[])).push({version:"3.43.0",mode:Fx?"pure":"global",copyright:"© 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 vl=b((pF,yf)=>{"use strict";var vf=Ds();yf.exports=function(s,e){return vf[s]||(vf[s]=e||{})}});var br=b((hF,Tf)=>{"use strict";var jx=ri(),Hx=Object;Tf.exports=function(s){return Hx(jx(s))}});var St=b((fF,If)=>{"use strict";var Wx=Se(),zx=br(),Qx=Wx({}.hasOwnProperty);If.exports=Object.hasOwn||function(e,t){return Qx(zx(e),t)}});var yl=b((mF,Ef)=>{"use strict";var Gx=Se(),Yx=0,Kx=Math.random(),Xx=Gx(1.1.toString);Ef.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Xx(++Yx+Kx,36)}});var Pe=b((bF,xf)=>{"use strict";var Jx=se(),Zx=vl(),wf=St(),eP=yl(),tP=hl(),iP=fl(),gr=Jx.Symbol,Tl=Zx("wks"),rP=iP?gr.for||gr:gr&&gr.withoutSetter||eP;xf.exports=function(s){return wf(Tl,s)||(Tl[s]=tP&&wf(gr,s)?gr[s]:rP("Symbol."+s)),Tl[s]}});var Rf=b((gF,Af)=>{"use strict";var sP=Ze(),Pf=We(),kf=ml(),aP=Ls(),nP=df(),oP=Pe(),uP=TypeError,lP=oP("toPrimitive");Af.exports=function(s,e){if(!Pf(s)||kf(s))return s;var t=aP(s,lP),i;if(t){if(e===void 0&&(e="default"),i=sP(t,s,e),!Pf(i)||kf(i))return i;throw new uP("Can't convert object to primitive value")}return e===void 0&&(e="number"),nP(s,e)}});var Il=b((SF,$f)=>{"use strict";var cP=Rf(),dP=ml();$f.exports=function(s){var e=cP(s,"string");return dP(e)?e:e+""}});var Hn=b((vF,Lf)=>{"use strict";var pP=se(),Mf=We(),El=pP.document,hP=Mf(El)&&Mf(El.createElement);Lf.exports=function(s){return hP?El.createElement(s):{}}});var wl=b((yF,Df)=>{"use strict";var fP=Je(),mP=ge(),bP=Hn();Df.exports=!fP&&!mP(function(){return Object.defineProperty(bP("div"),"a",{get:function(){return 7}}).a!==7})});var Vf=b(Cf=>{"use strict";var gP=Je(),SP=Ze(),vP=ol(),yP=As(),TP=$i(),IP=Il(),EP=St(),wP=wl(),Bf=Object.getOwnPropertyDescriptor;Cf.f=gP?Bf:function(e,t){if(e=TP(e),t=IP(t),wP)try{return Bf(e,t)}catch{}if(EP(e,t))return yP(!SP(vP.f,e,t),e[t])}});var xl=b((IF,_f)=>{"use strict";var xP=ge(),PP=ae(),kP=/#|\.prototype\./,Bs=function(s,e){var t=RP[AP(s)];return t===MP?!0:t===$P?!1:PP(e)?xP(e):!!e},AP=Bs.normalize=function(s){return String(s).replace(kP,".").toLowerCase()},RP=Bs.data={},$P=Bs.NATIVE="N",MP=Bs.POLYFILL="P";_f.exports=Bs});var Sr=b((EF,Nf)=>{"use strict";var Of=al(),LP=kt(),DP=ks(),BP=Of(Of.bind);Nf.exports=function(s,e){return LP(s),e===void 0?s:DP?BP(s,e):function(){return s.apply(e,arguments)}}});var Pl=b((wF,Ff)=>{"use strict";var CP=Je(),VP=ge();Ff.exports=CP&&VP(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var At=b((xF,Uf)=>{"use strict";var _P=We(),OP=String,NP=TypeError;Uf.exports=function(s){if(_P(s))return s;throw new NP(OP(s)+" is not an object")}});var Di=b(jf=>{"use strict";var FP=Je(),UP=wl(),qP=Pl(),Wn=At(),qf=Il(),jP=TypeError,kl=Object.defineProperty,HP=Object.getOwnPropertyDescriptor,Al="enumerable",Rl="configurable",$l="writable";jf.f=FP?qP?function(e,t,i){if(Wn(e),t=qf(t),Wn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&$l in i&&!i[$l]){var r=HP(e,t);r&&r[$l]&&(e[t]=i.value,i={configurable:Rl in i?i[Rl]:r[Rl],enumerable:Al in i?i[Al]:r[Al],writable:!1})}return kl(e,t,i)}:kl:function(e,t,i){if(Wn(e),t=qf(t),Wn(i),UP)try{return kl(e,t,i)}catch{}if("get"in i||"set"in i)throw new jP("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var vr=b((kF,Hf)=>{"use strict";var WP=Je(),zP=Di(),QP=As();Hf.exports=WP?function(s,e,t){return zP.f(s,e,QP(1,t))}:function(s,e,t){return s[e]=t,s}});var ue=b((AF,zf)=>{"use strict";var Cs=se(),GP=rl(),YP=al(),KP=ae(),XP=Vf().f,JP=xl(),yr=Mi(),ZP=Sr(),Tr=vr(),Wf=St();Ds();var ek=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return GP(s,this,arguments)};return e.prototype=s.prototype,e};zf.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Cs:r?Cs[t]:Cs[t]&&Cs[t].prototype,o=i?yr:yr[t]||Tr(yr,t,{})[t],u=o.prototype,l,p,c,d,h,f,m,S,g;for(d in e)l=JP(i?d:t+(r?".":"#")+d,s.forced),p=!l&&n&&Wf(n,d),f=o[d],p&&(s.dontCallGetSet?(g=XP(n,d),m=g&&g.value):m=n[d]),h=p&&m?m:e[d],!(!l&&!a&&typeof f==typeof h)&&(s.bind&&p?S=ZP(h,Cs):s.wrap&&p?S=ek(h):a&&KP(h)?S=YP(h):S=h,(s.sham||h&&h.sham||f&&f.sham)&&Tr(S,"sham",!0),Tr(o,d,S),a&&(c=t+"Prototype",Wf(yr,c)||Tr(yr,c,{}),Tr(yr[c],d,h),s.real&&u&&(l||!u[d])&&Tr(u,d,h)))}});var zn=b((RF,Gf)=>{"use strict";var tk=vl(),ik=yl(),Qf=tk("keys");Gf.exports=function(s){return Qf[s]||(Qf[s]=ik(s))}});var Kf=b(($F,Yf)=>{"use strict";var rk=ge();Yf.exports=!rk(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Qn=b((MF,Jf)=>{"use strict";var sk=St(),ak=ae(),nk=br(),ok=zn(),uk=Kf(),Xf=ok("IE_PROTO"),Ml=Object,lk=Ml.prototype;Jf.exports=uk?Ml.getPrototypeOf:function(s){var e=nk(s);if(sk(e,Xf))return e[Xf];var t=e.constructor;return ak(t)&&e instanceof t?t.prototype:e instanceof Ml?lk:null}});var em=b((LF,Zf)=>{"use strict";var ck=Math.ceil,dk=Math.floor;Zf.exports=Math.trunc||function(e){var t=+e;return(t>0?dk:ck)(t)}});var Vs=b((DF,tm)=>{"use strict";var pk=em();tm.exports=function(s){var e=+s;return e!==e||e===0?0:pk(e)}});var rm=b((BF,im)=>{"use strict";var hk=Vs(),fk=Math.max,mk=Math.min;im.exports=function(s,e){var t=hk(s);return t<0?fk(t+e,0):mk(t,e)}});var Ll=b((CF,sm)=>{"use strict";var bk=Vs(),gk=Math.min;sm.exports=function(s){var e=bk(s);return e>0?gk(e,9007199254740991):0}});var Ir=b((VF,am)=>{"use strict";var Sk=Ll();am.exports=function(s){return Sk(s.length)}});var Dl=b((_F,om)=>{"use strict";var vk=$i(),yk=rm(),Tk=Ir(),nm=function(s){return function(e,t,i){var r=vk(e),a=Tk(r);if(a===0)return!s&&-1;var n=yk(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};om.exports={includes:nm(!0),indexOf:nm(!1)}});var Gn=b((OF,um)=>{"use strict";um.exports={}});var dm=b((NF,cm)=>{"use strict";var Ik=Se(),Bl=St(),Ek=$i(),wk=Dl().indexOf,xk=Gn(),lm=Ik([].push);cm.exports=function(s,e){var t=Ek(s),i=0,r=[],a;for(a in t)!Bl(xk,a)&&Bl(t,a)&&lm(r,a);for(;e.length>i;)Bl(t,a=e[i++])&&(~wk(r,a)||lm(r,a));return r}});var Cl=b((FF,pm)=>{"use strict";pm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Vl=b((UF,hm)=>{"use strict";var Pk=dm(),kk=Cl();hm.exports=Object.keys||function(e){return Pk(e,kk)}});var _l=b((qF,Sm)=>{"use strict";var mm=Je(),Ak=ge(),bm=Se(),Rk=Qn(),$k=Vl(),Mk=$i(),Lk=ol().f,gm=bm(Lk),Dk=bm([].push),Bk=mm&&Ak(function(){var s=Object.create(null);return s[2]=2,!gm(s,2)}),fm=function(s){return function(e){for(var t=Mk(e),i=$k(t),r=Bk&&Rk(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!mm||(r?u in t:gm(t,u)))&&Dk(o,s?[u,t[u]]:t[u]);return o}};Sm.exports={entries:fm(!0),values:fm(!1)}});var vm=b(()=>{"use strict";var Ck=ue(),Vk=_l().values;Ck({target:"Object",stat:!0},{values:function(e){return Vk(e)}})});var Tm=b((WF,ym)=>{"use strict";vm();var _k=Mi();ym.exports=_k.Object.values});var Em=b((zF,Im)=>{"use strict";var Ok=Tm();Im.exports=Ok});var Bi=b((QF,wm)=>{"use strict";var Nk=Em();wm.exports=Nk});var _s=b((GF,xm)=>{"use strict";xm.exports=function(){}});var Pm=b(()=>{"use strict";var Fk=ue(),Uk=Dl().includes,qk=ge(),jk=_s(),Hk=qk(function(){return!Array(1).includes()});Fk({target:"Array",proto:!0,forced:Hk},{includes:function(e){return Uk(this,e,arguments.length>1?arguments[1]:void 0)}});jk("includes")});var si=b((XF,km)=>{"use strict";var Wk=_t();km.exports=Wk});var Rm=b((JF,Am)=>{"use strict";Pm();var zk=si();Am.exports=zk("Array","includes")});var Mm=b((ZF,$m)=>{"use strict";var Qk=Rm();$m.exports=Qk});var ke=b((eU,Lm)=>{"use strict";var Gk=Mm();Lm.exports=Gk});var sb=b(()=>{"use strict";var BA=ue(),CA=_l().entries;BA({target:"Object",stat:!0},{entries:function(e){return CA(e)}})});var nb=b((e1,ab)=>{"use strict";sb();var VA=Mi();ab.exports=VA.Object.entries});var ub=b((t1,ob)=>{"use strict";var _A=nb();ob.exports=_A});var oi=b((i1,lb)=>{"use strict";var OA=ub();lb.exports=OA});var _i=b((r1,cb)=>{"use strict";cb.exports={}});var hb=b((s1,pb)=>{"use strict";var NA=se(),FA=ae(),db=NA.WeakMap;pb.exports=FA(db)&&/native code/.test(String(db))});var Zl=b((a1,bb)=>{"use strict";var UA=hb(),mb=se(),qA=We(),jA=vr(),Kl=St(),Xl=Ds(),HA=zn(),WA=Gn(),fb="Object already initialized",Jl=mb.TypeError,zA=mb.WeakMap,ao,qs,no,QA=function(s){return no(s)?qs(s):ao(s,{})},GA=function(s){return function(e){var t;if(!qA(e)||(t=qs(e)).type!==s)throw new Jl("Incompatible receiver, "+s+" required");return t}};UA||Xl.state?(yt=Xl.state||(Xl.state=new zA),yt.get=yt.get,yt.has=yt.has,yt.set=yt.set,ao=function(s,e){if(yt.has(s))throw new Jl(fb);return e.facade=s,yt.set(s,e),e},qs=function(s){return yt.get(s)||{}},no=function(s){return yt.has(s)}):(Oi=HA("state"),WA[Oi]=!0,ao=function(s,e){if(Kl(s,Oi))throw new Jl(fb);return e.facade=s,jA(s,Oi,e),e},qs=function(s){return Kl(s,Oi)?s[Oi]:{}},no=function(s){return Kl(s,Oi)});var yt,Oi;bb.exports={set:ao,get:qs,has:no,enforce:QA,getterFor:GA}});var ic=b((n1,Sb)=>{"use strict";var ec=Je(),YA=St(),gb=Function.prototype,KA=ec&&Object.getOwnPropertyDescriptor,tc=YA(gb,"name"),XA=tc&&function(){}.name==="something",JA=tc&&(!ec||ec&&KA(gb,"name").configurable);Sb.exports={EXISTS:tc,PROPER:XA,CONFIGURABLE:JA}});var yb=b(vb=>{"use strict";var ZA=Je(),eR=Pl(),tR=Di(),iR=At(),rR=$i(),sR=Vl();vb.f=ZA&&!eR?Object.defineProperties:function(e,t){iR(e);for(var i=rR(t),r=sR(t),a=r.length,n=0,o;a>n;)tR.f(e,o=r[n++],i[o]);return e}});var rc=b((u1,Tb)=>{"use strict";var aR=_t();Tb.exports=aR("document","documentElement")});var oc=b((l1,Ab)=>{"use strict";var nR=At(),oR=yb(),Ib=Cl(),uR=Gn(),lR=rc(),cR=Hn(),dR=zn(),Eb=">",wb="<",ac="prototype",nc="script",Pb=dR("IE_PROTO"),sc=function(){},kb=function(s){return wb+nc+Eb+s+wb+"/"+nc+Eb},xb=function(s){s.write(kb("")),s.close();var e=s.parentWindow.Object;return s=null,e},pR=function(){var s=cR("iframe"),e="java"+nc+":",t;return s.style.display="none",lR.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(kb("document.F=Object")),t.close(),t.F},oo,uo=function(){try{oo=new ActiveXObject("htmlfile")}catch{}uo=typeof document<"u"?document.domain&&oo?xb(oo):pR():xb(oo);for(var s=Ib.length;s--;)delete uo[ac][Ib[s]];return uo()};uR[Pb]=!0;Ab.exports=Object.create||function(e,t){var i;return e!==null?(sc[ac]=nR(e),i=new sc,sc[ac]=null,i[Pb]=e):i=uo(),t===void 0?i:oR.f(i,t)}});var Pr=b((c1,Rb)=>{"use strict";var hR=vr();Rb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:hR(s,e,t),s}});var dc=b((d1,Lb)=>{"use strict";var fR=ge(),mR=ae(),bR=We(),gR=oc(),$b=Qn(),SR=Pr(),vR=Pe(),yR=gt(),cc=vR("iterator"),Mb=!1,Nt,uc,lc;[].keys&&(lc=[].keys(),"next"in lc?(uc=$b($b(lc)),uc!==Object.prototype&&(Nt=uc)):Mb=!0);var TR=!bR(Nt)||fR(function(){var s={};return Nt[cc].call(s)!==s});TR?Nt={}:yR&&(Nt=gR(Nt));mR(Nt[cc])||SR(Nt,cc,function(){return this});Lb.exports={IteratorPrototype:Nt,BUGGY_SAFARI_ITERATORS:Mb}});var lo=b((p1,Bb)=>{"use strict";var IR=Pe(),ER=IR("toStringTag"),Db={};Db[ER]="z";Bb.exports=String(Db)==="[object z]"});var js=b((h1,Cb)=>{"use strict";var wR=lo(),xR=ae(),co=Ri(),PR=Pe(),kR=PR("toStringTag"),AR=Object,RR=co(function(){return arguments}())==="Arguments",$R=function(s,e){try{return s[e]}catch{}};Cb.exports=wR?co:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=$R(e=AR(s),kR))=="string"?t:RR?co(e):(i=co(e))==="Object"&&xR(e.callee)?"Arguments":i}});var _b=b((f1,Vb)=>{"use strict";var MR=lo(),LR=js();Vb.exports=MR?{}.toString:function(){return"[object "+LR(this)+"]"}});var Hs=b((m1,Nb)=>{"use strict";var DR=lo(),BR=Di().f,CR=vr(),VR=St(),_R=_b(),OR=Pe(),Ob=OR("toStringTag");Nb.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(VR(r,Ob)||BR(r,Ob,{configurable:!0,value:e}),i&&!DR&&CR(r,"toString",_R))}});var Ub=b((b1,Fb)=>{"use strict";var NR=dc().IteratorPrototype,FR=oc(),UR=As(),qR=Hs(),jR=_i(),HR=function(){return this};Fb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=FR(NR,{next:UR(+!i,t)}),qR(s,r,!1,!0),jR[r]=HR,s}});var jb=b((g1,qb)=>{"use strict";var WR=Se(),zR=kt();qb.exports=function(s,e,t){try{return WR(zR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch{}}});var Wb=b((S1,Hb)=>{"use strict";var QR=We();Hb.exports=function(s){return QR(s)||s===null}});var Qb=b((v1,zb)=>{"use strict";var GR=Wb(),YR=String,KR=TypeError;zb.exports=function(s){if(GR(s))return s;throw new KR("Can't set "+YR(s)+" as a prototype")}});var pc=b((y1,Gb)=>{"use strict";var XR=jb(),JR=We(),ZR=ri(),e$=Qb();Gb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=XR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch{}return function(r,a){return ZR(r),e$(a),JR(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var ag=b((T1,sg)=>{"use strict";var t$=ue(),i$=Ze(),po=gt(),ig=ic(),r$=ae(),s$=Ub(),Yb=Qn(),Kb=pc(),a$=Hs(),n$=vr(),hc=Pr(),o$=Pe(),Xb=_i(),rg=dc(),u$=ig.PROPER,l$=ig.CONFIGURABLE,Jb=rg.IteratorPrototype,ho=rg.BUGGY_SAFARI_ITERATORS,Ws=o$("iterator"),Zb="keys",zs="values",eg="entries",tg=function(){return this};sg.exports=function(s,e,t,i,r,a,n){s$(t,e,i);var o=function(g){if(g===r&&d)return d;if(!ho&&g&&g in p)return p[g];switch(g){case Zb:return function(){return new t(this,g)};case zs:return function(){return new t(this,g)};case eg:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,p=s.prototype,c=p[Ws]||p["@@iterator"]||r&&p[r],d=!ho&&c||o(r),h=e==="Array"&&p.entries||c,f,m,S;if(h&&(f=Yb(h.call(new s)),f!==Object.prototype&&f.next&&(!po&&Yb(f)!==Jb&&(Kb?Kb(f,Jb):r$(f[Ws])||hc(f,Ws,tg)),a$(f,u,!0,!0),po&&(Xb[u]=tg))),u$&&r===zs&&c&&c.name!==zs&&(!po&&l$?n$(p,"name",zs):(l=!0,d=function(){return i$(c,this)})),r)if(m={values:o(zs),keys:a?d:o(Zb),entries:o(eg)},n)for(S in m)(ho||l||!(S in p))&&hc(p,S,m[S]);else t$({target:e,proto:!0,forced:ho||l},m);return(!po||n)&&p[Ws]!==d&&hc(p,Ws,d,{name:r}),Xb[e]=d,m}});var og=b((I1,ng)=>{"use strict";ng.exports=function(s,e){return{value:s,done:e}}});var mc=b((E1,pg)=>{"use strict";var c$=$i(),fc=_s(),ug=_i(),cg=Zl(),d$=Di().f,p$=ag(),fo=og(),h$=gt(),f$=Je(),dg="Array Iterator",m$=cg.set,b$=cg.getterFor(dg);pg.exports=p$(Array,"Array",function(s,e){m$(this,{type:dg,target:c$(s),index:0,kind:e})},function(){var s=b$(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,fo(void 0,!0);switch(s.kind){case"keys":return fo(t,!1);case"values":return fo(e[t],!1)}return fo([t,e[t]],!1)},"values");var lg=ug.Arguments=ug.Array;fc("keys");fc("values");fc("entries");if(!h$&&f$&&lg.name!=="values")try{d$(lg,"name",{value:"values"})}catch{}});var fg=b((w1,hg)=>{"use strict";var g$=Pe(),S$=_i(),v$=g$("iterator"),y$=Array.prototype;hg.exports=function(s){return s!==void 0&&(S$.Array===s||y$[v$]===s)}});var bc=b((x1,bg)=>{"use strict";var T$=js(),mg=Ls(),I$=Rs(),E$=_i(),w$=Pe(),x$=w$("iterator");bg.exports=function(s){if(!I$(s))return mg(s,x$)||mg(s,"@@iterator")||E$[T$(s)]}});var Sg=b((P1,gg)=>{"use strict";var P$=Ze(),k$=kt(),A$=At(),R$=Ms(),$$=bc(),M$=TypeError;gg.exports=function(s,e){var t=arguments.length<2?$$(s):e;if(k$(t))return A$(P$(t,s));throw new M$(R$(s)+" is not iterable")}});var Tg=b((k1,yg)=>{"use strict";var L$=Ze(),vg=At(),D$=Ls();yg.exports=function(s,e,t){var i,r;vg(s);try{if(i=D$(s,"return"),!i){if(e==="throw")throw t;return t}i=L$(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return vg(i),t}});var bo=b((A1,xg)=>{"use strict";var B$=Sr(),C$=Ze(),V$=At(),_$=Ms(),O$=fg(),N$=Ir(),Ig=$s(),F$=Sg(),U$=bc(),Eg=Tg(),q$=TypeError,mo=function(s,e){this.stopped=s,this.result=e},wg=mo.prototype;xg.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=B$(e,i),l,p,c,d,h,f,m,S=function(v){return l&&Eg(l,"normal"),new mo(!0,v)},g=function(v){return r?(V$(v),o?u(v[0],v[1],S):u(v[0],v[1])):o?u(v,S):u(v)};if(a)l=s.iterator;else if(n)l=s;else{if(p=U$(s),!p)throw new q$(_$(s)+" is not iterable");if(O$(p)){for(c=0,d=N$(s);d>c;c++)if(h=g(s[c]),h&&Ig(wg,h))return h;return new mo(!1)}l=F$(s,p)}for(f=a?s.next:l.next;!(m=C$(f,l)).done;){try{h=g(m.value)}catch(v){Eg(l,"throw",v)}if(typeof h=="object"&&h&&Ig(wg,h))return h}return new mo(!1)}});var kg=b((R1,Pg)=>{"use strict";var j$=Je(),H$=Di(),W$=As();Pg.exports=function(s,e,t){j$?H$.f(s,e,W$(0,t)):s[e]=t}});var Ag=b(()=>{"use strict";var z$=ue(),Q$=bo(),G$=kg();z$({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Q$(e,function(i,r){G$(t,i,r)},{AS_ENTRIES:!0}),t}})});var $g=b((L1,Rg)=>{"use strict";mc();Ag();var Y$=Mi();Rg.exports=Y$.Object.fromEntries});var Lg=b((D1,Mg)=>{"use strict";Mg.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 Bg=b(()=>{"use strict";mc();var K$=Lg(),X$=se(),J$=Hs(),Dg=_i();for(go in K$)J$(X$[go],go),Dg[go]=Dg.Array;var go});var Vg=b((V1,Cg)=>{"use strict";var Z$=$g();Bg();Cg.exports=Z$});var gc=b((_1,_g)=>{"use strict";var eM=Vg();_g.exports=eM});var Og=b(()=>{"use strict"});var Sc=b((F1,Ng)=>{"use strict";var Qs=se(),tM=Li(),iM=Ri(),So=function(s){return tM.slice(0,s.length)===s};Ng.exports=function(){return So("Bun/")?"BUN":So("Cloudflare-Workers")?"CLOUDFLARE":So("Deno/")?"DENO":So("Node.js/")?"NODE":Qs.Bun&&typeof Bun.version=="string"?"BUN":Qs.Deno&&typeof Deno.version=="object"?"DENO":iM(Qs.process)==="process"?"NODE":Qs.window&&Qs.document?"BROWSER":"REST"}()});var vo=b((U1,Fg)=>{"use strict";var rM=Sc();Fg.exports=rM==="NODE"});var qg=b((q1,Ug)=>{"use strict";var sM=Di();Ug.exports=function(s,e,t){return sM.f(s,e,t)}});var Wg=b((j1,Hg)=>{"use strict";var aM=_t(),nM=qg(),oM=Pe(),uM=Je(),jg=oM("species");Hg.exports=function(s){var e=aM(s);uM&&e&&!e[jg]&&nM(e,jg,{configurable:!0,get:function(){return this}})}});var Qg=b((H1,zg)=>{"use strict";var lM=$s(),cM=TypeError;zg.exports=function(s,e){if(lM(e,s))return s;throw new cM("Incorrect invocation")}});var yc=b((W1,Gg)=>{"use strict";var dM=Se(),pM=ae(),vc=Ds(),hM=dM(Function.toString);pM(vc.inspectSource)||(vc.inspectSource=function(s){return hM(s)});Gg.exports=vc.inspectSource});var Ic=b((z1,Zg)=>{"use strict";var fM=Se(),mM=ge(),Yg=ae(),bM=js(),gM=_t(),SM=yc(),Kg=function(){},Xg=gM("Reflect","construct"),Tc=/^\s*(?:class|function)\b/,vM=fM(Tc.exec),yM=!Tc.test(Kg),Gs=function(e){if(!Yg(e))return!1;try{return Xg(Kg,[],e),!0}catch{return!1}},Jg=function(e){if(!Yg(e))return!1;switch(bM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return yM||!!vM(Tc,SM(e))}catch{return!0}};Jg.sham=!0;Zg.exports=!Xg||mM(function(){var s;return Gs(Gs.call)||!Gs(Object)||!Gs(function(){s=!0})||s})?Jg:Gs});var tS=b((Q1,eS)=>{"use strict";var TM=Ic(),IM=Ms(),EM=TypeError;eS.exports=function(s){if(TM(s))return s;throw new EM(IM(s)+" is not a constructor")}});var Ec=b((G1,rS)=>{"use strict";var iS=At(),wM=tS(),xM=Rs(),PM=Pe(),kM=PM("species");rS.exports=function(s,e){var t=iS(s).constructor,i;return t===void 0||xM(i=iS(t)[kM])?e:wM(i)}});var aS=b((Y1,sS)=>{"use strict";var AM=Se();sS.exports=AM([].slice)});var oS=b((K1,nS)=>{"use strict";var RM=TypeError;nS.exports=function(s,e){if(s<e)throw new RM("Not enough arguments");return s}});var wc=b((X1,uS)=>{"use strict";var $M=Li();uS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test($M)});var Dc=b((J1,gS)=>{"use strict";var et=se(),MM=rl(),LM=Sr(),lS=ae(),DM=St(),bS=ge(),cS=rc(),BM=aS(),dS=Hn(),CM=oS(),VM=wc(),_M=vo(),$c=et.setImmediate,Mc=et.clearImmediate,OM=et.process,xc=et.Dispatch,NM=et.Function,pS=et.MessageChannel,FM=et.String,Pc=0,Ys={},hS="onreadystatechange",Ks,Ni,kc,Ac;bS(function(){Ks=et.location});var Lc=function(s){if(DM(Ys,s)){var e=Ys[s];delete Ys[s],e()}},Rc=function(s){return function(){Lc(s)}},fS=function(s){Lc(s.data)},mS=function(s){et.postMessage(FM(s),Ks.protocol+"//"+Ks.host)};(!$c||!Mc)&&($c=function(e){CM(arguments.length,1);var t=lS(e)?e:NM(e),i=BM(arguments,1);return Ys[++Pc]=function(){MM(t,void 0,i)},Ni(Pc),Pc},Mc=function(e){delete Ys[e]},_M?Ni=function(s){OM.nextTick(Rc(s))}:xc&&xc.now?Ni=function(s){xc.now(Rc(s))}:pS&&!VM?(kc=new pS,Ac=kc.port2,kc.port1.onmessage=fS,Ni=LM(Ac.postMessage,Ac)):et.addEventListener&&lS(et.postMessage)&&!et.importScripts&&Ks&&Ks.protocol!=="file:"&&!bS(mS)?(Ni=mS,et.addEventListener("message",fS,!1)):hS in dS("script")?Ni=function(s){cS.appendChild(dS("script"))[hS]=function(){cS.removeChild(this),Lc(s)}}:Ni=function(s){setTimeout(Rc(s),0)});gS.exports={set:$c,clear:Mc}});var yS=b((Z1,vS)=>{"use strict";var SS=se(),UM=Je(),qM=Object.getOwnPropertyDescriptor;vS.exports=function(s){if(!UM)return SS[s];var e=qM(SS,s);return e&&e.value}});var Bc=b((ej,IS)=>{"use strict";var TS=function(){this.head=null,this.tail=null};TS.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};IS.exports=TS});var wS=b((tj,ES)=>{"use strict";var jM=Li();ES.exports=/ipad|iphone|ipod/i.test(jM)&&typeof Pebble<"u"});var PS=b((ij,xS)=>{"use strict";var HM=Li();xS.exports=/web0s(?!.*chrome)/i.test(HM)});var DS=b((rj,LS)=>{"use strict";var Ar=se(),WM=yS(),kS=Sr(),Cc=Dc().set,zM=Bc(),QM=wc(),GM=wS(),YM=PS(),Vc=vo(),AS=Ar.MutationObserver||Ar.WebKitMutationObserver,RS=Ar.document,$S=Ar.process,yo=Ar.Promise,Nc=WM("queueMicrotask"),kr,_c,Oc,To,MS;Nc||(Xs=new zM,Js=function(){var s,e;for(Vc&&(s=$S.domain)&&s.exit();e=Xs.get();)try{e()}catch(t){throw Xs.head&&kr(),t}s&&s.enter()},!QM&&!Vc&&!YM&&AS&&RS?(_c=!0,Oc=RS.createTextNode(""),new AS(Js).observe(Oc,{characterData:!0}),kr=function(){Oc.data=_c=!_c}):!GM&&yo&&yo.resolve?(To=yo.resolve(void 0),To.constructor=yo,MS=kS(To.then,To),kr=function(){MS(Js)}):Vc?kr=function(){$S.nextTick(Js)}:(Cc=kS(Cc,Ar),kr=function(){Cc(Js)}),Nc=function(s){Xs.head||kr(),Xs.add(s)});var Xs,Js;LS.exports=Nc});var CS=b((sj,BS)=>{"use strict";BS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch{}}});var Io=b((aj,VS)=>{"use strict";VS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var Fi=b((nj,_S)=>{"use strict";var KM=se();_S.exports=KM.Promise});var Rr=b((oj,US)=>{"use strict";var XM=se(),Zs=Fi(),JM=ae(),ZM=xl(),eL=yc(),tL=Pe(),OS=Sc(),iL=gt(),Fc=pl(),NS=Zs&&Zs.prototype,rL=tL("species"),Uc=!1,FS=JM(XM.PromiseRejectionEvent),sL=ZM("Promise",function(){var s=eL(Zs),e=s!==String(Zs);if(!e&&Fc===66||iL&&!(NS.catch&&NS.finally))return!0;if(!Fc||Fc<51||!/native code/.test(s)){var t=new Zs(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[rL]=i,Uc=t.then(function(){})instanceof i,!Uc)return!0}return!e&&(OS==="BROWSER"||OS==="DENO")&&!FS});US.exports={CONSTRUCTOR:sL,REJECTION_EVENT:FS,SUBCLASSING:Uc}});var $r=b((uj,jS)=>{"use strict";var qS=kt(),aL=TypeError,nL=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new aL("Bad Promise constructor");e=i,t=r}),this.resolve=qS(e),this.reject=qS(t)};jS.exports.f=function(s){return new nL(s)}});var lv=b(()=>{"use strict";var oL=ue(),uL=gt(),Po=vo(),ui=se(),lL=Mi(),Br=Ze(),HS=Pr(),WS=pc(),cL=Hs(),dL=Wg(),pL=kt(),xo=ae(),hL=We(),fL=Qg(),mL=Ec(),KS=Dc().set,zc=DS(),bL=CS(),gL=Io(),SL=Bc(),XS=Zl(),ko=Fi(),Qc=Rr(),JS=$r(),Ao="Promise",ZS=Qc.CONSTRUCTOR,vL=Qc.REJECTION_EVENT,yL=Qc.SUBCLASSING,qc=XS.getterFor(Ao),TL=XS.set,Mr=ko&&ko.prototype,Ui=ko,Eo=Mr,ev=ui.TypeError,jc=ui.document,Gc=ui.process,Hc=JS.f,IL=Hc,EL=!!(jc&&jc.createEvent&&ui.dispatchEvent),tv="unhandledrejection",wL="rejectionhandled",zS=0,iv=1,xL=2,Yc=1,rv=2,wo,QS,sv,GS,av=function(s){var e;return hL(s)&&xo(e=s.then)?e:!1},nv=function(s,e){var t=e.value,i=e.state===iv,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,p;try{r?(i||(e.rejection===rv&&kL(e),e.rejection=Yc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),p=!0)),u===s.promise?n(new ev("Promise-chain cycle")):(l=av(u))?Br(l,u,a,n):a(u)):n(t)}catch(c){o&&!p&&o.exit(),n(c)}},ov=function(s,e){s.notified||(s.notified=!0,zc(function(){for(var t=s.reactions,i;i=t.get();)nv(i,s);s.notified=!1,e&&!s.rejection&&PL(s)}))},uv=function(s,e,t){var i,r;EL?(i=jc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),ui.dispatchEvent(i)):i={promise:e,reason:t},!vL&&(r=ui["on"+s])?r(i):s===tv&&bL("Unhandled promise rejection",t)},PL=function(s){Br(KS,ui,function(){var e=s.facade,t=s.value,i=YS(s),r;if(i&&(r=gL(function(){Po?Gc.emit("unhandledRejection",t,e):uv(tv,e,t)}),s.rejection=Po||YS(s)?rv:Yc,r.error))throw r.value})},YS=function(s){return s.rejection!==Yc&&!s.parent},kL=function(s){Br(KS,ui,function(){var e=s.facade;Po?Gc.emit("rejectionHandled",e):uv(wL,e,s.value)})},Lr=function(s,e,t){return function(i){s(e,i,t)}},Dr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=xL,ov(s,!0))},Wc=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new ev("Promise can't be resolved itself");var i=av(e);i?zc(function(){var r={done:!1};try{Br(i,e,Lr(Wc,r,s),Lr(Dr,r,s))}catch(a){Dr(r,a,s)}}):(s.value=e,s.state=iv,ov(s,!1))}catch(r){Dr({done:!1},r,s)}}};if(ZS&&(Ui=function(e){fL(this,Eo),pL(e),Br(wo,this);var t=qc(this);try{e(Lr(Wc,t),Lr(Dr,t))}catch(i){Dr(t,i)}},Eo=Ui.prototype,wo=function(e){TL(this,{type:Ao,done:!1,notified:!1,parent:!1,reactions:new SL,rejection:!1,state:zS,value:null})},wo.prototype=HS(Eo,"then",function(e,t){var i=qc(this),r=Hc(mL(this,Ui));return i.parent=!0,r.ok=xo(e)?e:!0,r.fail=xo(t)&&t,r.domain=Po?Gc.domain:void 0,i.state===zS?i.reactions.add(r):zc(function(){nv(r,i)}),r.promise}),QS=function(){var s=new wo,e=qc(s);this.promise=s,this.resolve=Lr(Wc,e),this.reject=Lr(Dr,e)},JS.f=Hc=function(s){return s===Ui||s===sv?new QS(s):IL(s)},!uL&&xo(ko)&&Mr!==Object.prototype)){GS=Mr.then,yL||HS(Mr,"then",function(e,t){var i=this;return new Ui(function(r,a){Br(GS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Mr.constructor}catch{}WS&&WS(Mr,Eo)}oL({global:!0,constructor:!0,wrap:!0,forced:ZS},{Promise:Ui});sv=lL.Promise;cL(Ui,Ao,!1,!0);dL(Ao)});var fv=b((dj,hv)=>{"use strict";var AL=Pe(),dv=AL("iterator"),pv=!1;try{cv=0,Kc={next:function(){return{done:!!cv++}},return:function(){pv=!0}},Kc[dv]=function(){return this},Array.from(Kc,function(){throw 2})}catch{}var cv,Kc;hv.exports=function(s,e){try{if(!e&&!pv)return!1}catch{return!1}var t=!1;try{var i={};i[dv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch{}return t}});var Xc=b((pj,mv)=>{"use strict";var RL=Fi(),$L=fv(),ML=Rr().CONSTRUCTOR;mv.exports=ML||!$L(function(s){RL.all(s).then(void 0,function(){})})});var bv=b(()=>{"use strict";var LL=ue(),DL=Ze(),BL=kt(),CL=$r(),VL=Io(),_L=bo(),OL=Xc();LL({target:"Promise",stat:!0,forced:OL},{all:function(e){var t=this,i=CL.f(t),r=i.resolve,a=i.reject,n=VL(function(){var o=BL(t.resolve),u=[],l=0,p=1;_L(e,function(c){var d=l++,h=!1;p++,DL(o,t,c).then(function(f){h||(h=!0,u[d]=f,--p||r(u))},a)}),--p||r(u)});return n.error&&a(n.value),i.promise}})});var Sv=b(()=>{"use strict";var NL=ue(),FL=gt(),UL=Rr().CONSTRUCTOR,Zc=Fi(),qL=_t(),jL=ae(),HL=Pr(),gv=Zc&&Zc.prototype;NL({target:"Promise",proto:!0,forced:UL,real:!0},{catch:function(s){return this.then(void 0,s)}});!FL&&jL(Zc)&&(Jc=qL("Promise").prototype.catch,gv.catch!==Jc&&HL(gv,"catch",Jc,{unsafe:!0}));var Jc});var vv=b(()=>{"use strict";var WL=ue(),zL=Ze(),QL=kt(),GL=$r(),YL=Io(),KL=bo(),XL=Xc();WL({target:"Promise",stat:!0,forced:XL},{race:function(e){var t=this,i=GL.f(t),r=i.reject,a=YL(function(){var n=QL(t.resolve);KL(e,function(o){zL(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var yv=b(()=>{"use strict";var JL=ue(),ZL=$r(),eD=Rr().CONSTRUCTOR;JL({target:"Promise",stat:!0,forced:eD},{reject:function(e){var t=ZL.f(this),i=t.reject;return i(e),t.promise}})});var ed=b((Tj,Tv)=>{"use strict";var tD=At(),iD=We(),rD=$r();Tv.exports=function(s,e){if(tD(s),iD(e)&&e.constructor===s)return e;var t=rD.f(s),i=t.resolve;return i(e),t.promise}});var wv=b(()=>{"use strict";var sD=ue(),aD=_t(),Iv=gt(),nD=Fi(),Ev=Rr().CONSTRUCTOR,oD=ed(),uD=aD("Promise"),lD=Iv&&!Ev;sD({target:"Promise",stat:!0,forced:Iv||Ev},{resolve:function(e){return oD(lD&&this===uD?nD:this,e)}})});var xv=b(()=>{"use strict";lv();bv();Sv();vv();yv();wv()});var Rv=b(()=>{"use strict";var cD=ue(),dD=gt(),Ro=Fi(),pD=ge(),kv=_t(),Av=ae(),hD=Ec(),Pv=ed(),fD=Pr(),id=Ro&&Ro.prototype,mD=!!Ro&&pD(function(){id.finally.call({then:function(){}},function(){})});cD({target:"Promise",proto:!0,real:!0,forced:mD},{finally:function(s){var e=hD(this,kv("Promise")),t=Av(s);return this.then(t?function(i){return Pv(e,s()).then(function(){return i})}:s,t?function(i){return Pv(e,s()).then(function(){throw i})}:s)}});!dD&&Av(Ro)&&(td=kv("Promise").prototype.finally,id.finally!==td&&fD(id,"finally",td,{unsafe:!0}));var td});var Mv=b((Aj,$v)=>{"use strict";Og();xv();Rv();var bD=si();$v.exports=bD("Promise","finally")});var Dv=b((Rj,Lv)=>{"use strict";var gD=Mv();Lv.exports=gD});var $o=b(($j,Bv)=>{"use strict";var SD=Dv();Bv.exports=SD});var Zv=b(()=>{"use strict";var QD=ue(),GD=br(),YD=Ir(),KD=Vs(),XD=_s();QD({target:"Array",proto:!0},{at:function(e){var t=GD(this),i=YD(t),r=KD(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});XD("at")});var ty=b((MH,ey)=>{"use strict";Zv();var JD=si();ey.exports=JD("Array","at")});var ry=b((LH,iy)=>{"use strict";var ZD=ty();iy.exports=ZD});var Ge=b((DH,sy)=>{"use strict";var eB=ry();sy.exports=eB});var Cd=b((GQ,Xy)=>{"use strict";var sC=Ri();Xy.exports=Array.isArray||function(e){return sC(e)==="Array"}});var Zy=b((YQ,Jy)=>{"use strict";var aC=TypeError,nC=9007199254740991;Jy.exports=function(s){if(s>nC)throw aC("Maximum allowed index exceeded");return s}});var iT=b((KQ,tT)=>{"use strict";var oC=Cd(),uC=Ir(),lC=Zy(),cC=Sr(),eT=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,p=n?cC(n,o):!1,c,d;l<i;)l in t&&(c=p?p(t[l],l,e):t[l],a>0&&oC(c)?(d=uC(c),u=eT(s,e,c,d,u,a-1)-1):(lC(u+1),s[u]=c),u++),l++;return u};tT.exports=eT});var nT=b((XQ,aT)=>{"use strict";var rT=Cd(),dC=Ic(),pC=We(),hC=Pe(),fC=hC("species"),sT=Array;aT.exports=function(s){var e;return rT(s)&&(e=s.constructor,dC(e)&&(e===sT||rT(e.prototype))?e=void 0:pC(e)&&(e=e[fC],e===null&&(e=void 0))),e===void 0?sT:e}});var uT=b((JQ,oT)=>{"use strict";var mC=nT();oT.exports=function(s,e){return new(mC(s))(e===0?0:e)}});var lT=b(()=>{"use strict";var bC=ue(),gC=iT(),SC=kt(),vC=br(),yC=Ir(),TC=uT();bC({target:"Array",proto:!0},{flatMap:function(e){var t=vC(this),i=yC(t),r;return SC(e),r=TC(t,0),r.length=gC(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var cT=b(()=>{"use strict";var IC=_s();IC("flatMap")});var pT=b((r2,dT)=>{"use strict";lT();cT();var EC=si();dT.exports=EC("Array","flatMap")});var fT=b((s2,hT)=>{"use strict";var wC=pT();hT.exports=wC});var Gi=b((a2,mT)=>{"use strict";var xC=fT();mT.exports=xC});var ma=b((I2,vT)=>{"use strict";var kC=js(),AC=String;vT.exports=function(s){if(kC(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return AC(s)}});var _d=b((E2,yT)=>{"use strict";yT.exports=`
7
- \v\f\r                 \u2028\u2029\uFEFF`});var ET=b((w2,IT)=>{"use strict";var RC=Se(),$C=ri(),MC=ma(),Nd=_d(),TT=RC("".replace),LC=RegExp("^["+Nd+"]+"),DC=RegExp("(^|[^"+Nd+"])["+Nd+"]+$"),Od=function(s){return function(e){var t=MC($C(e));return s&1&&(t=TT(t,LC,"")),s&2&&(t=TT(t,DC,"$1")),t}};IT.exports={start:Od(1),end:Od(2),trim:Od(3)}});var kT=b((x2,PT)=>{"use strict";var BC=ic().PROPER,CC=ge(),wT=_d(),xT="​…᠎";PT.exports=function(s){return CC(function(){return!!wT[s]()||xT[s]()!==xT||BC&&wT[s].name!==s})}});var Fd=b((P2,AT)=>{"use strict";var VC=ET().start,_C=kT();AT.exports=_C("trimStart")?function(){return VC(this)}:"".trimStart});var $T=b(()=>{"use strict";var OC=ue(),RT=Fd();OC({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==RT},{trimLeft:RT})});var LT=b(()=>{"use strict";$T();var NC=ue(),MT=Fd();NC({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==MT},{trimStart:MT})});var BT=b((M2,DT)=>{"use strict";LT();var FC=si();DT.exports=FC("String","trimLeft")});var VT=b((L2,CT)=>{"use strict";var UC=BT();CT.exports=UC});var OT=b((D2,_T)=>{"use strict";var qC=VT();_T.exports=qC});var qT=b(()=>{"use strict"});var jT=b(()=>{"use strict"});var WT=b((bG,HT)=>{"use strict";var zC=We(),QC=Ri(),GC=Pe(),YC=GC("match");HT.exports=function(s){var e;return zC(s)&&((e=s[YC])!==void 0?!!e:QC(s)==="RegExp")}});var GT=b((gG,QT)=>{"use strict";var KC=se(),XC=ge(),zT=KC.RegExp,JC=!XC(function(){var s=!0;try{zT(".","d")}catch{s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};s&&(a.hasIndices="d");for(var n in a)r(n,a[n]);var o=Object.getOwnPropertyDescriptor(zT.prototype,"flags").get.call(e);return o!==i||t!==i});QT.exports={correct:JC}});var KT=b((SG,YT)=>{"use strict";var ZC=At();YT.exports=function(){var s=ZC(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var ZT=b((vG,JT)=>{"use strict";var eV=Ze(),tV=St(),iV=$s(),XT=GT(),rV=KT(),sV=RegExp.prototype;JT.exports=XT.correct?function(s){return s.flags}:function(s){return!XT.correct&&iV(sV,s)&&!tV(s,"flags")?eV(rV,s):s.flags}});var tI=b((yG,eI)=>{"use strict";var Wd=Se(),aV=br(),nV=Math.floor,jd=Wd("".charAt),oV=Wd("".replace),Hd=Wd("".slice),uV=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,lV=/\$([$&'`]|\d{1,2})/g;eI.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=lV;return r!==void 0&&(r=aV(r),u=uV),oV(a,u,function(l,p){var c;switch(jd(p,0)){case"$":return"$";case"&":return s;case"`":return Hd(e,0,t);case"'":return Hd(e,n);case"<":c=r[Hd(p,1,-1)];break;default:var d=+p;if(d===0)return l;if(d>o){var h=nV(d/10);return h===0?l:h<=o?i[h-1]===void 0?jd(p,1):i[h-1]+jd(p,1):l}c=i[d-1]}return c===void 0?"":c})}});var sI=b(()=>{"use strict";var cV=ue(),dV=Ze(),Qd=Se(),iI=ri(),pV=ae(),hV=We(),fV=WT(),Xr=ma(),mV=Ls(),bV=ZT(),gV=tI(),SV=Pe(),vV=gt(),yV=SV("replace"),TV=TypeError,zd=Qd("".indexOf),IV=Qd("".replace),rI=Qd("".slice),EV=Math.max;cV({target:"String",proto:!0},{replaceAll:function(e,t){var i=iI(this),r,a,n,o,u,l,p,c,d,h,f=0,m="";if(hV(e)){if(r=fV(e),r&&(a=Xr(iI(bV(e))),!~zd(a,"g")))throw new TV("`.replaceAll` does not allow non-global regexes");if(n=mV(e,yV),n)return dV(n,e,i,t);if(vV&&r)return IV(Xr(i),e,t)}for(o=Xr(i),u=Xr(e),l=pV(t),l||(t=Xr(t)),p=u.length,c=EV(1,p),d=zd(o,u);d!==-1;)h=l?Xr(t(u,d,o)):gV(u,o,d,[],void 0,t),m+=rI(o,f,d)+h,f=d+p,d=d+c>o.length?-1:zd(o,u,d+c);return f<o.length&&(m+=rI(o,f)),m}})});var nI=b((EG,aI)=>{"use strict";qT();jT();sI();var wV=si();aI.exports=wV("String","replaceAll")});var uI=b((wG,oI)=>{"use strict";var xV=nI();oI.exports=xV});var cI=b((xG,lI)=>{"use strict";var PV=uI();lI.exports=PV});var pI=b((PG,dI)=>{"use strict";var kV=Vs(),AV=ma(),RV=ri(),$V=RangeError;dI.exports=function(e){var t=AV(RV(this)),i="",r=kV(e);if(r<0||r===1/0)throw new $V("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var gI=b((kG,bI)=>{"use strict";var mI=Se(),MV=Ll(),hI=ma(),LV=pI(),DV=ri(),BV=mI(LV),CV=mI("".slice),VV=Math.ceil,fI=function(s){return function(e,t,i){var r=hI(DV(e)),a=MV(t),n=r.length,o=i===void 0?" ":hI(i),u,l;return a<=n||o===""?r:(u=a-n,l=BV(o,VV(u/o.length)),l.length>u&&(l=CV(l,0,u)),s?r+l:l+r)}};bI.exports={start:fI(!1),end:fI(!0)}});var vI=b((AG,SI)=>{"use strict";var _V=Li();SI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(_V)});var yI=b(()=>{"use strict";var OV=ue(),NV=gI().start,FV=vI();OV({target:"String",proto:!0,forced:FV},{padStart:function(e){return NV(this,e,arguments.length>1?arguments[1]:void 0)}})});var II=b((MG,TI)=>{"use strict";yI();var UV=si();TI.exports=UV("String","padStart")});var wI=b((LG,EI)=>{"use strict";var qV=II();EI.exports=qV});var PI=b((DG,xI)=>{"use strict";var jV=wI();xI.exports=jV});var bh="2.0.149-dev.e6e86083.0";var xe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(xe||{}),Vt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(Vt||{});var xs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(xs||{}),el=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(el||{});var tl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(tl||{}),Un=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Un||{});var hh=D(Bi(),1),Hw=D(ke(),1);import{assertNever as Om,assertNonNullable as Yk,isNonNullable as Yn,ValueSubject as Ol,Subject as Kk,Subscription as Xk,merge as Jk,observableFrom as Zk,fromEvent as Bm,map as Cm,tap as Vm,filterChanged as eA,isNullable as Nl,ErrorCategory as _m}from"@vkontakte/videoplayer-shared";var Dm=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Kn=class{constructor(e){this.connection$=new Ol(void 0);this.castState$=new Ol("NOT_AVAILABLE");this.errorEvent$=new Kk;this.realCastState$=new Ol("NOT_AVAILABLE");this.subscription=new Xk;this.isDestroyed=!1;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=Yn(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||Dm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:_m.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Yn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Nl(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Nl(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(Bm(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Om(r.sessionState)}})).add(Jk(Bm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Vm(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),Cm(r=>r.castState)),Zk([i.getCastState()])).pipe(eA(),Cm(tA),Vm(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",n=Yn(this.connection$.getValue());if(a&&!n){let o=i.getCurrentSession();Yk(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(Nl(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Yn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:_m.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},tA=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Om(s)}};import{assertNonNullable as jl,combine as Hl,debounce as Wl,ErrorCategory as IA,filter as wr,filterChanged as Jm,isNonNullable as zl,isNullable as Zm,map as EA,Subscription as wA,ValueSubject as Ql}from"@vkontakte/videoplayer-shared";import{assertNever as iA,assertNonNullable as Ci,ErrorCategory as rA,getHighestQuality as sA,isNonNullable as Fm}from"@vkontakte/videoplayer-shared";import{assertNever as Nm}from"@vkontakte/videoplayer-shared";var ne=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Nm(t)}return s},ai=(s,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(s);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(s);return Number(t.searchParams.get("offset_p")??0)}default:Nm(e)}};var Jn=s=>{let{source:e,format:t,meta:i,output:r}=s,a,n,o;switch(t){case"MPEG":{let c=e[t];Ci(c);let d=sA(Object.keys(c));Ci(d);let h=c[d];Ci(h),a=h,n="video/mp4",o=Xn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=e[t];Ci(c),a=c.url,n="application/x-mpegurl",o=Xn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=e[t];Ci(c),a=c.url,n="application/dash+xml",o=Xn();break}case"DASH_LIVE_CMAF":{let c=e[t];Ci(c),a=c.url,n="application/dash+xml",o=Um();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=e[t];Ci(c),a=ne(c.url),n="application/x-mpegurl",o=Um();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:rA.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return iA(t)}let u=aA(i.videoId??a,n);u.contentUrl=a,u.streamType=o,u.metadata=nA();let{title:l,subtitle:p}=i;return Fm(l)&&(u.metadata.title=l),Fm(p)&&(u.metadata.subtitle=p),u};function Xn(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function Um(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function aA(s,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(s,e):{contentId:s,contentType:e,metadata:{title:"",subtitle:""},streamType:Xn()}}function nA(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var k=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var Zn=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as Xm}from"@vkontakte/videoplayer-shared";import{isBrowserWindow as vA,ValueSubject as yA}from"@vkontakte/videoplayer-shared";var qm=D(ke(),1);import{getWindow as oA}from"@vkontakte/videoplayer-shared";var eo=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,qm.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=oA().navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var jm=D(ke(),1);import{getWindow as uA,isBrowserWindow as lA}from"@vkontakte/videoplayer-shared";var Vi=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var to=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,jm.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||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.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Vi()}catch(t){console.error(t)}this.detectDevice(e),this.detectOS(e),this.detectDeviceDetails(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t,t.platform&&(this._os.name=this.normalizeOSName(t.platform),t.platformVersion&&(this._os.version=this.normalizeOSVersion(t.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),t.model&&(this._details.model=t.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error(t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]*( se)?)/i,["Windows Mobile",2]],[/(windows)[/ ](1[01]|2000|3\.1|7|8(\.1)?|9[58]|me|server 20\d\d( r2)?|vista|xp)/i,[1,2]],[/windows nt ?([\d.)]*)(?!.+xbox)/i,[2]],[/\bwin(?=3| ?9|n)(?:nt| 9x )?([\d.;]*)/i,[1]],[/(mac os x) ?([\w. ]*)/i,["macOS",2]],[/(macintosh|mac_powerpc\b)(?!.+(haiku|morphos))/i,["macOS"]],[/(?:ios;fbsv|ios(?=.+ip(?:ad|hone))|ip(?:ad|hone)(?: |.+i(?:pad)?)os)[/ ]([\w.]+)/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(android|harmonyos)[/ ]?([\d.]*)/i,[1,2]],[/(linux|ubuntu|debian|fedora|red hat|centos)[-/ ]?([\w.]*)/i,[1,2]],[/(cros) \w+(?:\)| ([\w.]+)\b)/i,["Chrome OS",2]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r[0],o=r[1],u=typeof n=="number"?a[n]:n,l=typeof o=="number"?a[o]:o;u.toLowerCase().includes("mac")?u="macOS":u.toLowerCase().includes("windows")?u="Windows":u.toLowerCase().includes("android")?u="Android":(u.toLowerCase().includes("ios")||u.toLowerCase().includes("iphone")||u.toLowerCase().includes("ipad"))&&(u="iOS"),l&&(l=l.replace(/_/g,".")),this._os={name:u,version:l||"Unknown",full:l?`${u} ${l}`:u};break}}this._os.name==="Unknown"&&(e.includes("Mac")?this._os={name:"macOS",version:"Unknown",full:"macOS"}:e.includes("Win")?this._os={name:"Windows",version:"Unknown",full:"Windows"}:e.includes("Linux")&&(this._os={name:"Linux",version:"Unknown",full:"Linux"}))}catch(t){console.error("OS detection error:",t)}}detectDeviceDetails(e){try{let t=[[/(ip(hone|od|ad))/i,["Apple",1]],[/(macintosh)/i,["Apple","Macintosh"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptx]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?[\d]+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/(?:huawei) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note|max|cc)?[_ ]?(?:\d{0,2}\w?)[_ ]?(?:plus|se|lite|pro)?( 5g|lte)?)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,["Xiaomi",1]],[/\b(?:xiao)?((?:red)?mi[-_ ]?pad[\w- ]*)(?: bui|\))/i,["Xiaomi",1]],[/(?:one)?(?:plus)? (a\d0\d\d)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((gm|hd)19|(ac|be|in|kb)20|(d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",1]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",1]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",1]],[/droid.+; (a?\d[0-2]{2}so|[c-g]\d{4}|so[-gl]\w+|xq-\w\w\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/(sonyericsson)[-_ ]?([-\w]*)/i,["Sony Ericsson",2]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",1]],[/(pixel (c|tablet))\b/i,["Google",1]],[/droid.+;(?: google)? (g(01[13]a|020[aem]|025[jn]|1b60|1f8f|2ybb|4s1m|576d|5nz6|8hhn|8vou|a02099|c15s|d1yq|e2ae|ec77|gh2x|kv4x|p4bc|pj41|r83y|tt9q|ur25|wvk6)|pixel[\d ]*a?( pro)?( xl)?( fold)?( \(5g\))?)( bui|\))/i,["Google",1]],[/(google) (pixelbook( go)?)/i,["Google",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))( bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i,["ASUS",1]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])( bui|;|\)|\/)/i,["Lenovo",1]],[/(kf[a-z]{2}wi|aeo(?!bc)\w\w)( bui|\))/i,["Amazon",1]],[/(kf[a-z]+)( bui|\)).+silk\//i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i,["Amazon",1]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(alcatel|geeksphone|nexian|panasonic)[-_ ]?([-\w]*)/i,[1,2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(dell) (streak)/i,["Dell",2]],[/(hp) ([\w ]+\w)/i,["HP",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(spice)[-_ ]?([-\w]*)/i,["Spice",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(shield \w+ tv)/i,["Nvidia",1]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*[)/]((?:dvp-)?[\d.]*)/i,["Roku",1]],[/(apple) ?tv/i,["Apple","TV"]],[/(amazon) ?tv/i,["Amazon","Fire TV"]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r[0],o=r[1],u=typeof n=="number"?a[n]:n,l=typeof o=="number"?a[o]:o;this._details.vendor=u,this._details.model=l||"Unknown";break}}}catch(t){console.error("Device details detection error:",t)}}detectIOSVersion(){try{let e=uA();if(!lA(e))return;if(this._highEntropyValues.platformVersion){let n=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),o=parseFloat(n);this._iosVersion=o;return}let{userAgent:t}=e.navigator,i=t.match(/OS (\d+(_\d+)?)/i);if(!i)return;let r=i[1].replace(/_/g,".");if(!r)return;let a=parseFloat(r);if(isNaN(a))return;this._iosVersion=a}catch(e){console.error(e)}}normalizeOSName(e){let t=e.toLowerCase();return t.includes("mac")?"macOS":t.includes("win")?"Windows":t.includes("linux")?"Linux":t.includes("android")?"Android":t.includes("ios")||t.includes("iphone")?"iOS":e}normalizeOSVersion(e){return e.replace(/_/g,".")}};import{getWindow as Hm,isBrowserWindow as cA}from"@vkontakte/videoplayer-shared";var io=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in Hm()}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(){let e=Hm();if(!cA(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r??0,this._isHdr=!!e.matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=i.colorDepth}catch(a){console.error(a)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(a){console.error(a)}}};import{getWindow as Fl,isBrowserWindow as zm}from"@vkontakte/videoplayer-shared";var _e=()=>window.ManagedMediaSource||window.MediaSource,ni=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Wm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Er=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var dA=Fl().document?.createElement("video"),pA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',hA='video/mp4; codecs="hev1.1.6.L93.B0"',Qm='video/webm; codecs="vp09.00.10.08"',Gm='video/webm; codecs="av01.0.00M.08"',fA='audio/mp4; codecs="mp4a.40.2"',mA='audio/webm; codecs="opus"',Ym,bA=async()=>{let s=Fl();if(!zm(s))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Gm}}),s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Qm}})]);Ym={DASH_WEBM_AV1:t,DASH_WEBM:i}};bA().catch(s=>{console.log(dA),console.error(s)});var ro=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 Ym}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=Fl();if(!zm(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:ni(),mse:Wm(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let i=!!_e()?.isTypeSupported?.(pA),r=!!_e()?.isTypeSupported?.(hA),a=!!_e()?.isTypeSupported?.(fA);this._codecs={h264:i,h265:r,vp9:!!_e()?.isTypeSupported?.(Qm),av1:!!_e()?.isTypeSupported?.(Gm),aac:a,opus:!!_e()?.isTypeSupported?.(mA),mpeg:(i||r)&&a},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(i){console.error(i)}try{this.destroyVideoElement()}catch(i){console.error("Error destroying video element:",i)}}destroyVideoElement(){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);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};import{getWindow as gA,isBrowserWindow as SA}from"@vkontakte/videoplayer-shared";var Km="audio/mpeg",so=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=gA();if(!SA(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Km)},this._codecs={mp3:!!_e()?.isTypeSupported?.(Km)}}catch(i){console.error(i)}try{this.destroyAudioElement()}catch(i){console.error("Error destroying audio element:",i)}}destroyAudioElement(){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);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};var Ul=class{constructor(){this.isInited$=new yA(!1);this._displayChecker=new io,this._deviceChecker=new to(this._displayChecker),this._browserChecker=new eo,this._videoChecker=new ro(this._deviceChecker,this._browserChecker),this._audioChecker=new so,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(){vA()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},$=new Ul;var ql=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=$.video,a=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return s.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&a;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&a||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&a;case"DASH_LIVE_CMAF":return n&&e.mp4&&a&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&a;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Xm(o)}})},Os=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Xm(s)}},TA=s=>{let t=Object.keys(s).filter(i=>!Os(i));return ql(t).length>0};var Ns=class{constructor(e){this.subscription=new wA;this.sessionId$=new Ql(null);this.mediaSessionId$=new Ql(null);this.contentId$=new Ql(null);this.isMobile=Vi();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if(Zm(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=e.media?.duration;zl(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(zl(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let n=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!n?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new Zn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Os(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:IA.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(wr(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(wr(zl),Jm(),Wl(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(Jm(),EA(Boolean));this.subscription.add(Hl({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(wr(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=Hl({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(wr(({mediaLoaded:r})=>r),Wl(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(wr(({mediaLoaded:r,playbackState:{from:a,to:n}})=>!r&&a==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(Hl({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(Wl(30)),mediaLoaded:t}).pipe(wr(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:a,volume:n}=r.to;this.setVolume(n,a)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=Jn(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=t??(i.state!=="none"?i.position/1e3:0),n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();jl(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();jl(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();jl(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":k(this.params.desiredState.playbackState,"paused");break;case"PLAYING":k(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),k(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):k(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if(Zm(e))return;let{level:t,muted:i}=e,r={muted:i??!1,volume:t??0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let a=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,a+=`, volume passed to state machine: ${r.volume}`),this.log({message:a}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as xA,ErrorCategory as Gl,filter as PA,Subject as kA,Subscription as Yl,tap as AA,ValueSubject as xr,fromEvent as Fs}from"@vkontakte/videoplayer-shared";var eb=s=>({castDevice:{friendlyName:s},remotePlayer:{},remotePlayerController:{},session:{}}),tb=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Us=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new xr(null);this.sessionId$=new xr(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new Yl;this.subscriptionEvents=new Yl;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new xr(!1);this.presentationConnection$=new xr(null);this.message$=new xr(null);this.friendlyName$=new xr(null);this.errorEvent$=new kA;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let a=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(Fs(r,"change").subscribe(()=>{a()})),a()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();xA(e,"connect with null presentationRequest");let t=await e.start();this.handleConnection(t)}catch(e){switch(e?.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:Gl.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(Fs(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe(AA(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),PA(e=>!!e)).subscribe(e=>{let t=Fs(e,"message").subscribe(a=>{let n=JSON.parse(a.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${a.data}`}),this.handleMessage(n),this.message$.next(n))}),i=Fs(e,"connect").subscribe(()=>{this.send("client_connect")}),r=Fs(e,"close").subscribe(a=>{switch(a.reason){case"error":this.errorEvent$.next({category:Gl.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:a});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();t?.state==="connected"&&t?.send(e)}catch(t){this.errorEvent$.next({category:Gl.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":e.message?.action==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||tb()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new Yl}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};import{ValueSubject as ib,Subject as RA,map as $A,Subscription as MA,combine as LA,filterChanged as rb,assertNonNullable as DA}from"@vkontakte/videoplayer-shared";var Ot=class s{constructor(e){this.subscription=new MA;this.connection$=new ib(void 0);this.castState$=new ib("NOT_AVAILABLE");this.errorEvent$=new RA;let t=s.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Us({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){DA(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=LA({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(rb())});this.subscription.add(e.pipe($A(({connection:t,friendlyName:i})=>!!(t&&i)),rb()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?eb(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){this.log({message:"connect"}),this.chromecastConnector?.connect()}disconnect(){this.log({message:"disconnect"}),this.chromecastConnector?.disconnect()}async stopMedia(){this.log({message:"stopMedia"}),this.chromecastConnector?.stopMedia()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:"destroy"}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}};var th=D(ke(),1),ih=D(oi(),1),Ew=D(gc(),1);var Fv=D($o(),1);import{isNonNullable as vD,Subject as Mo,merge as Cv}from"@vkontakte/videoplayer-shared";var O=class{constructor(e){this.transitionStarted$=new Mo;this.transitionEnded$=new Mo;this.transitionUpdated$=new Mo;this.forceChanged$=new Mo;this.stateChangeStarted$=Cv(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Cv(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||vD(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 ea,debounce as Vv,ErrorCategory as yD,fromEvent as qi,map as _v,merge as Ov,observableFrom as TD,Subject as ID,Subscription as rd,timeout as ED}from"@vkontakte/videoplayer-shared";var wD=5,xD=5,PD=500,Nv=7e3,ta=class{constructor(e){this.subscription=new rd;this.loadMediaTimeoutSubscription=new rd;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:ea(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:ea(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:ea(e)}break}default:ea(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Os(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});let t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);let e=new rd;this.subscription.add(e),this.subscription.add(Ov(this.videoState.stateChangeStarted$.pipe(_v(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(_v(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new ID;e.add(r.pipe(Vv(PD)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>wD)&&r.next(o),a=o})),e.add(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<xD&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:ea(n)}}),t(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Ov(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,TD(["init"])).pipe(Vv(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=Jn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),k(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&k(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(ED(Nv).subscribe(()=>a(`timeout(${Nv})`)))});(0,Fv.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:yD.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Id=D(ke(),1);import{clearVideoElement as qv,getWindow as AD}from"@vkontakte/videoplayer-shared";import{clearVideoElement as kD}from"@vkontakte/videoplayer-shared";var Uv=s=>{try{s.pause(),s.playbackRate=0,kD(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as RD,Subscription as $D}from"@vkontakte/videoplayer-shared";var sd=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)}},Lo=AD(),ad=Lo.WeakMap?new Lo.WeakMap:new sd,nd=Lo.WeakMap?new Lo.WeakMap:new Map,MD=(s,e=20)=>{let t=0;return RD(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Ae=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?qv(i):(i=document.createElement("video"),s.appendChild(i)),ad.set(i,r);let a=new $D;return a.add(MD(i,e)),nd.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Re=s=>{nd.get(s)?.unsubscribe(),nd.delete(s);let t=ad.get(s);ad.delete(s),t?qv(s):Uv(s)};var ud=D(Bi(),1);import{assertNonNullable as ra,isNonNullable as Rt,isNullable as BD,fromEvent as Cr,merge as jv,observableFrom as Hv,filterChanged as Wv,map as sa,Subject as zv,Subscription as CD,ValueSubject as VD,ErrorCategory as _D}from"@vkontakte/videoplayer-shared";import{isNonNullable as od,isNullable as LD,Subscription as DD}from"@vkontakte/videoplayer-shared";var Do=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=LD(r),l=new DD;return r&&l.add(r.subscribe(p=>{let c=s.getState();i(p,c)&&s.setState(p)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(p=>{t(p.to),u&&s.setState(p.to)},a)),l},ot=(s,e,t)=>Do(e,()=>s.loop,i=>{od(i)&&(s.loop=i)},{onError:t}),$e=(s,e,t,i)=>Do(e,()=>({muted:s.muted,volume:s.volume}),r=>{od(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),ze=(s,e,t,i)=>Do(e,()=>s.playbackRate,r=>{od(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),ia=Do;var OD=s=>["__",s.language,s.label].join("|"),ND=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},ld=class s{constructor(e){this.available$=new zv;this.current$=new VD(void 0);this.error$=new zv;this.subscription=new CD;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:_D.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ia(t.internalTextTracks,()=>(0,ud.default)(this.internalTracks),a=>{Rt(a)&&this.setInternal(a)},{equal:(a,n)=>Rt(a)&&Rt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(sa(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ia(t.externalTextTracks,()=>(0,ud.default)(this.externalTracks),a=>{Rt(a)&&this.setExternal(a)},{equal:(a,n)=>Rt(a)&&Rt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(sa(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ia(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(ia(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){ra(this.video);let{textTracks:e}=this.video;this.subscription.add(Cr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(jv(Cr(e,"addtrack"),Cr(e,"removetrack"),Hv(["init"])).pipe(sa(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Wv((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(jv(Cr(e,"change"),Hv(["init"])).pipe(sa(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),sa(i=>i&&this.htmlTextTrackToITextTrack(i).id),Wv()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Cr(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Cr(e,"removetrack").subscribe(i=>{i.track?.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;Rt(t.align)&&(r.align=t.align),Rt(t.position)&&(r.position=t.position),Rt(t.size)&&(r.size=t.size),Rt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ra(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:OD(e),a=this.externalTracks.has(r),n=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){ra(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(BD(e)||!ND(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){ra(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){ra(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Qe=ld;var ji=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 Qv=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},cd=s=>{let e=Qv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Gv=s=>{let e=Qv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as Oe,map as $t,merge as Bo,filterChanged as Kv,isNonNullable as Xv,Subject as UD,filter as dd,mapTo as pd,combine as qD,once as jD,shareReplay as Ne,throttle as HD,ErrorCategory as WD,ValueSubject as Jv,Subscription as zD}from"@vkontakte/videoplayer-shared";var FD=3,Yv=(s,e,t=FD)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var Me=s=>{let e=P=>Oe(s,P).pipe(pd(void 0),Ne(1)),t=new zD,i=()=>t.unsubscribe(),r=Bo(Oe(s,"progress"),Oe(s,"timeupdate")).pipe($t(()=>Yv(s.buffered,s.currentTime)),Ne(1)),a=$.browser.isSafari?qD({play:e("play").pipe(jD()),playing:e("playing")}).pipe(pd(void 0),Ne(1)):e("playing"),n=Oe(s,"volumechange").pipe($t(()=>({muted:s.muted,volume:s.volume})),Ne(1)),o=Oe(s,"ratechange").pipe($t(()=>s.playbackRate),Ne(1)),u=Oe(s,"error").pipe(dd(()=>!!(s.error||s.played.length)),$t(()=>{let P=s.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:WD.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:s.error??void 0}}),Ne(1)),l=Oe(s,"timeupdate").pipe($t(()=>s.currentTime),Ne(1)),p=["waiting","seeking","seeked","timeupdate"],c=new UD,d=.3,h;t.add(Bo(...p.map(P=>Oe(s,P))).subscribe(P=>{let F=s.currentTime;s.loop&&Xv(h)&&Xv(F)&&h>=s.duration-d&&F<=d&&c.next(h),h=F}));let f=e("pause").pipe(dd(()=>!s.error&&h!==s.duration),Ne(1)),m=Oe(s,"enterpictureinpicture").pipe(Ne(1)),S=Oe(s,"leavepictureinpicture").pipe(Ne(1)),g=new Jv(Gv(s));t.add(m.subscribe(()=>g.next(!0))),t.add(S.subscribe(()=>g.next(!1)));let v=new Jv(cd(s)),T=Oe(s,"fullscreenchange").pipe(Ne(1));t.add(T.pipe($t(()=>cd(s))).subscribe(v));let y=.1,x=1e3,A=Oe(s,"timeupdate").pipe($t(P=>s.duration-s.currentTime<y),Kv(),Ne(1)),R=Bo(A.pipe(dd(P=>!s.loop&&P)),Oe(s,"ended")).pipe(HD(x),pd(void 0),Ne(1)),B=Bo(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>Oe(s,P)),A.pipe($t(P=>({type:P?"ended":"unknown"})))).pipe($t(P=>$.browser.isFirefox&&P.type==="ended"?s.readyState<2:s.readyState<3),Kv(),Ne(1));return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:R,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$:Oe(s,"durationchange").pipe($t(()=>s.duration),Ne(1)),isBuffering$:B,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:S,destroy:i}};import{VideoQuality as li}from"@vkontakte/videoplayer-shared";var Mt=s=>{switch(s){case"mobile":return li.Q_144P;case"lowest":return li.Q_240P;case"low":return li.Q_360P;case"sd":case"medium":return li.Q_480P;case"hd":case"high":return li.Q_720P;case"fullhd":case"full":return li.Q_1080P;case"quadhd":case"quad":return li.Q_1440P;case"ultrahd":case"ultra":return li.Q_2160P}};var Ue=D(Ge(),1),fd=D(ke(),1),Wi=D(oi(),1);import{isNonNullable as K,isNullable as Oo,now as my,isHigher as No,isHigherOrEqual as Hi,isInvariantQuality as Fo,isLowerOrEqual as _r,videoSizeToQuality as by,assertNotEmptyArray as Uo,assertNonNullable as gy}from"@vkontakte/videoplayer-shared";var hd=!1,Ft={},ay=s=>{hd=s},ny=()=>{Ft={}},oy=s=>{s(Ft)},aa=(s,e)=>{hd&&(Ft.meta=Ft.meta??{},Ft.meta[s]=e)},Fe=class{constructor(e){this.name=e}next(e){if(!hd)return;Ft.series=Ft.series??{};let t=Ft.series[this.name]??[];t.push([Date.now(),e]),Ft.series[this.name]=t}};import{isHigher as tB,isHigherOrEqual as NH,isLower as uy,isLowerOrEqual as FH,isNonNullable as Co,isNullable as iB,videoHeightToQuality as Vo}from"@vkontakte/videoplayer-shared";function ly(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Vr(s,e,t){return iB(s)||Co(s.min)&&Co(s.max)&&uy(s.max,s.min)||Co(s.min)&&e&&tB(s.min,e)||Co(s.max)&&t&&uy(s.max,t)}function cy({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Vr({max:s?.max?Vo(s.max):void 0,min:s?.min?Vo(s.min):void 0},e?Vo(e):void 0,t?Vo(t):void 0)}var Sy=new Fe("best_bitrate"),qo=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Or=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Tt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=my()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},jo='Assertion "ABR Tracks is empty array" failed',_o=new WeakMap,dy=new WeakMap,py=new WeakMap,zi=(s,e,t,i)=>{let r=[...e].sort(Or(1)),a=[...t].sort(Or(1)),n=a.filter(u=>K(u.bitrate)&&K(s.bitrate)?s.bitrate/u.bitrate>i:!0),o=(0,Ue.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,Ue.default)(a,-1);return o&&(0,fd.default)(n,o)?o:n.length?(0,Ue.default)(n,-1):(0,Ue.default)(a,0)},Qi=(s,e,t,i)=>{let r=_o.get(e);r||(r=[...e].sort(Or(1)),_o.set(e,r));let a=_o.get(t);a||(a=[...t].sort(Or(1)),_o.set(t,a));let n=py.get(s);n||(n=a.filter(u=>K(u.bitrate)&&K(s.bitrate)?s.bitrate/u.bitrate>i:!0),py.set(s,n));let o=(0,Ue.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,Ue.default)(a,-1);return o&&(0,fd.default)(n,o)?o:n.length?(0,Ue.default)(n,-1):(0,Ue.default)(a,0)},hy=s=>"quality"in s,Ho=(s,e,t,i)=>{let r=K(i?.last?.bitrate)&&K(t?.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&my()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let n=i.last;i?.recordSwitch(n);let o=hy(n)?"video":"audio",u=hy(n)?n.quality:n.bitrate;return e({message:`
6
+ var Xw=Object.create;var gh=Object.defineProperty;var Jw=Object.getOwnPropertyDescriptor;var Zw=Object.getOwnPropertyNames;var ex=Object.getPrototypeOf,tx=Object.prototype.hasOwnProperty;var b=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports);var ix=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Zw(e))!tx.call(s,r)&&r!==t&&gh(s,r,{get:()=>e[r],enumerable:!(i=Jw(e,r))||i.enumerable});return s};var D=(s,e,t)=>(t=s!=null?Xw(ex(s)):{},ix(e||!s||!s.__esModule?gh(t,"default",{value:s,enumerable:!0}):t,s));var se=b((il,vh)=>{"use strict";var ks=function(s){return s&&s.Math===Math&&s};vh.exports=ks(typeof globalThis=="object"&&globalThis)||ks(typeof window=="object"&&window)||ks(typeof self=="object"&&self)||ks(typeof global=="object"&&global)||ks(typeof il=="object"&&il)||function(){return this}()||Function("return this")()});var ge=b((CN,yh)=>{"use strict";yh.exports=function(s){try{return!!s()}catch{return!0}}});var Ps=b((VN,Th)=>{"use strict";var rx=ge();Th.exports=!rx(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")})});var rl=b((_N,xh)=>{"use strict";var sx=Ps(),wh=Function.prototype,Ih=wh.apply,Eh=wh.call;xh.exports=typeof Reflect=="object"&&Reflect.apply||(sx?Eh.bind(Ih):function(){return Eh.apply(Ih,arguments)})});var Se=b((ON,Ah)=>{"use strict";var kh=Ps(),Ph=Function.prototype,sl=Ph.call,ax=kh&&Ph.bind.bind(sl,sl);Ah.exports=kh?ax:function(s){return function(){return sl.apply(s,arguments)}}});var Ri=b((NN,$h)=>{"use strict";var Rh=Se(),nx=Rh({}.toString),ox=Rh("".slice);$h.exports=function(s){return ox(nx(s),8,-1)}});var al=b((FN,Mh)=>{"use strict";var ux=Ri(),lx=Se();Mh.exports=function(s){if(ux(s)==="Function")return lx(s)}});var ae=b((UN,Lh)=>{"use strict";var nl=typeof document=="object"&&document.all;Lh.exports=typeof nl>"u"&&nl!==void 0?function(s){return typeof s=="function"||s===nl}:function(s){return typeof s=="function"}});var Je=b((qN,Dh)=>{"use strict";var cx=ge();Dh.exports=!cx(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ze=b((jN,Bh)=>{"use strict";var dx=Ps(),qn=Function.prototype.call;Bh.exports=dx?qn.bind(qn):function(){return qn.apply(qn,arguments)}});var ol=b(_h=>{"use strict";var Ch={}.propertyIsEnumerable,Vh=Object.getOwnPropertyDescriptor,px=Vh&&!Ch.call({1:2},1);_h.f=px?function(e){var t=Vh(this,e);return!!t&&t.enumerable}:Ch});var As=b((zN,Oh)=>{"use strict";Oh.exports=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}}});var Fh=b((WN,Nh)=>{"use strict";var hx=Se(),fx=ge(),mx=Ri(),ul=Object,bx=hx("".split);Nh.exports=fx(function(){return!ul("z").propertyIsEnumerable(0)})?function(s){return mx(s)==="String"?bx(s,""):ul(s)}:ul});var Rs=b((QN,Uh)=>{"use strict";Uh.exports=function(s){return s==null}});var ri=b((GN,qh)=>{"use strict";var gx=Rs(),Sx=TypeError;qh.exports=function(s){if(gx(s))throw new Sx("Can't call method on "+s);return s}});var $i=b((YN,jh)=>{"use strict";var vx=Fh(),yx=ri();jh.exports=function(s){return vx(yx(s))}});var ze=b((KN,Hh)=>{"use strict";var Tx=ae();Hh.exports=function(s){return typeof s=="object"?s!==null:Tx(s)}});var Mi=b((XN,zh)=>{"use strict";zh.exports={}});var _t=b((JN,Qh)=>{"use strict";var ll=Mi(),cl=se(),Ix=ae(),Wh=function(s){return Ix(s)?s:void 0};Qh.exports=function(s,e){return arguments.length<2?Wh(ll[s])||Wh(cl[s]):ll[s]&&ll[s][e]||cl[s]&&cl[s][e]}});var $s=b((ZN,Gh)=>{"use strict";var Ex=Se();Gh.exports=Ex({}.isPrototypeOf)});var Li=b((eF,Xh)=>{"use strict";var wx=se(),Yh=wx.navigator,Kh=Yh&&Yh.userAgent;Xh.exports=Kh?String(Kh):""});var pl=b((tF,sf)=>{"use strict";var rf=se(),dl=Li(),Jh=rf.process,Zh=rf.Deno,ef=Jh&&Jh.versions||Zh&&Zh.version,tf=ef&&ef.v8,bt,jn;tf&&(bt=tf.split("."),jn=bt[0]>0&&bt[0]<4?1:+(bt[0]+bt[1]));!jn&&dl&&(bt=dl.match(/Edge\/(\d+)/),(!bt||bt[1]>=74)&&(bt=dl.match(/Chrome\/(\d+)/),bt&&(jn=+bt[1])));sf.exports=jn});var hl=b((iF,nf)=>{"use strict";var af=pl(),xx=ge(),kx=se(),Px=kx.String;nf.exports=!!Object.getOwnPropertySymbols&&!xx(function(){var s=Symbol("symbol detection");return!Px(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&af&&af<41})});var fl=b((rF,of)=>{"use strict";var Ax=hl();of.exports=Ax&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ml=b((sF,uf)=>{"use strict";var Rx=_t(),$x=ae(),Mx=$s(),Lx=fl(),Dx=Object;uf.exports=Lx?function(s){return typeof s=="symbol"}:function(s){var e=Rx("Symbol");return $x(e)&&Mx(e.prototype,Dx(s))}});var Ms=b((aF,lf)=>{"use strict";var Bx=String;lf.exports=function(s){try{return Bx(s)}catch{return"Object"}}});var Pt=b((nF,cf)=>{"use strict";var Cx=ae(),Vx=Ms(),_x=TypeError;cf.exports=function(s){if(Cx(s))return s;throw new _x(Vx(s)+" is not a function")}});var Ls=b((oF,df)=>{"use strict";var Ox=Pt(),Nx=Rs();df.exports=function(s,e){var t=s[e];return Nx(t)?void 0:Ox(t)}});var hf=b((uF,pf)=>{"use strict";var bl=Ze(),gl=ae(),Sl=ze(),Fx=TypeError;pf.exports=function(s,e){var t,i;if(e==="string"&&gl(t=s.toString)&&!Sl(i=bl(t,s))||gl(t=s.valueOf)&&!Sl(i=bl(t,s))||e!=="string"&&gl(t=s.toString)&&!Sl(i=bl(t,s)))return i;throw new Fx("Can't convert object to primitive value")}});var gt=b((lF,ff)=>{"use strict";ff.exports=!0});var gf=b((cF,bf)=>{"use strict";var mf=se(),Ux=Object.defineProperty;bf.exports=function(s,e){try{Ux(mf,s,{value:e,configurable:!0,writable:!0})}catch{mf[s]=e}return e}});var Ds=b((dF,yf)=>{"use strict";var qx=gt(),jx=se(),Hx=gf(),Sf="__core-js_shared__",vf=yf.exports=jx[Sf]||Hx(Sf,{});(vf.versions||(vf.versions=[])).push({version:"3.43.0",mode:qx?"pure":"global",copyright:"© 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 vl=b((pF,If)=>{"use strict";var Tf=Ds();If.exports=function(s,e){return Tf[s]||(Tf[s]=e||{})}});var br=b((hF,Ef)=>{"use strict";var zx=ri(),Wx=Object;Ef.exports=function(s){return Wx(zx(s))}});var St=b((fF,wf)=>{"use strict";var Qx=Se(),Gx=br(),Yx=Qx({}.hasOwnProperty);wf.exports=Object.hasOwn||function(e,t){return Yx(Gx(e),t)}});var yl=b((mF,xf)=>{"use strict";var Kx=Se(),Xx=0,Jx=Math.random(),Zx=Kx(1.1.toString);xf.exports=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Zx(++Xx+Jx,36)}});var ke=b((bF,Pf)=>{"use strict";var ek=se(),tk=vl(),kf=St(),ik=yl(),rk=hl(),sk=fl(),gr=ek.Symbol,Tl=tk("wks"),ak=sk?gr.for||gr:gr&&gr.withoutSetter||ik;Pf.exports=function(s){return kf(Tl,s)||(Tl[s]=rk&&kf(gr,s)?gr[s]:ak("Symbol."+s)),Tl[s]}});var Mf=b((gF,$f)=>{"use strict";var nk=Ze(),Af=ze(),Rf=ml(),ok=Ls(),uk=hf(),lk=ke(),ck=TypeError,dk=lk("toPrimitive");$f.exports=function(s,e){if(!Af(s)||Rf(s))return s;var t=ok(s,dk),i;if(t){if(e===void 0&&(e="default"),i=nk(t,s,e),!Af(i)||Rf(i))return i;throw new ck("Can't convert object to primitive value")}return e===void 0&&(e="number"),uk(s,e)}});var Il=b((SF,Lf)=>{"use strict";var pk=Mf(),hk=ml();Lf.exports=function(s){var e=pk(s,"string");return hk(e)?e:e+""}});var Hn=b((vF,Bf)=>{"use strict";var fk=se(),Df=ze(),El=fk.document,mk=Df(El)&&Df(El.createElement);Bf.exports=function(s){return mk?El.createElement(s):{}}});var wl=b((yF,Cf)=>{"use strict";var bk=Je(),gk=ge(),Sk=Hn();Cf.exports=!bk&&!gk(function(){return Object.defineProperty(Sk("div"),"a",{get:function(){return 7}}).a!==7})});var Of=b(_f=>{"use strict";var vk=Je(),yk=Ze(),Tk=ol(),Ik=As(),Ek=$i(),wk=Il(),xk=St(),kk=wl(),Vf=Object.getOwnPropertyDescriptor;_f.f=vk?Vf:function(e,t){if(e=Ek(e),t=wk(t),kk)try{return Vf(e,t)}catch{}if(xk(e,t))return Ik(!yk(Tk.f,e,t),e[t])}});var xl=b((IF,Nf)=>{"use strict";var Pk=ge(),Ak=ae(),Rk=/#|\.prototype\./,Bs=function(s,e){var t=Mk[$k(s)];return t===Dk?!0:t===Lk?!1:Ak(e)?Pk(e):!!e},$k=Bs.normalize=function(s){return String(s).replace(Rk,".").toLowerCase()},Mk=Bs.data={},Lk=Bs.NATIVE="N",Dk=Bs.POLYFILL="P";Nf.exports=Bs});var Sr=b((EF,Uf)=>{"use strict";var Ff=al(),Bk=Pt(),Ck=Ps(),Vk=Ff(Ff.bind);Uf.exports=function(s,e){return Bk(s),e===void 0?s:Ck?Vk(s,e):function(){return s.apply(e,arguments)}}});var kl=b((wF,qf)=>{"use strict";var _k=Je(),Ok=ge();qf.exports=_k&&Ok(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var At=b((xF,jf)=>{"use strict";var Nk=ze(),Fk=String,Uk=TypeError;jf.exports=function(s){if(Nk(s))return s;throw new Uk(Fk(s)+" is not an object")}});var Di=b(zf=>{"use strict";var qk=Je(),jk=wl(),Hk=kl(),zn=At(),Hf=Il(),zk=TypeError,Pl=Object.defineProperty,Wk=Object.getOwnPropertyDescriptor,Al="enumerable",Rl="configurable",$l="writable";zf.f=qk?Hk?function(e,t,i){if(zn(e),t=Hf(t),zn(i),typeof e=="function"&&t==="prototype"&&"value"in i&&$l in i&&!i[$l]){var r=Wk(e,t);r&&r[$l]&&(e[t]=i.value,i={configurable:Rl in i?i[Rl]:r[Rl],enumerable:Al in i?i[Al]:r[Al],writable:!1})}return Pl(e,t,i)}:Pl:function(e,t,i){if(zn(e),t=Hf(t),zn(i),jk)try{return Pl(e,t,i)}catch{}if("get"in i||"set"in i)throw new zk("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var vr=b((PF,Wf)=>{"use strict";var Qk=Je(),Gk=Di(),Yk=As();Wf.exports=Qk?function(s,e,t){return Gk.f(s,e,Yk(1,t))}:function(s,e,t){return s[e]=t,s}});var ue=b((AF,Gf)=>{"use strict";var Cs=se(),Kk=rl(),Xk=al(),Jk=ae(),Zk=Of().f,eP=xl(),yr=Mi(),tP=Sr(),Tr=vr(),Qf=St();Ds();var iP=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Kk(s,this,arguments)};return e.prototype=s.prototype,e};Gf.exports=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Cs:r?Cs[t]:Cs[t]&&Cs[t].prototype,o=i?yr:yr[t]||Tr(yr,t,{})[t],u=o.prototype,l,p,c,d,h,f,m,S,g;for(d in e)l=eP(i?d:t+(r?".":"#")+d,s.forced),p=!l&&n&&Qf(n,d),f=o[d],p&&(s.dontCallGetSet?(g=Zk(n,d),m=g&&g.value):m=n[d]),h=p&&m?m:e[d],!(!l&&!a&&typeof f==typeof h)&&(s.bind&&p?S=tP(h,Cs):s.wrap&&p?S=iP(h):a&&Jk(h)?S=Xk(h):S=h,(s.sham||h&&h.sham||f&&f.sham)&&Tr(S,"sham",!0),Tr(o,d,S),a&&(c=t+"Prototype",Qf(yr,c)||Tr(yr,c,{}),Tr(yr[c],d,h),s.real&&u&&(l||!u[d])&&Tr(u,d,h)))}});var Wn=b((RF,Kf)=>{"use strict";var rP=vl(),sP=yl(),Yf=rP("keys");Kf.exports=function(s){return Yf[s]||(Yf[s]=sP(s))}});var Jf=b(($F,Xf)=>{"use strict";var aP=ge();Xf.exports=!aP(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype})});var Qn=b((MF,em)=>{"use strict";var nP=St(),oP=ae(),uP=br(),lP=Wn(),cP=Jf(),Zf=lP("IE_PROTO"),Ml=Object,dP=Ml.prototype;em.exports=cP?Ml.getPrototypeOf:function(s){var e=uP(s);if(nP(e,Zf))return e[Zf];var t=e.constructor;return oP(t)&&e instanceof t?t.prototype:e instanceof Ml?dP:null}});var im=b((LF,tm)=>{"use strict";var pP=Math.ceil,hP=Math.floor;tm.exports=Math.trunc||function(e){var t=+e;return(t>0?hP:pP)(t)}});var Vs=b((DF,rm)=>{"use strict";var fP=im();rm.exports=function(s){var e=+s;return e!==e||e===0?0:fP(e)}});var am=b((BF,sm)=>{"use strict";var mP=Vs(),bP=Math.max,gP=Math.min;sm.exports=function(s,e){var t=mP(s);return t<0?bP(t+e,0):gP(t,e)}});var Ll=b((CF,nm)=>{"use strict";var SP=Vs(),vP=Math.min;nm.exports=function(s){var e=SP(s);return e>0?vP(e,9007199254740991):0}});var Ir=b((VF,om)=>{"use strict";var yP=Ll();om.exports=function(s){return yP(s.length)}});var Dl=b((_F,lm)=>{"use strict";var TP=$i(),IP=am(),EP=Ir(),um=function(s){return function(e,t,i){var r=TP(e),a=EP(r);if(a===0)return!s&&-1;var n=IP(i,a),o;if(s&&t!==t){for(;a>n;)if(o=r[n++],o!==o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}};lm.exports={includes:um(!0),indexOf:um(!1)}});var Gn=b((OF,cm)=>{"use strict";cm.exports={}});var hm=b((NF,pm)=>{"use strict";var wP=Se(),Bl=St(),xP=$i(),kP=Dl().indexOf,PP=Gn(),dm=wP([].push);pm.exports=function(s,e){var t=xP(s),i=0,r=[],a;for(a in t)!Bl(PP,a)&&Bl(t,a)&&dm(r,a);for(;e.length>i;)Bl(t,a=e[i++])&&(~kP(r,a)||dm(r,a));return r}});var Cl=b((FF,fm)=>{"use strict";fm.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Vl=b((UF,mm)=>{"use strict";var AP=hm(),RP=Cl();mm.exports=Object.keys||function(e){return AP(e,RP)}});var _l=b((qF,ym)=>{"use strict";var gm=Je(),$P=ge(),Sm=Se(),MP=Qn(),LP=Vl(),DP=$i(),BP=ol().f,vm=Sm(BP),CP=Sm([].push),VP=gm&&$P(function(){var s=Object.create(null);return s[2]=2,!vm(s,2)}),bm=function(s){return function(e){for(var t=DP(e),i=LP(t),r=VP&&MP(t)===null,a=i.length,n=0,o=[],u;a>n;)u=i[n++],(!gm||(r?u in t:vm(t,u)))&&CP(o,s?[u,t[u]]:t[u]);return o}};ym.exports={entries:bm(!0),values:bm(!1)}});var Tm=b(()=>{"use strict";var _P=ue(),OP=_l().values;_P({target:"Object",stat:!0},{values:function(e){return OP(e)}})});var Em=b((zF,Im)=>{"use strict";Tm();var NP=Mi();Im.exports=NP.Object.values});var xm=b((WF,wm)=>{"use strict";var FP=Em();wm.exports=FP});var Bi=b((QF,km)=>{"use strict";var UP=xm();km.exports=UP});var _s=b((GF,Pm)=>{"use strict";Pm.exports=function(){}});var Am=b(()=>{"use strict";var qP=ue(),jP=Dl().includes,HP=ge(),zP=_s(),WP=HP(function(){return!Array(1).includes()});qP({target:"Array",proto:!0,forced:WP},{includes:function(e){return jP(this,e,arguments.length>1?arguments[1]:void 0)}});zP("includes")});var si=b((XF,Rm)=>{"use strict";var QP=_t();Rm.exports=QP});var Mm=b((JF,$m)=>{"use strict";Am();var GP=si();$m.exports=GP("Array","includes")});var Dm=b((ZF,Lm)=>{"use strict";var YP=Mm();Lm.exports=YP});var Pe=b((eU,Bm)=>{"use strict";var KP=Dm();Bm.exports=KP});var nb=b(()=>{"use strict";var BA=ue(),CA=_l().entries;BA({target:"Object",stat:!0},{entries:function(e){return CA(e)}})});var ub=b((e1,ob)=>{"use strict";nb();var VA=Mi();ob.exports=VA.Object.entries});var cb=b((t1,lb)=>{"use strict";var _A=ub();lb.exports=_A});var oi=b((i1,db)=>{"use strict";var OA=cb();db.exports=OA});var _i=b((r1,pb)=>{"use strict";pb.exports={}});var mb=b((s1,fb)=>{"use strict";var NA=se(),FA=ae(),hb=NA.WeakMap;fb.exports=FA(hb)&&/native code/.test(String(hb))});var tc=b((a1,Sb)=>{"use strict";var UA=mb(),gb=se(),qA=ze(),jA=vr(),Jl=St(),Zl=Ds(),HA=Wn(),zA=Gn(),bb="Object already initialized",ec=gb.TypeError,WA=gb.WeakMap,ao,qs,no,QA=function(s){return no(s)?qs(s):ao(s,{})},GA=function(s){return function(e){var t;if(!qA(e)||(t=qs(e)).type!==s)throw new ec("Incompatible receiver, "+s+" required");return t}};UA||Zl.state?(yt=Zl.state||(Zl.state=new WA),yt.get=yt.get,yt.has=yt.has,yt.set=yt.set,ao=function(s,e){if(yt.has(s))throw new ec(bb);return e.facade=s,yt.set(s,e),e},qs=function(s){return yt.get(s)||{}},no=function(s){return yt.has(s)}):(Oi=HA("state"),zA[Oi]=!0,ao=function(s,e){if(Jl(s,Oi))throw new ec(bb);return e.facade=s,jA(s,Oi,e),e},qs=function(s){return Jl(s,Oi)?s[Oi]:{}},no=function(s){return Jl(s,Oi)});var yt,Oi;Sb.exports={set:ao,get:qs,has:no,enforce:QA,getterFor:GA}});var sc=b((n1,yb)=>{"use strict";var ic=Je(),YA=St(),vb=Function.prototype,KA=ic&&Object.getOwnPropertyDescriptor,rc=YA(vb,"name"),XA=rc&&function(){}.name==="something",JA=rc&&(!ic||ic&&KA(vb,"name").configurable);yb.exports={EXISTS:rc,PROPER:XA,CONFIGURABLE:JA}});var Ib=b(Tb=>{"use strict";var ZA=Je(),eR=kl(),tR=Di(),iR=At(),rR=$i(),sR=Vl();Tb.f=ZA&&!eR?Object.defineProperties:function(e,t){iR(e);for(var i=rR(t),r=sR(t),a=r.length,n=0,o;a>n;)tR.f(e,o=r[n++],i[o]);return e}});var ac=b((u1,Eb)=>{"use strict";var aR=_t();Eb.exports=aR("document","documentElement")});var lc=b((l1,$b)=>{"use strict";var nR=At(),oR=Ib(),wb=Cl(),uR=Gn(),lR=ac(),cR=Hn(),dR=Wn(),xb=">",kb="<",oc="prototype",uc="script",Ab=dR("IE_PROTO"),nc=function(){},Rb=function(s){return kb+uc+xb+s+kb+"/"+uc+xb},Pb=function(s){s.write(Rb("")),s.close();var e=s.parentWindow.Object;return s=null,e},pR=function(){var s=cR("iframe"),e="java"+uc+":",t;return s.style.display="none",lR.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Rb("document.F=Object")),t.close(),t.F},oo,uo=function(){try{oo=new ActiveXObject("htmlfile")}catch{}uo=typeof document<"u"?document.domain&&oo?Pb(oo):pR():Pb(oo);for(var s=wb.length;s--;)delete uo[oc][wb[s]];return uo()};uR[Ab]=!0;$b.exports=Object.create||function(e,t){var i;return e!==null?(nc[oc]=nR(e),i=new nc,nc[oc]=null,i[Ab]=e):i=uo(),t===void 0?i:oR.f(i,t)}});var kr=b((c1,Mb)=>{"use strict";var hR=vr();Mb.exports=function(s,e,t,i){return i&&i.enumerable?s[e]=t:hR(s,e,t),s}});var hc=b((d1,Bb)=>{"use strict";var fR=ge(),mR=ae(),bR=ze(),gR=lc(),Lb=Qn(),SR=kr(),vR=ke(),yR=gt(),pc=vR("iterator"),Db=!1,Nt,cc,dc;[].keys&&(dc=[].keys(),"next"in dc?(cc=Lb(Lb(dc)),cc!==Object.prototype&&(Nt=cc)):Db=!0);var TR=!bR(Nt)||fR(function(){var s={};return Nt[pc].call(s)!==s});TR?Nt={}:yR&&(Nt=gR(Nt));mR(Nt[pc])||SR(Nt,pc,function(){return this});Bb.exports={IteratorPrototype:Nt,BUGGY_SAFARI_ITERATORS:Db}});var lo=b((p1,Vb)=>{"use strict";var IR=ke(),ER=IR("toStringTag"),Cb={};Cb[ER]="z";Vb.exports=String(Cb)==="[object z]"});var js=b((h1,_b)=>{"use strict";var wR=lo(),xR=ae(),co=Ri(),kR=ke(),PR=kR("toStringTag"),AR=Object,RR=co(function(){return arguments}())==="Arguments",$R=function(s,e){try{return s[e]}catch{}};_b.exports=wR?co:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=$R(e=AR(s),PR))=="string"?t:RR?co(e):(i=co(e))==="Object"&&xR(e.callee)?"Arguments":i}});var Nb=b((f1,Ob)=>{"use strict";var MR=lo(),LR=js();Ob.exports=MR?{}.toString:function(){return"[object "+LR(this)+"]"}});var Hs=b((m1,Ub)=>{"use strict";var DR=lo(),BR=Di().f,CR=vr(),VR=St(),_R=Nb(),OR=ke(),Fb=OR("toStringTag");Ub.exports=function(s,e,t,i){var r=t?s:s&&s.prototype;r&&(VR(r,Fb)||BR(r,Fb,{configurable:!0,value:e}),i&&!DR&&CR(r,"toString",_R))}});var jb=b((b1,qb)=>{"use strict";var NR=hc().IteratorPrototype,FR=lc(),UR=As(),qR=Hs(),jR=_i(),HR=function(){return this};qb.exports=function(s,e,t,i){var r=e+" Iterator";return s.prototype=FR(NR,{next:UR(+!i,t)}),qR(s,r,!1,!0),jR[r]=HR,s}});var zb=b((g1,Hb)=>{"use strict";var zR=Se(),WR=Pt();Hb.exports=function(s,e,t){try{return zR(WR(Object.getOwnPropertyDescriptor(s,e)[t]))}catch{}}});var Qb=b((S1,Wb)=>{"use strict";var QR=ze();Wb.exports=function(s){return QR(s)||s===null}});var Yb=b((v1,Gb)=>{"use strict";var GR=Qb(),YR=String,KR=TypeError;Gb.exports=function(s){if(GR(s))return s;throw new KR("Can't set "+YR(s)+" as a prototype")}});var fc=b((y1,Kb)=>{"use strict";var XR=zb(),JR=ze(),ZR=ri(),e$=Yb();Kb.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var s=!1,e={},t;try{t=XR(Object.prototype,"__proto__","set"),t(e,[]),s=e instanceof Array}catch{}return function(r,a){return ZR(r),e$(a),JR(r)&&(s?t(r,a):r.__proto__=a),r}}():void 0)});var og=b((T1,ng)=>{"use strict";var t$=ue(),i$=Ze(),po=gt(),sg=sc(),r$=ae(),s$=jb(),Xb=Qn(),Jb=fc(),a$=Hs(),n$=vr(),mc=kr(),o$=ke(),Zb=_i(),ag=hc(),u$=sg.PROPER,l$=sg.CONFIGURABLE,eg=ag.IteratorPrototype,ho=ag.BUGGY_SAFARI_ITERATORS,zs=o$("iterator"),tg="keys",Ws="values",ig="entries",rg=function(){return this};ng.exports=function(s,e,t,i,r,a,n){s$(t,e,i);var o=function(g){if(g===r&&d)return d;if(!ho&&g&&g in p)return p[g];switch(g){case tg:return function(){return new t(this,g)};case Ws:return function(){return new t(this,g)};case ig:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,p=s.prototype,c=p[zs]||p["@@iterator"]||r&&p[r],d=!ho&&c||o(r),h=e==="Array"&&p.entries||c,f,m,S;if(h&&(f=Xb(h.call(new s)),f!==Object.prototype&&f.next&&(!po&&Xb(f)!==eg&&(Jb?Jb(f,eg):r$(f[zs])||mc(f,zs,rg)),a$(f,u,!0,!0),po&&(Zb[u]=rg))),u$&&r===Ws&&c&&c.name!==Ws&&(!po&&l$?n$(p,"name",Ws):(l=!0,d=function(){return i$(c,this)})),r)if(m={values:o(Ws),keys:a?d:o(tg),entries:o(ig)},n)for(S in m)(ho||l||!(S in p))&&mc(p,S,m[S]);else t$({target:e,proto:!0,forced:ho||l},m);return(!po||n)&&p[zs]!==d&&mc(p,zs,d,{name:r}),Zb[e]=d,m}});var lg=b((I1,ug)=>{"use strict";ug.exports=function(s,e){return{value:s,done:e}}});var gc=b((E1,fg)=>{"use strict";var c$=$i(),bc=_s(),cg=_i(),pg=tc(),d$=Di().f,p$=og(),fo=lg(),h$=gt(),f$=Je(),hg="Array Iterator",m$=pg.set,b$=pg.getterFor(hg);fg.exports=p$(Array,"Array",function(s,e){m$(this,{type:hg,target:c$(s),index:0,kind:e})},function(){var s=b$(this),e=s.target,t=s.index++;if(!e||t>=e.length)return s.target=null,fo(void 0,!0);switch(s.kind){case"keys":return fo(t,!1);case"values":return fo(e[t],!1)}return fo([t,e[t]],!1)},"values");var dg=cg.Arguments=cg.Array;bc("keys");bc("values");bc("entries");if(!h$&&f$&&dg.name!=="values")try{d$(dg,"name",{value:"values"})}catch{}});var bg=b((w1,mg)=>{"use strict";var g$=ke(),S$=_i(),v$=g$("iterator"),y$=Array.prototype;mg.exports=function(s){return s!==void 0&&(S$.Array===s||y$[v$]===s)}});var Sc=b((x1,Sg)=>{"use strict";var T$=js(),gg=Ls(),I$=Rs(),E$=_i(),w$=ke(),x$=w$("iterator");Sg.exports=function(s){if(!I$(s))return gg(s,x$)||gg(s,"@@iterator")||E$[T$(s)]}});var yg=b((k1,vg)=>{"use strict";var k$=Ze(),P$=Pt(),A$=At(),R$=Ms(),$$=Sc(),M$=TypeError;vg.exports=function(s,e){var t=arguments.length<2?$$(s):e;if(P$(t))return A$(k$(t,s));throw new M$(R$(s)+" is not iterable")}});var Eg=b((P1,Ig)=>{"use strict";var L$=Ze(),Tg=At(),D$=Ls();Ig.exports=function(s,e,t){var i,r;Tg(s);try{if(i=D$(s,"return"),!i){if(e==="throw")throw t;return t}i=L$(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Tg(i),t}});var bo=b((A1,Pg)=>{"use strict";var B$=Sr(),C$=Ze(),V$=At(),_$=Ms(),O$=bg(),N$=Ir(),wg=$s(),F$=yg(),U$=Sc(),xg=Eg(),q$=TypeError,mo=function(s,e){this.stopped=s,this.result=e},kg=mo.prototype;Pg.exports=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=B$(e,i),l,p,c,d,h,f,m,S=function(v){return l&&xg(l,"normal"),new mo(!0,v)},g=function(v){return r?(V$(v),o?u(v[0],v[1],S):u(v[0],v[1])):o?u(v,S):u(v)};if(a)l=s.iterator;else if(n)l=s;else{if(p=U$(s),!p)throw new q$(_$(s)+" is not iterable");if(O$(p)){for(c=0,d=N$(s);d>c;c++)if(h=g(s[c]),h&&wg(kg,h))return h;return new mo(!1)}l=F$(s,p)}for(f=a?s.next:l.next;!(m=C$(f,l)).done;){try{h=g(m.value)}catch(v){xg(l,"throw",v)}if(typeof h=="object"&&h&&wg(kg,h))return h}return new mo(!1)}});var Rg=b((R1,Ag)=>{"use strict";var j$=Je(),H$=Di(),z$=As();Ag.exports=function(s,e,t){j$?H$.f(s,e,z$(0,t)):s[e]=t}});var $g=b(()=>{"use strict";var W$=ue(),Q$=bo(),G$=Rg();W$({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Q$(e,function(i,r){G$(t,i,r)},{AS_ENTRIES:!0}),t}})});var Lg=b((L1,Mg)=>{"use strict";gc();$g();var Y$=Mi();Mg.exports=Y$.Object.fromEntries});var Bg=b((D1,Dg)=>{"use strict";Dg.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}});var Vg=b(()=>{"use strict";gc();var K$=Bg(),X$=se(),J$=Hs(),Cg=_i();for(go in K$)J$(X$[go],go),Cg[go]=Cg.Array;var go});var Og=b((V1,_g)=>{"use strict";var Z$=Lg();Vg();_g.exports=Z$});var vc=b((_1,Ng)=>{"use strict";var eM=Og();Ng.exports=eM});var Fg=b(()=>{"use strict"});var yc=b((F1,Ug)=>{"use strict";var Qs=se(),tM=Li(),iM=Ri(),So=function(s){return tM.slice(0,s.length)===s};Ug.exports=function(){return So("Bun/")?"BUN":So("Cloudflare-Workers")?"CLOUDFLARE":So("Deno/")?"DENO":So("Node.js/")?"NODE":Qs.Bun&&typeof Bun.version=="string"?"BUN":Qs.Deno&&typeof Deno.version=="object"?"DENO":iM(Qs.process)==="process"?"NODE":Qs.window&&Qs.document?"BROWSER":"REST"}()});var vo=b((U1,qg)=>{"use strict";var rM=yc();qg.exports=rM==="NODE"});var Hg=b((q1,jg)=>{"use strict";var sM=Di();jg.exports=function(s,e,t){return sM.f(s,e,t)}});var Qg=b((j1,Wg)=>{"use strict";var aM=_t(),nM=Hg(),oM=ke(),uM=Je(),zg=oM("species");Wg.exports=function(s){var e=aM(s);uM&&e&&!e[zg]&&nM(e,zg,{configurable:!0,get:function(){return this}})}});var Yg=b((H1,Gg)=>{"use strict";var lM=$s(),cM=TypeError;Gg.exports=function(s,e){if(lM(e,s))return s;throw new cM("Incorrect invocation")}});var Ic=b((z1,Kg)=>{"use strict";var dM=Se(),pM=ae(),Tc=Ds(),hM=dM(Function.toString);pM(Tc.inspectSource)||(Tc.inspectSource=function(s){return hM(s)});Kg.exports=Tc.inspectSource});var wc=b((W1,tS)=>{"use strict";var fM=Se(),mM=ge(),Xg=ae(),bM=js(),gM=_t(),SM=Ic(),Jg=function(){},Zg=gM("Reflect","construct"),Ec=/^\s*(?:class|function)\b/,vM=fM(Ec.exec),yM=!Ec.test(Jg),Gs=function(e){if(!Xg(e))return!1;try{return Zg(Jg,[],e),!0}catch{return!1}},eS=function(e){if(!Xg(e))return!1;switch(bM(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return yM||!!vM(Ec,SM(e))}catch{return!0}};eS.sham=!0;tS.exports=!Zg||mM(function(){var s;return Gs(Gs.call)||!Gs(Object)||!Gs(function(){s=!0})||s})?eS:Gs});var rS=b((Q1,iS)=>{"use strict";var TM=wc(),IM=Ms(),EM=TypeError;iS.exports=function(s){if(TM(s))return s;throw new EM(IM(s)+" is not a constructor")}});var xc=b((G1,aS)=>{"use strict";var sS=At(),wM=rS(),xM=Rs(),kM=ke(),PM=kM("species");aS.exports=function(s,e){var t=sS(s).constructor,i;return t===void 0||xM(i=sS(t)[PM])?e:wM(i)}});var oS=b((Y1,nS)=>{"use strict";var AM=Se();nS.exports=AM([].slice)});var lS=b((K1,uS)=>{"use strict";var RM=TypeError;uS.exports=function(s,e){if(s<e)throw new RM("Not enough arguments");return s}});var kc=b((X1,cS)=>{"use strict";var $M=Li();cS.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test($M)});var Cc=b((J1,vS)=>{"use strict";var et=se(),MM=rl(),LM=Sr(),dS=ae(),DM=St(),SS=ge(),pS=ac(),BM=oS(),hS=Hn(),CM=lS(),VM=kc(),_M=vo(),Lc=et.setImmediate,Dc=et.clearImmediate,OM=et.process,Pc=et.Dispatch,NM=et.Function,fS=et.MessageChannel,FM=et.String,Ac=0,Ys={},mS="onreadystatechange",Ks,Ni,Rc,$c;SS(function(){Ks=et.location});var Bc=function(s){if(DM(Ys,s)){var e=Ys[s];delete Ys[s],e()}},Mc=function(s){return function(){Bc(s)}},bS=function(s){Bc(s.data)},gS=function(s){et.postMessage(FM(s),Ks.protocol+"//"+Ks.host)};(!Lc||!Dc)&&(Lc=function(e){CM(arguments.length,1);var t=dS(e)?e:NM(e),i=BM(arguments,1);return Ys[++Ac]=function(){MM(t,void 0,i)},Ni(Ac),Ac},Dc=function(e){delete Ys[e]},_M?Ni=function(s){OM.nextTick(Mc(s))}:Pc&&Pc.now?Ni=function(s){Pc.now(Mc(s))}:fS&&!VM?(Rc=new fS,$c=Rc.port2,Rc.port1.onmessage=bS,Ni=LM($c.postMessage,$c)):et.addEventListener&&dS(et.postMessage)&&!et.importScripts&&Ks&&Ks.protocol!=="file:"&&!SS(gS)?(Ni=gS,et.addEventListener("message",bS,!1)):mS in hS("script")?Ni=function(s){pS.appendChild(hS("script"))[mS]=function(){pS.removeChild(this),Bc(s)}}:Ni=function(s){setTimeout(Mc(s),0)});vS.exports={set:Lc,clear:Dc}});var IS=b((Z1,TS)=>{"use strict";var yS=se(),UM=Je(),qM=Object.getOwnPropertyDescriptor;TS.exports=function(s){if(!UM)return yS[s];var e=qM(yS,s);return e&&e.value}});var Vc=b((ej,wS)=>{"use strict";var ES=function(){this.head=null,this.tail=null};ES.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};wS.exports=ES});var kS=b((tj,xS)=>{"use strict";var jM=Li();xS.exports=/ipad|iphone|ipod/i.test(jM)&&typeof Pebble<"u"});var AS=b((ij,PS)=>{"use strict";var HM=Li();PS.exports=/web0s(?!.*chrome)/i.test(HM)});var CS=b((rj,BS)=>{"use strict";var Ar=se(),zM=IS(),RS=Sr(),_c=Cc().set,WM=Vc(),QM=kc(),GM=kS(),YM=AS(),Oc=vo(),$S=Ar.MutationObserver||Ar.WebKitMutationObserver,MS=Ar.document,LS=Ar.process,yo=Ar.Promise,Uc=zM("queueMicrotask"),Pr,Nc,Fc,To,DS;Uc||(Xs=new WM,Js=function(){var s,e;for(Oc&&(s=LS.domain)&&s.exit();e=Xs.get();)try{e()}catch(t){throw Xs.head&&Pr(),t}s&&s.enter()},!QM&&!Oc&&!YM&&$S&&MS?(Nc=!0,Fc=MS.createTextNode(""),new $S(Js).observe(Fc,{characterData:!0}),Pr=function(){Fc.data=Nc=!Nc}):!GM&&yo&&yo.resolve?(To=yo.resolve(void 0),To.constructor=yo,DS=RS(To.then,To),Pr=function(){DS(Js)}):Oc?Pr=function(){LS.nextTick(Js)}:(_c=RS(_c,Ar),Pr=function(){_c(Js)}),Uc=function(s){Xs.head||Pr(),Xs.add(s)});var Xs,Js;BS.exports=Uc});var _S=b((sj,VS)=>{"use strict";VS.exports=function(s,e){try{arguments.length===1?console.error(s):console.error(s,e)}catch{}}});var Io=b((aj,OS)=>{"use strict";OS.exports=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}}});var Fi=b((nj,NS)=>{"use strict";var KM=se();NS.exports=KM.Promise});var Rr=b((oj,jS)=>{"use strict";var XM=se(),Zs=Fi(),JM=ae(),ZM=xl(),eL=Ic(),tL=ke(),FS=yc(),iL=gt(),qc=pl(),US=Zs&&Zs.prototype,rL=tL("species"),jc=!1,qS=JM(XM.PromiseRejectionEvent),sL=ZM("Promise",function(){var s=eL(Zs),e=s!==String(Zs);if(!e&&qc===66||iL&&!(US.catch&&US.finally))return!0;if(!qc||qc<51||!/native code/.test(s)){var t=new Zs(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[rL]=i,jc=t.then(function(){})instanceof i,!jc)return!0}return!e&&(FS==="BROWSER"||FS==="DENO")&&!qS});jS.exports={CONSTRUCTOR:sL,REJECTION_EVENT:qS,SUBCLASSING:jc}});var $r=b((uj,zS)=>{"use strict";var HS=Pt(),aL=TypeError,nL=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw new aL("Bad Promise constructor");e=i,t=r}),this.resolve=HS(e),this.reject=HS(t)};zS.exports.f=function(s){return new nL(s)}});var dv=b(()=>{"use strict";var oL=ue(),uL=gt(),ko=vo(),ui=se(),lL=Mi(),Br=Ze(),WS=kr(),QS=fc(),cL=Hs(),dL=Qg(),pL=Pt(),xo=ae(),hL=ze(),fL=Yg(),mL=xc(),JS=Cc().set,Gc=CS(),bL=_S(),gL=Io(),SL=Vc(),ZS=tc(),Po=Fi(),Yc=Rr(),ev=$r(),Ao="Promise",tv=Yc.CONSTRUCTOR,vL=Yc.REJECTION_EVENT,yL=Yc.SUBCLASSING,Hc=ZS.getterFor(Ao),TL=ZS.set,Mr=Po&&Po.prototype,Ui=Po,Eo=Mr,iv=ui.TypeError,zc=ui.document,Kc=ui.process,Wc=ev.f,IL=Wc,EL=!!(zc&&zc.createEvent&&ui.dispatchEvent),rv="unhandledrejection",wL="rejectionhandled",GS=0,sv=1,xL=2,Xc=1,av=2,wo,YS,nv,KS,ov=function(s){var e;return hL(s)&&xo(e=s.then)?e:!1},uv=function(s,e){var t=e.value,i=e.state===sv,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,l,p;try{r?(i||(e.rejection===av&&PL(e),e.rejection=Xc),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),p=!0)),u===s.promise?n(new iv("Promise-chain cycle")):(l=ov(u))?Br(l,u,a,n):a(u)):n(t)}catch(c){o&&!p&&o.exit(),n(c)}},lv=function(s,e){s.notified||(s.notified=!0,Gc(function(){for(var t=s.reactions,i;i=t.get();)uv(i,s);s.notified=!1,e&&!s.rejection&&kL(s)}))},cv=function(s,e,t){var i,r;EL?(i=zc.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),ui.dispatchEvent(i)):i={promise:e,reason:t},!vL&&(r=ui["on"+s])?r(i):s===rv&&bL("Unhandled promise rejection",t)},kL=function(s){Br(JS,ui,function(){var e=s.facade,t=s.value,i=XS(s),r;if(i&&(r=gL(function(){ko?Kc.emit("unhandledRejection",t,e):cv(rv,e,t)}),s.rejection=ko||XS(s)?av:Xc,r.error))throw r.value})},XS=function(s){return s.rejection!==Xc&&!s.parent},PL=function(s){Br(JS,ui,function(){var e=s.facade;ko?Kc.emit("rejectionHandled",e):cv(wL,e,s.value)})},Lr=function(s,e,t){return function(i){s(e,i,t)}},Dr=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=xL,lv(s,!0))},Qc=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw new iv("Promise can't be resolved itself");var i=ov(e);i?Gc(function(){var r={done:!1};try{Br(i,e,Lr(Qc,r,s),Lr(Dr,r,s))}catch(a){Dr(r,a,s)}}):(s.value=e,s.state=sv,lv(s,!1))}catch(r){Dr({done:!1},r,s)}}};if(tv&&(Ui=function(e){fL(this,Eo),pL(e),Br(wo,this);var t=Hc(this);try{e(Lr(Qc,t),Lr(Dr,t))}catch(i){Dr(t,i)}},Eo=Ui.prototype,wo=function(e){TL(this,{type:Ao,done:!1,notified:!1,parent:!1,reactions:new SL,rejection:!1,state:GS,value:null})},wo.prototype=WS(Eo,"then",function(e,t){var i=Hc(this),r=Wc(mL(this,Ui));return i.parent=!0,r.ok=xo(e)?e:!0,r.fail=xo(t)&&t,r.domain=ko?Kc.domain:void 0,i.state===GS?i.reactions.add(r):Gc(function(){uv(r,i)}),r.promise}),YS=function(){var s=new wo,e=Hc(s);this.promise=s,this.resolve=Lr(Qc,e),this.reject=Lr(Dr,e)},ev.f=Wc=function(s){return s===Ui||s===nv?new YS(s):IL(s)},!uL&&xo(Po)&&Mr!==Object.prototype)){KS=Mr.then,yL||WS(Mr,"then",function(e,t){var i=this;return new Ui(function(r,a){Br(KS,i,r,a)}).then(e,t)},{unsafe:!0});try{delete Mr.constructor}catch{}QS&&QS(Mr,Eo)}oL({global:!0,constructor:!0,wrap:!0,forced:tv},{Promise:Ui});nv=lL.Promise;cL(Ui,Ao,!1,!0);dL(Ao)});var bv=b((dj,mv)=>{"use strict";var AL=ke(),hv=AL("iterator"),fv=!1;try{pv=0,Jc={next:function(){return{done:!!pv++}},return:function(){fv=!0}},Jc[hv]=function(){return this},Array.from(Jc,function(){throw 2})}catch{}var pv,Jc;mv.exports=function(s,e){try{if(!e&&!fv)return!1}catch{return!1}var t=!1;try{var i={};i[hv]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch{}return t}});var Zc=b((pj,gv)=>{"use strict";var RL=Fi(),$L=bv(),ML=Rr().CONSTRUCTOR;gv.exports=ML||!$L(function(s){RL.all(s).then(void 0,function(){})})});var Sv=b(()=>{"use strict";var LL=ue(),DL=Ze(),BL=Pt(),CL=$r(),VL=Io(),_L=bo(),OL=Zc();LL({target:"Promise",stat:!0,forced:OL},{all:function(e){var t=this,i=CL.f(t),r=i.resolve,a=i.reject,n=VL(function(){var o=BL(t.resolve),u=[],l=0,p=1;_L(e,function(c){var d=l++,h=!1;p++,DL(o,t,c).then(function(f){h||(h=!0,u[d]=f,--p||r(u))},a)}),--p||r(u)});return n.error&&a(n.value),i.promise}})});var yv=b(()=>{"use strict";var NL=ue(),FL=gt(),UL=Rr().CONSTRUCTOR,td=Fi(),qL=_t(),jL=ae(),HL=kr(),vv=td&&td.prototype;NL({target:"Promise",proto:!0,forced:UL,real:!0},{catch:function(s){return this.then(void 0,s)}});!FL&&jL(td)&&(ed=qL("Promise").prototype.catch,vv.catch!==ed&&HL(vv,"catch",ed,{unsafe:!0}));var ed});var Tv=b(()=>{"use strict";var zL=ue(),WL=Ze(),QL=Pt(),GL=$r(),YL=Io(),KL=bo(),XL=Zc();zL({target:"Promise",stat:!0,forced:XL},{race:function(e){var t=this,i=GL.f(t),r=i.reject,a=YL(function(){var n=QL(t.resolve);KL(e,function(o){WL(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}})});var Iv=b(()=>{"use strict";var JL=ue(),ZL=$r(),eD=Rr().CONSTRUCTOR;JL({target:"Promise",stat:!0,forced:eD},{reject:function(e){var t=ZL.f(this),i=t.reject;return i(e),t.promise}})});var id=b((Tj,Ev)=>{"use strict";var tD=At(),iD=ze(),rD=$r();Ev.exports=function(s,e){if(tD(s),iD(e)&&e.constructor===s)return e;var t=rD.f(s),i=t.resolve;return i(e),t.promise}});var kv=b(()=>{"use strict";var sD=ue(),aD=_t(),wv=gt(),nD=Fi(),xv=Rr().CONSTRUCTOR,oD=id(),uD=aD("Promise"),lD=wv&&!xv;sD({target:"Promise",stat:!0,forced:wv||xv},{resolve:function(e){return oD(lD&&this===uD?nD:this,e)}})});var Pv=b(()=>{"use strict";dv();Sv();yv();Tv();Iv();kv()});var Mv=b(()=>{"use strict";var cD=ue(),dD=gt(),Ro=Fi(),pD=ge(),Rv=_t(),$v=ae(),hD=xc(),Av=id(),fD=kr(),sd=Ro&&Ro.prototype,mD=!!Ro&&pD(function(){sd.finally.call({then:function(){}},function(){})});cD({target:"Promise",proto:!0,real:!0,forced:mD},{finally:function(s){var e=hD(this,Rv("Promise")),t=$v(s);return this.then(t?function(i){return Av(e,s()).then(function(){return i})}:s,t?function(i){return Av(e,s()).then(function(){throw i})}:s)}});!dD&&$v(Ro)&&(rd=Rv("Promise").prototype.finally,sd.finally!==rd&&fD(sd,"finally",rd,{unsafe:!0}));var rd});var Dv=b((Aj,Lv)=>{"use strict";Fg();Pv();Mv();var bD=si();Lv.exports=bD("Promise","finally")});var Cv=b((Rj,Bv)=>{"use strict";var gD=Dv();Bv.exports=gD});var $o=b(($j,Vv)=>{"use strict";var SD=Cv();Vv.exports=SD});var ty=b(()=>{"use strict";var QD=ue(),GD=br(),YD=Ir(),KD=Vs(),XD=_s();QD({target:"Array",proto:!0},{at:function(e){var t=GD(this),i=YD(t),r=KD(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});XD("at")});var ry=b((MH,iy)=>{"use strict";ty();var JD=si();iy.exports=JD("Array","at")});var ay=b((LH,sy)=>{"use strict";var ZD=ry();sy.exports=ZD});var Ge=b((DH,ny)=>{"use strict";var eB=ay();ny.exports=eB});var _d=b((GQ,Zy)=>{"use strict";var sC=Ri();Zy.exports=Array.isArray||function(e){return sC(e)==="Array"}});var tT=b((YQ,eT)=>{"use strict";var aC=TypeError,nC=9007199254740991;eT.exports=function(s){if(s>nC)throw aC("Maximum allowed index exceeded");return s}});var sT=b((KQ,rT)=>{"use strict";var oC=_d(),uC=Ir(),lC=tT(),cC=Sr(),iT=function(s,e,t,i,r,a,n,o){for(var u=r,l=0,p=n?cC(n,o):!1,c,d;l<i;)l in t&&(c=p?p(t[l],l,e):t[l],a>0&&oC(c)?(d=uC(c),u=iT(s,e,c,d,u,a-1)-1):(lC(u+1),s[u]=c),u++),l++;return u};rT.exports=iT});var uT=b((XQ,oT)=>{"use strict";var aT=_d(),dC=wc(),pC=ze(),hC=ke(),fC=hC("species"),nT=Array;oT.exports=function(s){var e;return aT(s)&&(e=s.constructor,dC(e)&&(e===nT||aT(e.prototype))?e=void 0:pC(e)&&(e=e[fC],e===null&&(e=void 0))),e===void 0?nT:e}});var cT=b((JQ,lT)=>{"use strict";var mC=uT();lT.exports=function(s,e){return new(mC(s))(e===0?0:e)}});var dT=b(()=>{"use strict";var bC=ue(),gC=sT(),SC=Pt(),vC=br(),yC=Ir(),TC=cT();bC({target:"Array",proto:!0},{flatMap:function(e){var t=vC(this),i=yC(t),r;return SC(e),r=TC(t,0),r.length=gC(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var pT=b(()=>{"use strict";var IC=_s();IC("flatMap")});var fT=b((r2,hT)=>{"use strict";dT();pT();var EC=si();hT.exports=EC("Array","flatMap")});var bT=b((s2,mT)=>{"use strict";var wC=fT();mT.exports=wC});var Gi=b((a2,gT)=>{"use strict";var xC=bT();gT.exports=xC});var ma=b((I2,TT)=>{"use strict";var PC=js(),AC=String;TT.exports=function(s){if(PC(s)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return AC(s)}});var Nd=b((E2,IT)=>{"use strict";IT.exports=`
7
+ \v\f\r                 \u2028\u2029\uFEFF`});var xT=b((w2,wT)=>{"use strict";var RC=Se(),$C=ri(),MC=ma(),Ud=Nd(),ET=RC("".replace),LC=RegExp("^["+Ud+"]+"),DC=RegExp("(^|[^"+Ud+"])["+Ud+"]+$"),Fd=function(s){return function(e){var t=MC($C(e));return s&1&&(t=ET(t,LC,"")),s&2&&(t=ET(t,DC,"$1")),t}};wT.exports={start:Fd(1),end:Fd(2),trim:Fd(3)}});var RT=b((x2,AT)=>{"use strict";var BC=sc().PROPER,CC=ge(),kT=Nd(),PT="​…᠎";AT.exports=function(s){return CC(function(){return!!kT[s]()||PT[s]()!==PT||BC&&kT[s].name!==s})}});var qd=b((k2,$T)=>{"use strict";var VC=xT().start,_C=RT();$T.exports=_C("trimStart")?function(){return VC(this)}:"".trimStart});var LT=b(()=>{"use strict";var OC=ue(),MT=qd();OC({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==MT},{trimLeft:MT})});var BT=b(()=>{"use strict";LT();var NC=ue(),DT=qd();NC({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==DT},{trimStart:DT})});var VT=b((M2,CT)=>{"use strict";BT();var FC=si();CT.exports=FC("String","trimLeft")});var OT=b((L2,_T)=>{"use strict";var UC=VT();_T.exports=UC});var FT=b((D2,NT)=>{"use strict";var qC=OT();NT.exports=qC});var HT=b(()=>{"use strict"});var zT=b(()=>{"use strict"});var QT=b((bG,WT)=>{"use strict";var WC=ze(),QC=Ri(),GC=ke(),YC=GC("match");WT.exports=function(s){var e;return WC(s)&&((e=s[YC])!==void 0?!!e:QC(s)==="RegExp")}});var KT=b((gG,YT)=>{"use strict";var KC=se(),XC=ge(),GT=KC.RegExp,JC=!XC(function(){var s=!0;try{GT(".","d")}catch{s=!1}var e={},t="",i=s?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},a={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};s&&(a.hasIndices="d");for(var n in a)r(n,a[n]);var o=Object.getOwnPropertyDescriptor(GT.prototype,"flags").get.call(e);return o!==i||t!==i});YT.exports={correct:JC}});var JT=b((SG,XT)=>{"use strict";var ZC=At();XT.exports=function(){var s=ZC(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e}});var tI=b((vG,eI)=>{"use strict";var eV=Ze(),tV=St(),iV=$s(),ZT=KT(),rV=JT(),sV=RegExp.prototype;eI.exports=ZT.correct?function(s){return s.flags}:function(s){return!ZT.correct&&iV(sV,s)&&!tV(s,"flags")?eV(rV,s):s.flags}});var rI=b((yG,iI)=>{"use strict";var Qd=Se(),aV=br(),nV=Math.floor,zd=Qd("".charAt),oV=Qd("".replace),Wd=Qd("".slice),uV=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,lV=/\$([$&'`]|\d{1,2})/g;iI.exports=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=lV;return r!==void 0&&(r=aV(r),u=uV),oV(a,u,function(l,p){var c;switch(zd(p,0)){case"$":return"$";case"&":return s;case"`":return Wd(e,0,t);case"'":return Wd(e,n);case"<":c=r[Wd(p,1,-1)];break;default:var d=+p;if(d===0)return l;if(d>o){var h=nV(d/10);return h===0?l:h<=o?i[h-1]===void 0?zd(p,1):i[h-1]+zd(p,1):l}c=i[d-1]}return c===void 0?"":c})}});var nI=b(()=>{"use strict";var cV=ue(),dV=Ze(),Yd=Se(),sI=ri(),pV=ae(),hV=ze(),fV=QT(),Xr=ma(),mV=Ls(),bV=tI(),gV=rI(),SV=ke(),vV=gt(),yV=SV("replace"),TV=TypeError,Gd=Yd("".indexOf),IV=Yd("".replace),aI=Yd("".slice),EV=Math.max;cV({target:"String",proto:!0},{replaceAll:function(e,t){var i=sI(this),r,a,n,o,u,l,p,c,d,h,f=0,m="";if(hV(e)){if(r=fV(e),r&&(a=Xr(sI(bV(e))),!~Gd(a,"g")))throw new TV("`.replaceAll` does not allow non-global regexes");if(n=mV(e,yV),n)return dV(n,e,i,t);if(vV&&r)return IV(Xr(i),e,t)}for(o=Xr(i),u=Xr(e),l=pV(t),l||(t=Xr(t)),p=u.length,c=EV(1,p),d=Gd(o,u);d!==-1;)h=l?Xr(t(u,d,o)):gV(u,o,d,[],void 0,t),m+=aI(o,f,d)+h,f=d+p,d=d+c>o.length?-1:Gd(o,u,d+c);return f<o.length&&(m+=aI(o,f)),m}})});var uI=b((EG,oI)=>{"use strict";HT();zT();nI();var wV=si();oI.exports=wV("String","replaceAll")});var cI=b((wG,lI)=>{"use strict";var xV=uI();lI.exports=xV});var pI=b((xG,dI)=>{"use strict";var kV=cI();dI.exports=kV});var fI=b((kG,hI)=>{"use strict";var PV=Vs(),AV=ma(),RV=ri(),$V=RangeError;hI.exports=function(e){var t=AV(RV(this)),i="",r=PV(e);if(r<0||r===1/0)throw new $V("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var vI=b((PG,SI)=>{"use strict";var gI=Se(),MV=Ll(),mI=ma(),LV=fI(),DV=ri(),BV=gI(LV),CV=gI("".slice),VV=Math.ceil,bI=function(s){return function(e,t,i){var r=mI(DV(e)),a=MV(t),n=r.length,o=i===void 0?" ":mI(i),u,l;return a<=n||o===""?r:(u=a-n,l=BV(o,VV(u/o.length)),l.length>u&&(l=CV(l,0,u)),s?r+l:l+r)}};SI.exports={start:bI(!1),end:bI(!0)}});var TI=b((AG,yI)=>{"use strict";var _V=Li();yI.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(_V)});var II=b(()=>{"use strict";var OV=ue(),NV=vI().start,FV=TI();OV({target:"String",proto:!0,forced:FV},{padStart:function(e){return NV(this,e,arguments.length>1?arguments[1]:void 0)}})});var wI=b((MG,EI)=>{"use strict";II();var UV=si();EI.exports=UV("String","padStart")});var kI=b((LG,xI)=>{"use strict";var qV=wI();xI.exports=qV});var AI=b((DG,PI)=>{"use strict";var jV=kI();PI.exports=jV});var Sh="2.0.150-dev.31e6196f.0";var xe=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(xe||{}),Vt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_FMP4="HLS_FMP4",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(Vt||{});var xs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(xs||{}),el=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(el||{});var tl=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(tl||{}),Un=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Un||{});var mh=D(Bi(),1),Ww=D(Pe(),1);import{assertNever as Fm,assertNonNullable as XP,isNonNullable as Yn,ValueSubject as Ol,Subject as JP,Subscription as ZP,merge as eA,observableFrom as tA,fromEvent as Vm,map as _m,tap as Om,filterChanged as iA,isNullable as Nl,ErrorCategory as Nm}from"@vkontakte/videoplayer-shared";var Cm=s=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Kn=class{constructor(e){this.connection$=new Ol(void 0);this.castState$=new Ol("NOT_AVAILABLE");this.errorEvent$=new JP;this.realCastState$=new Ol("NOT_AVAILABLE");this.subscription=new ZP;this.isDestroyed=!1;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=Yn(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=a=>{delete window.__onGCastApiAvailable,a&&!this.isDestroyed&&this.initializeCastApi()},r||Cm("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Nm.NETWORK,message:"Script loading failed!"})))}connect(){cast.framework.CastContext.getInstance()?.requestSession()}disconnect(){cast.framework.CastContext.getInstance()?.getCurrentSession()?.endSession(!0)}stopMedia(){return new Promise((e,t)=>{cast.framework.CastContext.getInstance()?.getCurrentSession()?.getMediaSession()?.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Yn(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Nl(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Nl(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(Vm(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=i.getCurrentSession()?.getMediaSession()?.media?.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Fm(r.sessionState)}})).add(eA(Vm(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Om(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),_m(r=>r.castState)),tA([i.getCastState()])).pipe(iA(),_m(rA),Om(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let a=r==="CONNECTED",n=Yn(this.connection$.getValue());if(a&&!n){let o=i.getCurrentSession();XP(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(Nl(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!a&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Yn(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){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{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:i}),this.initListeners()}catch(r){this.errorEvent$.next({id:"ChromecastInitializer",category:Nm.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},rA=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Fm(s)}};import{assertNonNullable as zl,combine as Wl,debounce as Ql,ErrorCategory as IA,filter as wr,filterChanged as eb,isNonNullable as Gl,isNullable as tb,map as EA,Subscription as wA,ValueSubject as Yl}from"@vkontakte/videoplayer-shared";import{assertNever as sA,assertNonNullable as Ci,ErrorCategory as aA,getHighestQuality as nA,isNonNullable as qm}from"@vkontakte/videoplayer-shared";import{assertNever as Um}from"@vkontakte/videoplayer-shared";var ne=(s,e=0,t=0)=>{switch(t){case 0:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return s;let i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Um(t)}return s},ai=(s,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(s);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(s);return Number(t.searchParams.get("offset_p")??0)}default:Um(e)}};var Jn=s=>{let{source:e,format:t,meta:i,output:r}=s,a,n,o;switch(t){case"MPEG":{let c=e[t];Ci(c);let d=nA(Object.keys(c));Ci(d);let h=c[d];Ci(h),a=h,n="video/mp4",o=Xn();break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let c=e[t];Ci(c),a=c.url,n="application/x-mpegurl",o=Xn();break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=e[t];Ci(c),a=c.url,n="application/dash+xml",o=Xn();break}case"DASH_LIVE_CMAF":{let c=e[t];Ci(c),a=c.url,n="application/dash+xml",o=jm();break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=e[t];Ci(c),a=ne(c.url),n="application/x-mpegurl",o=jm();break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw r.error$.next({id:"ChromecastProvider.createMediaInfo()",category:aA.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${t} is no longer supported`);default:return sA(t)}let u=oA(i.videoId??a,n);u.contentUrl=a,u.streamType=o,u.metadata=uA();let{title:l,subtitle:p}=i;return qm(l)&&(u.metadata.title=l),qm(p)&&(u.metadata.subtitle=p),u};function Xn(){return chrome.cast?.media?.StreamType?.BUFFERED??"BUFFERED"}function jm(){return chrome.cast?.media?.StreamType?.LIVE??"LIVE"}function oA(s,e){return chrome.cast?.media?.MediaInfo?new chrome.cast.media.MediaInfo(s,e):{contentId:s,contentType:e,metadata:{title:"",subtitle:""},streamType:Xn()}}function uA(){return chrome.cast?.media?.GenericMediaMetadata?new chrome.cast.media.GenericMediaMetadata:{images:[],metadataType:0,releaseDate:"",subtitle:"",title:"",releaseYear:1970,type:0}}var P=(s,e,t=!1)=>{let i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};var Zn=class{constructor(e){this.interval=0;this.params=e}start(e=0){clearInterval(this.interval),this.startVideoPosition=e,this.startTs=Date.now(),this.interval=window.setInterval(()=>{let t=(Date.now()-this.startTs)/1e3,i=this.startVideoPosition+t;this.params.output.position$.next(i)},1e3)}pause(){clearInterval(this.interval)}destroy(){clearInterval(this.interval)}};import{assertNever as Zm}from"@vkontakte/videoplayer-shared";import{isBrowserWindow as vA,ValueSubject as yA}from"@vkontakte/videoplayer-shared";var Hm=D(Pe(),1);import{getWindow as lA}from"@vkontakte/videoplayer-shared";var eo=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isChromiumBased(){return(0,Hm.default)(["Chrome","Chromium","Opera","Yandex","Edge","SamsungBrowser"],this.current)}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,a=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||a||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=lA().navigator,i=t.match(e);if(!i)return;let r=i[1],a=parseInt(r,10);if(!isNaN(a))return this._current_version=a,a}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var zm=D(Pe(),1);import{getWindow as Fl,isBrowserWindow as Ul}from"@vkontakte/videoplayer-shared";var Vi=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var to=class{constructor(e){this._highEntropyValues={};this._os={name:"Unknown",version:"Unknown",full:"Unknown"};this._details={vendor:"Unknown",model:"Unknown"};this._displayChecker=e}get current(){return this._current}get os(){return this._os}get details(){return this._details}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||this.os.name.toLowerCase().includes("ios")||(0,zm.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.os.name.toLowerCase().includes("mac")||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.os.name.toLowerCase().includes("android")||this.current==="Android"}get isWindows(){return this.os.name.toLowerCase().includes("windows")}get isLinux(){return this.os.name.toLowerCase().includes("linux")&&!this.isAndroid}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let e=Fl();if(!Ul(e))return;let{userAgent:t}=e.navigator;try{this._isMobile=Vi()}catch(i){console.error("DeviceChecker: calling isMobile error - ",i)}this.detectDevice(t),this.detectOS(t),this.detectDeviceDetails(t),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let e=Fl();if(!Ul(e))return;let{userAgentData:t}=e.navigator;if(t?.getHighEntropyValues){let i=await t.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=i,i.platform&&(this._os.name=this.normalizeOSName(i.platform),i.platformVersion&&(this._os.version=this.normalizeOSVersion(i.platformVersion),this._os.full=`${this._os.name} ${this._os.version}`)),i.model&&(this._details.model=i.model)}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,a=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||a||o||n||"Desktop"}catch(t){console.error("DeviceChecker: device detection error - ",t)}}detectOS(e){try{let t=[[/(windows nt) (6\.[23]); arm/i,["Windows RT"]],[/(windows nt) (6\.3); arm/i,["Windows RT 8.1"]],[/(windows (?:phone|mobile|iot))(?: os)?[/ ]?([\d.]+)/i,["Windows Mobile",2]],[/(windows)[/ ](xp|vista|7|8(\.1)?|10|11|2000|me)/i,[1,1]],[/windows nt ?([\d.]+)/i,["Windows",1]],[/(windows)[/ ](95|98|me|2000|xp|vista|7|8|8\.1|10|11)/i,[1,2]],[/(iphone os|cpu iphone os) ([\d_.]+)/i,["iOS",2]],[/(ipad os|cpu os) ([\d_.]+)/i,["iPadOS",2]],[/(ipod os|cpu ipod os) ([\d_.]+)/i,["iOS",2]],[/(?:ios|os) ([\d_.]+) like mac os x/i,["iOS",1]],[/cfnetwork\/.+darwin/i,["iOS"]],[/(mac os x) ?([\d_.]+)/i,["macOS",2]],[/(macintosh|mac os)/i,["macOS"]],[/(android) ([\d.]+)/i,[1,2]],[/(harmonyos)[/ ]?([\d.]*)/i,["HarmonyOS",2]],[/\b(ubuntu|debian|fedora|centos|arch|linux)(?:[-/ ]([\w.]+))?/i,[1,2]],[/(cros)\D*([\d.]+)/i,["Chrome OS",2]],[/(freebsd|openbsd|netbsd|dragonfly)[/ ]?([\w.]*)/i,[1,2]],[/(sunos|solaris)?([\d.]*)/i,["Solaris",2]],[/(aix)?([\d.]*)/i,["AIX",2]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r.length>0,o=r.length>1,u="Unknown",l="Unknown";if(n){let p=r[0];typeof p=="number"?p<a.length&&a[p]!==void 0&&(u=a[p]):u=p}if(o){let p=r[1];typeof p=="number"?p<a.length&&a[p]!==void 0&&(l=a[p]):p!==void 0&&(l=p)}else a[2]!==void 0?l=a[2]:a[1]!==void 0&&n&&typeof r[0]=="string"&&(l=a[1]);u=this.normalizeOSName(u),l=this.normalizeOSVersion(l,u),u==="iOS"&&/ipad/i.test(e)?u="iPadOS":u==="iPadOS"&&/ip(hone|od)/i.test(e)&&(u="iOS"),this._os={name:u,version:l||"Unknown",full:l&&l!=="Unknown"?`${u} ${l}`:u};break}}}catch(t){console.error("DeviceChecker: OS detection error - ",t)}}normalizeOSName(e){if(!e)return"Unknown";let t=e.toLowerCase();return t.includes("windows")?"Windows":t.includes("mac os")||t.includes("macintosh")?"macOS":t.includes("iphone")||t.includes("ios")?"iOS":t.includes("ipados")?"iPadOS":t.includes("android")?"Android":t.includes("harmonyos")?"HarmonyOS":t.includes("linux")?"Linux":t.includes("cros")?"Chrome OS":t.includes("freebsd")?"FreeBSD":t.includes("openbsd")?"OpenBSD":t.includes("solaris")||t.includes("sunos")?"Solaris":t.includes("aix")?"AIX":e}normalizeOSVersion(e,t){if(!e)return"Unknown";if(e!=="Unknown"&&(e=e.replace(/_/g,"."),t==="Windows")){let i=parseFloat(e);if(!isNaN(i)){if(i>=11)return"11";if(i>=10)return"10";if(i===6.3)return"8.1";if(i===6.2)return"8";if(i===6.1)return"7";if(i===6)return"Vista";if(i===5.1||i===5.2)return"XP";if(i===5)return"2000";if(i===4)return"NT 4.0"}}return e}detectDeviceDetails(e){try{let t=[[/(iphone)/i,["Apple","iPhone"]],[/(ipad)/i,["Apple","iPad"]],[/(ipod)/i,["Apple","iPod"]],[/(macintosh)/i,["Apple","Macintosh"]],[/(windows[\w\-_ ]*phone)/i,["Microsoft",0]],[/(windows nt|win64|win32|wow64)/i,["Microsoft","PC"]],[/\b(sch-i[89]0\d|shw-m380s|sm-[ptxs]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i,["Samsung",1]],[/\b((?:s[cgp]h|gt|sm)-(?![lr])\w+|sc[g-]?\d+a?|galaxy nexus)/i,["Samsung",1]],[/samsung[- ]((?!sm-[lr]|browser)[-\w]+)/i,["Samsung",1]],[/sec-(sgh\w+)/i,["Samsung",1]],[/smart-tv.+(samsung)/i,["Samsung","Smart TV"]],[/(samsung).*tizen/i,["Samsung","Smart TV"]],[/(pixel (?:c|tablet|[0-9a-z ]+))/i,["Google",1]],[/(pixelbook(?: go)?)/i,["Google",1]],[/nexus [0-9]/i,["Google",0]],[/(redmi[-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(mi[\w\-_ ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(poco[\w ]+)(?: bui|\))/i,["Xiaomi",1]],[/\b(hm[-_ ]?note?[\w ]*)(?: bui|\))/i,["Xiaomi",1]],[/\b(?:xiao)?mi[\w\-_ ]+pad/i,["Xiaomi",0]],[/(?:huawei|honor) ?([-\w ]+)[;)]/i,["Huawei",1]],[/\b(nexus 6p|\w{2,4}e?-[atu]?[ln][\dx][\dc][adnt]?)\b(?!.+d\/s)/i,["Huawei",1]],[/\b((?:ag[rs][2356]?k?|bah[234]?|bg[2o]|bt[kv]|cmr|cpn|db[ry]2?|jdn2|got|kob2?k?|mon|pce|scm|sht?|[tw]gr|vrd)-[ad]?[lw][0125][09]b?)/i,["Huawei",1]],[/(?:one)?(?:plus)? ?([a\d0]\d\d\d?)(?: b|\))/i,["OnePlus",1]],[/droid.+; (cph2[3-6]\d[13579]|((?:gm|hd)19|(?:ac|be|in|kb)20|(?:d[en]|eb|le|mt)21|ne22)[0-2]\d)(?: bui|\))/i,["OnePlus",1]],[/(oneplus)[-_ ]?([-\w]*)/i,["OnePlus",2]],[/\b(rmx[1-3]\d{3})(?: bui|;|\))/i,["Realme",1]],[/(realme)[-_ ]?([-\w]*)/i,["Realme",2]],[/; (\w+) bui.+ oppo/i,["OPPO",1]],[/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i,["OPPO",1]],[/\b(opd2(\d{3}a?))(?: bui|\))/i,["OPPO",1]],[/(oppo)[-_ ]?([-\w]*)/i,["OPPO",2]],[/; vivo (\w+)(?: bui|\))/i,["Vivo",1]],[/\b(v[12]\d{3}\w?[at])(?: bui|;)/i,["Vivo",1]],[/(vivo)[-_ ]?([-\w]*)/i,["Vivo",2]],[/\bmot(?:orola)?[- ]([\w\s]+)(\)| bui)/i,["Motorola",1]],[/((?:moto(?! 360)[-\w() ]+|xt\d{3,4}[cgkosw+]?[-\d]*|nexus 6)(?= bui|\)))/i,["Motorola",1]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b/i,["Motorola",0]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i,["Motorola",0]],[/droid.+; ([a-z]?\d[0-2]{2}[a-z]{2}|[c-g]\d{4}|so[-gl]\w+|xq-[a-z]{2}\d\d)(?= bui|\))/i,["Sony",1]],[/sony tablet [ps]/i,["Sony","Xperia Tablet"]],[/\b(?:sony)?sgp\w+(?: bui|\))/i,["Sony",0]],[/(sony)[-_ ]?([-\w]*)/i,["Sony",2]],[/\blg[-e;/ ]+(?!.*(?:browser|netcast|android tv|watch|webos))(\w+)/i,["LG",1]],[/\blg-?([\d\w]+) bui/i,["LG",1]],[/(lm(?:-?f100[nv]?|-[\w.]+)(?= bui|\))|nexus [45])/i,["LG",1]],[/((?=lg)?[vl]k-?\d{3}) bui/i,["LG",0]],[/(lg)[-_ ]?([-\w]*)/i,["LG",2]],[/(?:maemo|nokia).*(n900|lumia \d+|rm-\d+)/i,["Nokia",1]],[/nokia[-_ ]?(([-\w. ]*?))(?: bui|\)|;|\/)/i,["Nokia",1]],[/(nokia) (t[12][01])/i,["Nokia",2]],[/(?:\b|asus_)(transfo[prime ]{4,10} \w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i,["ASUS",1]],[/(?:asus[-_ ])?(zenfone[\w\-_ ]*)/i,["ASUS",1]],[/(rog[\w\-_ ]*)/i,["ASUS",1]],[/(asus)[-_ ]?([-\w]*)/i,["ASUS",2]],[/lenovo[-_ ]?([-\w ]+?)(?: bui|\)|\/)/i,["Lenovo",1]],[/(ideatab[-\w ]+|602lv|d-42a|a101lv|a2109a|a3500-hv|s[56]000|pb-6505[my]|tb-?x?\d{3,4}(?:f[cu]|xu|[av])|yt\d?-[jx]?\d+[lfmx])(?: bui|;|\)|\/)/i,["Lenovo",1]],[/(thinkpad[\w\-_ ]*)/i,["Lenovo",0]],[/(kf[a-z]{2}[a-z]*)(?: bui|\))/i,["Amazon",1]],[/(alexa)webm/i,["Amazon","Echo"]],[/(fire[\w\-_ ]*)/i,["Amazon",0]],[/(amazon)[-_ ]?([-\w]*)/i,["Amazon",2]],[/(?:blackberry|\(bb10;) (\w+)/i,["BlackBerry",1]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,["BlackBerry",1]],[/(playbook);[-\w),; ]+(rim)/i,["BlackBerry",1]],[/(microsoft); (lumia[\w ]+)/i,["Microsoft",2]],[/(surface duo)/i,["Microsoft","Surface Duo"]],[/(surface[\w\-_ ]*)/i,["Microsoft",0]],[/(zte)[- ]([\w ]+?)(?: bui|\/|\))/i,["ZTE",2]],[/(htc)[-;_ ]{1,2}([\w ]+(?=\)| bui)|\w+)/i,["HTC",2]],[/(alcatel|tcl)[-_ ]?([-\w]*)/i,[1,2]],[/(meizu)[-_ ]?([-\w]*)/i,["Meizu",2]],[/(tecno)[-_ ]?([-\w]*)/i,["Tecno",2]],[/(infinix)[-_ ]?([-\w]*)/i,["Infinix",2]],[/(micromax)[-_ ]?([-\w]*)/i,["Micromax",2]],[/(lava)[-_ ]?([-\w]*)/i,["Lava",2]],[/(panasonic)[-_ ]?([-\w]*)/i,["Panasonic",2]],[/(sharp)\/?([-\w]*)/i,["Sharp",2]],[/(benq)[-_ ]?([-\w]*)/i,["BenQ",2]],[/(palm)[-_ ]?([-\w]*)/i,["Palm",2]],[/(vertu)[-_ ]?([-\w]*)/i,["Vertu",2]],[/(gionee)[-_ ]?([-\w]*)/i,["Gionee",2]],[/(doogee)[-_ ]?([-\w]*)/i,["Doogee",2]],[/(ulefone)[-_ ]?([-\w]*)/i,["Ulefone",2]],[/(blackview)[-_ ]?([-\w]*)/i,["Blackview",2]],[/(cubot)[-_ ]?([-\w]*)/i,["Cubot",2]],[/(umidigi)[-_ ]?([-\w]*)/i,["UMIDIGI",2]],[/(oukitel)[-_ ]?([-\w]*)/i,["Oukitel",2]],[/(fairphone)[-_ ]?([-\w]*)/i,["Fairphone",2]],[/(cat)[-_ ]?([-\w]*)/i,["Cat",2]],[/(energy)[-_ ]?([-\w]*)/i,["Energizer",2]],[/(land rover)[-_ ]?([-\w]*)/i,["Land Rover",2]],[/(shield[\w\-_ ]*)/i,["Nvidia",0]],[/(crkey)/i,["Google","Chromecast"]],[/(roku)[\dx]*/i,["Roku",0]],[/(apple)[-_ ]?tv/i,["Apple","TV"]],[/(amazon)[-_ ]?tv/i,["Amazon","Fire TV"]],[/(google)[-_ ]?tv/i,["Google","TV"]],[/(smart[\w\-_ ]*tv)/i,[0,"Smart TV"]],[/(playstation[\w\-_ ]*)/i,["Sony",0]],[/(nintendo[\w\-_ ]*)/i,["Nintendo",0]],[/(xbox[\w\-_ ]*)/i,["Microsoft",0]],[/(googlebot)/i,["Google","Bot"]],[/(bingbot)/i,["Microsoft","Bing Bot"]],[/(yandexbot)/i,["Yandex","Bot"]],[/(slackbot)/i,["Slack","Bot"]],[/(twitterbot)/i,["Twitter","Bot"]],[/(facebookbot)/i,["Facebook","Bot"]],[/(linkedinbot)/i,["LinkedIn","Bot"]],[/(tesla)[-_ ]?([-\w]*)/i,["Tesla",2]],[/(raspberry[\w\-_ ]*)/i,["Raspberry Pi",0]]];for(let[i,r]of t){let a=e.match(i);if(a){let n=r[0],o=r[1],u=typeof n=="number"?a[n]!==void 0?this.normalizeVendorName(a[n]):"Unknown":this.normalizeVendorName(n),l="Unknown";typeof o=="number"?l=a[o]!==void 0?a[o]:"Unknown":o!==void 0?l=o:a[1]!==void 0?l=a[1]:a[0]!==void 0&&(l=a[0]),l=this.normalizeModelName(l,u),this.details.vendor=u,this.details.model=l;break}}}catch(t){console.error("DeviceChecker: device details detection error - ",t)}}normalizeVendorName(e){if(!e)return"Unknown";let t=e.toLowerCase();return{apple:"Apple",samsung:"Samsung",google:"Google",xiaomi:"Xiaomi",huawei:"Huawei",oneplus:"OnePlus",oppo:"OPPO",vivo:"Vivo",realme:"Realme",motorola:"Motorola",sony:"Sony",lg:"LG",nokia:"Nokia",asus:"ASUS",lenovo:"Lenovo",amazon:"Amazon",blackberry:"BlackBerry",microsoft:"Microsoft",zte:"ZTE",htc:"HTC",alcatel:"Alcatel",tcl:"TCL",meizu:"Meizu",tecno:"Tecno",infinix:"Infinix",micromax:"Micromax",lava:"Lava",panasonic:"Panasonic",sharp:"Sharp",benq:"BenQ",palm:"Palm",honor:"Honor",nvidia:"NVIDIA",roku:"Roku"}[t]||e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}normalizeModelName(e,t){if(!e||e==="Unknown")return e;if(e==="0")return"Unknown";let i=e.replace(/^build\//i,"").replace(/\s+bui$/i,"").replace(/\)$/,"").replace(/[;,)]/g,"").replace(/\s*\(.*?\)\s*/g,"").trim(),r=t.toLowerCase();return r.includes("samsung")?i=i.replace(/^(sm-|gt-|sgh-|sch-)/i,""):r.includes("xiaomi")?i=i.replace(/^(mi[\s\-_]*|redmi[\s\-_]*)/i,""):r.includes("oneplus")?i=i.replace(/^oneplus[\s\-_]*/i,""):r.includes("google")&&(i=i.replace(/^(pixel[\s\-_]*|nexus[\s\-_]*)/i,"")),i=i.replace(/_/g," ").replace(/-/g," ").replace(/\s+/g," ").trim(),i?(i.length>0&&/^[a-z]/.test(i)&&(i=i.charAt(0).toUpperCase()+i.slice(1)),i):"Unknown"}detectIOSVersion(){try{let e=Fl();if(!Ul(e))return;if(this._highEntropyValues.platformVersion){let i=this._highEntropyValues.platformVersion.split(".").slice(0,2).join(".");this._iosVersion=parseFloat(i);return}if(this._os.version!=="Unknown"){let i=this._os.version.split("."),r=i.length>=2?`${i[0]}.${i[1]}`:i[0];this._iosVersion=parseFloat(r);return}let t=e.navigator.userAgent.match(/OS (\d+(_\d+)?)/i);t?.[1]&&(this._iosVersion=parseFloat(t[1].replace(/_/g,".")))}catch(e){console.error("DeviceChecker: iOS version detection error - ",e)}}};import{getWindow as Wm,isBrowserWindow as cA}from"@vkontakte/videoplayer-shared";var io=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in Wm()}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(){let e=Wm();if(!cA(e))return;let{navigator:t,screen:i}=e,{maxTouchPoints:r}=t;try{this._maxTouchPoints=r??0,this._isHdr=!!e.matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=i.colorDepth}catch(a){console.error(a)}try{this._pixelRatio=e.devicePixelRatio||1,this._height=i.height,this._width=i.width,this._height=i.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(a){console.error(a)}}};import{getWindow as ql,isBrowserWindow as Gm}from"@vkontakte/videoplayer-shared";var _e=()=>window.ManagedMediaSource||window.MediaSource,ni=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Qm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Er=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var dA=ql().document?.createElement("video"),pA='video/mp4; codecs="avc1.42000a,mp4a.40.2"',hA='video/mp4; codecs="hev1.1.6.L93.B0"',Ym='video/webm; codecs="vp09.00.10.08"',Km='video/webm; codecs="av01.0.00M.08"',fA='audio/mp4; codecs="mp4a.40.2"',mA='audio/webm; codecs="opus"',Xm,bA=async()=>{let s=ql();if(!Gm(s))return;let e={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[t,i]=await Promise.all([s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Km}}),s.navigator.mediaCapabilities.decodingInfo({...e,video:{...e.video,contentType:Ym}})]);Xm={DASH_WEBM_AV1:t,DASH_WEBM:i}};bA().catch(s=>{console.log(dA),console.error(s)});var ro=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 Xm}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){let e=ql();if(!Gm(e))return;let t=e.document;this._video=t.createElement("video");try{this._protocols={mms:ni(),mse:Qm(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!e.RTCPeerConnection,ws:!!e.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let i=!!_e()?.isTypeSupported?.(pA),r=!!_e()?.isTypeSupported?.(hA),a=!!_e()?.isTypeSupported?.(fA);this._codecs={h264:i,h265:r,vp9:!!_e()?.isTypeSupported?.(Ym),av1:!!_e()?.isTypeSupported?.(Km),aac:a,opus:!!_e()?.isTypeSupported?.(mA),mpeg:(i||r)&&a},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(i){console.error(i)}try{this.destroyVideoElement()}catch(i){console.error("Error destroying video element:",i)}}destroyVideoElement(){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);this._video.parentNode?.replaceChild(e,this._video),this._video=null}};import{getWindow as gA,isBrowserWindow as SA}from"@vkontakte/videoplayer-shared";var Jm="audio/mpeg",so=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){let e=gA();if(!SA(e))return;let t=e.document;this._audio=t.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(Jm)},this._codecs={mp3:!!_e()?.isTypeSupported?.(Jm)}}catch(i){console.error(i)}try{this.destroyAudioElement()}catch(i){console.error("Error destroying audio element:",i)}}destroyAudioElement(){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);this._audio.parentNode?.replaceChild(e,this._audio),this._audio=null}};var jl=class{constructor(){this.isInited$=new yA(!1);this._displayChecker=new io,this._deviceChecker=new to(this._displayChecker),this._browserChecker=new eo,this._videoChecker=new ro(this._deviceChecker,this._browserChecker),this._audioChecker=new so,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(){vA()&&(this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0))}},$=new jl;var Hl=s=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=$.video,a=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return s.filter(o=>{switch(o){case"DASH_SEP":return n&&e.mp4&&a;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&a||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&a;case"DASH_LIVE_CMAF":return n&&e.mp4&&a&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&a;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return Zm(o)}})},Os=s=>{switch(s){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return Zm(s)}},TA=s=>{let t=Object.keys(s).filter(i=>!Os(i));return Hl(t).length>0};var Ns=class{constructor(e){this.subscription=new wA;this.sessionId$=new Yl(null);this.mediaSessionId$=new Yl(null);this.contentId$=new Yl(null);this.isMobile=Vi();this.mobileVolumeState={muted:!1,volume:0};this.media=null;this.lastRequestedVolume=null;this.syncMediaState=e=>{if(tb(e))return;this.media=e,this.mediaSessionId$.next(e.mediaSessionId??null);let t=e.media?.contentId;t&&this.contentId$.next(t),this.syncPlaybackState(e);let i=e.media?.duration;Gl(i)&&this.params.output.duration$.next(Math.max(0,i));let r=e.currentTime;if(Gl(r)){this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.params.output.position$.next(r);let n=this.params.output.isLive$.getValue();e.playerState==="PLAYING"&&!n?this.progressTicker.start(r):this.progressTicker.pause()}};this.params=e,this.progressTicker=new Zn(e),this.log=this.params.dependencies.logger.createComponentLog("ChromecastPresentationApiProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Os(e.format)),this.subscribe()}subscribe(){let e=r=>{this.params.output.error$.next({category:IA.WTF,id:"ChromecastPresentationApiProvider",message:r?.message??"Unknown error",thrown:r})};this.subscription.add(this.params.chromecastConnector.message$.pipe(wr(r=>!!r)).subscribe(r=>{this.handleMessage(r)},e)),this.subscription.add(this.sessionId$.pipe(wr(Gl),eb(),Ql(0)).subscribe(()=>{this.loadMedia()},e));let t=this.contentId$.pipe(eb(),EA(Boolean));this.subscription.add(Wl({seekState:this.params.desiredState.seekState.stateChangeEnded$,mediaLoaded:t}).pipe(wr(({mediaLoaded:r})=>r)).subscribe(()=>{let r=this.params.desiredState.seekState.getState();r.state==="requested"&&this.seek(r.position/1e3)},e));let i=Wl({playbackState:this.params.desiredState.playbackState.stateChangeStarted$,mediaLoaded:t});this.subscription.add(i.pipe(wr(({mediaLoaded:r})=>r),Ql(0)).subscribe(()=>{this.syncPlayback()},e)),this.subscription.add(i.pipe(wr(({mediaLoaded:r,playbackState:{from:a,to:n}})=>!r&&a==="stopped"&&n==="playing")).subscribe(()=>{this.loadMedia()},e)),this.subscription.add(Wl({volumeState:this.params.desiredState.volume.stateChangeStarted$.pipe(Ql(30)),mediaLoaded:t}).pipe(wr(({mediaLoaded:r})=>r)).subscribe(({volumeState:r})=>{let{muted:a,volume:n}=r.to;this.setVolume(n,a)},e))}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId);let t=e.message?.media?.[0];this.syncMediaState(t);let i=e.message?.receiver.volume;this.syncVolumeState(i)}break;case"v2_message":{switch(e.message?.type){case"MEDIA_STATUS":{let t=e.message?.status?.[0];this.syncMediaState(t);break}}break}}}loadMedia(){let e=Jn(this.params),t=this.media?.currentTime,i=this.params.desiredState.seekState.getState(),r=t??(i.state!=="none"?i.position/1e3:0),n=this.params.desiredState.playbackState.getState()==="playing";this.params.chromecastConnector.sendV2Message({type:"LOAD",requestId:0,media:e,autoplay:n,currentTime:r,customData:null,activeTrackIds:null}),this.params.output.willSeekEvent$.next()}stop(){this.params.chromecastConnector.stopMedia()}play(){let e=this.mediaSessionId$.getValue();zl(e,"play on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PLAY",mediaSessionId:e,customData:null})}pause(){let e=this.mediaSessionId$.getValue();zl(e,"pause on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"PAUSE",mediaSessionId:e,customData:null})}seek(e){let t=this.mediaSessionId$.getValue();zl(t,"seek on null mediaSessionId"),this.params.chromecastConnector.sendV2Message({type:"SEEK",currentTime:e,mediaSessionId:t}),this.params.output.willSeekEvent$.next()}setVolume(e,t){let i=e,r=`[setVolume] volume: ${e}, muted: ${t}`;this.isMobile&&(i=this.mobileVolumeState.volume,r+=`, mobile next volume: ${i}`),this.log({message:r}),this.lastRequestedVolume={volume:i,muted:t},this.params.chromecastConnector.sendV2Message({type:"SET_VOLUME",requestId:0,volume:{level:t?0:i,muted:t?!0:null}})}syncPlaybackState({playerState:e,idleReason:t}){let i=this.params.output.isBuffering$.getValue(),r=e==="BUFFERING";switch(i!==r&&this.params.output.isBuffering$.next(r),e){case"PAUSED":P(this.params.desiredState.playbackState,"paused");break;case"PLAYING":P(this.params.desiredState.playbackState,"playing");break;case"IDLE":{t==="FINISHED"?(this.params.output.endedEvent$.next(),P(this.params.desiredState.playbackState,"stopped"),this.contentId$.next(null)):P(this.params.desiredState.playbackState,"ready");break}case"BUFFERING":break}}syncPlayback(){let e=this.params.desiredState.playbackState.getState();switch(this.log({message:`[syncPlayback] ${e}`}),e){case"ready":break;case"playing":this.play();break;case"paused":this.pause();break;case"stopped":this.stop();break}}syncVolumeState(e){if(tb(e))return;let{level:t,muted:i}=e,r={muted:i??!1,volume:t??0};this.lastRequestedVolume&&(i&&(r.volume=this.lastRequestedVolume.volume),this.lastRequestedVolume.muted&&!t&&!i&&(r.volume=this.lastRequestedVolume.volume,r.muted=!0),this.lastRequestedVolume=null);let a=`[syncVolumeState] volume: ${r.volume}, muted: ${r.muted}`;this.isMobile&&(this.mobileVolumeState.volume=r.volume,this.mobileVolumeState.muted=r.muted,r.volume=this.params.output.volume$.getValue().volume,a+=`, volume passed to state machine: ${r.volume}`),this.log({message:a}),this.params.output.volume$.next(r)}destroy(){this.progressTicker.destroy(),this.subscription.unsubscribe()}};import{assertNonNullable as xA,ErrorCategory as Kl,filter as kA,Subject as PA,Subscription as Xl,tap as AA,ValueSubject as xr,fromEvent as Fs}from"@vkontakte/videoplayer-shared";var ib=s=>({castDevice:{friendlyName:s},remotePlayer:{},remotePlayerController:{},session:{}}),rb=()=>String(Date.now())+String(Math.floor(Math.random()*1e5));var Us=class{constructor(e){this.capabilities=["WEB"];this.presentationRequest$=new xr(null);this.sessionId$=new xr(null);this.broadcastChannel=new BroadcastChannel("vk_player_chromecast_events");this.subscription=new Xl;this.subscriptionEvents=new Xl;this.isDestroyed=!1;this.sequenceNumber=0;this.presentationAvailable$=new xr(!1);this.presentationConnection$=new xr(null);this.message$=new xr(null);this.friendlyName$=new xr(null);this.errorEvent$=new PA;this.clientId=this.getClientId(),this.params=e,this.log=e.logger.createComponentLog("ChromecastPresentationApiConnector"),this.log({message:"constructor"}),this.reinitPresentation(),this.subscribe()}destroy(){this.log({message:"destroy"}),this.subscription.unsubscribe(),this.subscriptionEvents.unsubscribe(),this.broadcastChannel.close(),this.isDestroyed=!0}disconnect(e=!0){this.log({message:"disconnect"}),e&&this.stopMedia(),this.presentationRequest$.next(null);let t=this.presentationConnection$.getValue();t&&t.close(),this.presentationConnection$.next(null),this.friendlyName$.next(null),this.resetSequenceNumber(),this.resetSubscriptionEvents()}stopMedia(){this.log({message:"stopMedia"}),this.sendV2Message({type:"STOP"})}reinitPresentation(e=!0){let t=this.createCastUrl(),i=new PresentationRequest(t);this.presentationRequest$.next(i),this.log({message:"PresentationRequest created"}),i.getAvailability().then(r=>{let a=()=>{this.log({message:`PresentationRequest presentation availability: ${r.value}`}),this.presentationAvailable$.next(r.value)};this.subscriptionEvents.add(Fs(r,"change").subscribe(()=>{a()})),a()}).catch(()=>{this.presentationAvailable$.next(!0)}),window.navigator.presentation.defaultRequest=i,e&&i.reconnect("auto-join").then(r=>{this.log({message:"PresentationRequest reconnect success"}),this.handleConnection(r)}).catch(()=>{this.log({message:"PresentationRequest reconnect failed"})})}async connect(){this.log({message:"connect"});try{this.presentationRequest$.getValue()||(this.log({message:"reinitPresentation"}),this.reinitPresentation(!1));let e=this.presentationRequest$.getValue();xA(e,"connect with null presentationRequest");let t=await e.start();this.handleConnection(t)}catch(e){switch(e?.name){case"AbortError":case"NotAllowedError":break;default:this.errorEvent$.next({category:Kl.WTF,id:"ChromecastPresentationApiConnector",message:e?.message??"connect error",thrown:e});break}}}subscribe(){this.subscription.add(Fs(this.broadcastChannel,"message").subscribe(e=>{this.log({message:`broadcast connection data: ${e.data}`}),e.data==="connection"&&this.disconnect(!1)})),this.subscription.add(this.presentationAvailable$.subscribe(e=>{this.log({message:`presentationAvailable$: ${e}`})})),this.subscription.add(this.presentationConnection$.pipe(AA(e=>{this.log({message:`presentationConnection$: ${!!e}`})}),kA(e=>!!e)).subscribe(e=>{let t=Fs(e,"message").subscribe(a=>{let n=JSON.parse(a.data);n.clientId===this.clientId&&(this.log({message:`[onmessage] ${a.data}`}),this.handleMessage(n),this.message$.next(n))}),i=Fs(e,"connect").subscribe(()=>{this.send("client_connect")}),r=Fs(e,"close").subscribe(a=>{switch(a.reason){case"error":this.errorEvent$.next({category:Kl.WTF,id:"ChromecastPresentationApiConnector",message:"Session error",thrown:a});break;case"closed":break}});this.subscriptionEvents.add(t),this.subscriptionEvents.add(i),this.subscriptionEvents.add(r)}))}send(e){switch(e){case"client_connect":{let t={type:"client_connect",message:this.clientId,sequenceNumber:-1,timeoutMillis:0,clientId:this.clientId};this.safeSend(JSON.stringify(t));break}}}sendV2Message(e){let t=this.sessionId$.getValue();if(t){let i={type:"v2_message",sequenceNumber:this.getSequenceNumber(),timeoutMillis:0,clientId:this.clientId,message:{...e,sessionId:t}};this.safeSend(JSON.stringify(i))}}safeSend(e){try{this.log({message:`[send] ${e}`});let t=this.presentationConnection$.getValue();t?.state==="connected"&&t?.send(e)}catch(t){this.errorEvent$.next({category:Kl.WTF,id:"ChromecastPresentationApiConnector",message:"PresentationConnection send error",data:{message:e},thrown:t})}}handleMessage(e){switch(e.type){case"new_session":case"update_session":{this.sessionId$.next(e.message.sessionId),this.friendlyName$.next(e.message.receiver.friendlyName||"Chromecast Device");break}case"receiver_action":e.message?.action==="stop"&&this.disconnect();break}}createCastUrl(){return`cast:${this.params.appId}?clientId=${this.clientId}&autoJoinPolicy=tab_and_origin_scoped&defaultActionPolicy=create_session&launchTimeout=60000&supportedAppTypes=${this.capabilities}&appParams=%7B%22launchCheckerParams%22%3A%7B%7D%7D`}getSequenceNumber(){let e=this.sequenceNumber;return this.sequenceNumber=(this.sequenceNumber+1)%Number.MAX_SAFE_INTEGER,e}resetSequenceNumber(){this.sequenceNumber=0}getClientId(){let e="__vk_player_chromecast_id";return window[e]=window[e]||rb()}resetSubscriptionEvents(){this.subscriptionEvents.unsubscribe(),this.subscriptionEvents=new Xl}handleConnection(e){this.log({message:"connection available"}),this.isDestroyed?(this.log({message:"connected on already destroyed component"}),e.close()):(this.broadcastChannel.postMessage("connection"),this.presentationConnection$.next(e))}};import{ValueSubject as sb,Subject as RA,map as $A,Subscription as MA,combine as LA,filterChanged as ab,assertNonNullable as DA}from"@vkontakte/videoplayer-shared";var Ot=class s{constructor(e){this.subscription=new MA;this.connection$=new sb(void 0);this.castState$=new sb("NOT_AVAILABLE");this.errorEvent$=new RA;let t=s.isSupported();this.log=e.dependencies.logger.createComponentLog("ChromecastPresentationApiInitializer"),this.log({message:`[constructor] receiverApplicationId: ${e.receiverApplicationId}, isDisabled: ${e.isDisabled}, isSupported: ${t}`}),!(!t||e.isDisabled||!e.receiverApplicationId)&&(this.chromecastConnector=new Us({appId:e.receiverApplicationId,logger:e.dependencies.logger}),this.subscribe())}static isSupported(){return"chrome"in window&&"presentation"in navigator&&"BroadcastChannel"in window}subscribe(){DA(this.chromecastConnector,"subscribe with null chromecastConnector"),this.subscription.add(this.chromecastConnector.errorEvent$.subscribe(this.errorEvent$));let e=LA({connection:this.chromecastConnector.presentationConnection$,available:this.chromecastConnector.presentationAvailable$,friendlyName:this.chromecastConnector.friendlyName$.pipe(ab())});this.subscription.add(e.pipe($A(({connection:t,friendlyName:i})=>!!(t&&i)),ab()).subscribe(t=>{let i=this.chromecastConnector?.friendlyName$.getValue()??"";this.connection$.next(t?ib(i):void 0)})).add(e.subscribe(({available:t,connection:i})=>{t?i?this.castState$.next("CONNECTED"):this.castState$.next("AVAILABLE"):this.castState$.next("NOT_AVAILABLE")}))}connect(){this.log({message:"connect"}),this.chromecastConnector?.connect()}disconnect(){this.log({message:"disconnect"}),this.chromecastConnector?.disconnect()}async stopMedia(){this.log({message:"stopMedia"}),this.chromecastConnector?.stopMedia()}toggleConnection(){let e=!!this.chromecastConnector?.presentationConnection$.getValue();this.log({message:`toggleConnection: isConnected - ${e}`}),e?this.disconnect():this.connect()}setVolume(e){}setMuted(e){}destroy(){this.log({message:"destroy"}),this.chromecastConnector?.destroy(),this.subscription.unsubscribe()}};var rh=D(Pe(),1),sh=D(oi(),1),xw=D(vc(),1);var qv=D($o(),1);import{isNonNullable as vD,Subject as Mo,merge as _v}from"@vkontakte/videoplayer-shared";var O=class{constructor(e){this.transitionStarted$=new Mo;this.transitionEnded$=new Mo;this.transitionUpdated$=new Mo;this.forceChanged$=new Mo;this.stateChangeStarted$=_v(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=_v(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||vD(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 ea,debounce as Ov,ErrorCategory as yD,fromEvent as qi,map as Nv,merge as Fv,observableFrom as TD,Subject as ID,Subscription as ad,timeout as ED}from"@vkontakte/videoplayer-shared";var wD=5,xD=5,kD=500,Uv=7e3,ta=class{constructor(e){this.subscription=new ad;this.loadMediaTimeoutSubscription=new ad;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:ea(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:ea(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:ea(e)}break}default:ea(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Os(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 ad;this.subscription.add(e),this.subscription.add(Fv(this.videoState.stateChangeStarted$.pipe(Nv(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(Nv(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new ID;e.add(r.pipe(Ov(kD)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>wD)&&r.next(o),a=o})),e.add(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<xD&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:ea(n)}}),t(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(qi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Fv(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,TD(["init"])).pipe(Ov(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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=Jn(this.params),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),i={volume:e.volume??t.volume,muted:e.muted??t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(ED(Uv).subscribe(()=>a(`timeout(${Uv})`)))});(0,qv.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:yD.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var wd=D(Pe(),1);import{clearVideoElement as Hv,getWindow as AD}from"@vkontakte/videoplayer-shared";import{clearVideoElement as PD}from"@vkontakte/videoplayer-shared";var jv=s=>{try{s.pause(),s.playbackRate=0,PD(s),s.remove()}catch(e){console.error(e)}};import{fromEvent as RD,Subscription as $D}from"@vkontakte/videoplayer-shared";var nd=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)}},Lo=AD(),od=Lo.WeakMap?new Lo.WeakMap:new nd,ud=Lo.WeakMap?new Lo.WeakMap:new Map,MD=(s,e=20)=>{let t=0;return RD(s,"ratechange").subscribe(i=>{t++,t>=e&&(s.currentTime=s.currentTime,t=0)})},Ae=(s,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=s.querySelector("video"),r=!!i;i?Hv(i):(i=document.createElement("video"),s.appendChild(i)),od.set(i,r);let a=new $D;return a.add(MD(i,e)),ud.set(i,a),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},Re=s=>{ud.get(s)?.unsubscribe(),ud.delete(s);let t=od.get(s);od.delete(s),t?Hv(s):jv(s)};var cd=D(Bi(),1);import{assertNonNullable as ra,isNonNullable as Rt,isNullable as BD,fromEvent as Cr,merge as zv,observableFrom as Wv,filterChanged as Qv,map as sa,Subject as Gv,Subscription as CD,ValueSubject as VD,ErrorCategory as _D}from"@vkontakte/videoplayer-shared";import{isNonNullable as ld,isNullable as LD,Subscription as DD}from"@vkontakte/videoplayer-shared";var Do=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{let n=s.getState(),o=e(),u=LD(r),l=new DD;return r&&l.add(r.subscribe(p=>{let c=s.getState();i(p,c)&&s.setState(p)},a)),i(o,n)||(t(n),u&&s.setState(n)),l.add(s.stateChangeStarted$.subscribe(p=>{t(p.to),u&&s.setState(p.to)},a)),l},ot=(s,e,t)=>Do(e,()=>s.loop,i=>{ld(i)&&(s.loop=i)},{onError:t}),$e=(s,e,t,i)=>Do(e,()=>({muted:s.muted,volume:s.volume}),r=>{ld(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||r?.muted===a?.muted&&r?.volume===a?.volume,changed$:t,onError:i}),We=(s,e,t,i)=>Do(e,()=>s.playbackRate,r=>{ld(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),ia=Do;var OD=s=>["__",s.language,s.label].join("|"),ND=(s,e)=>{if(s.id===e)return!0;let[t,i,r]=e.split("|");return s.language===i&&s.label===r},dd=class s{constructor(e){this.available$=new Gv;this.current$=new VD(void 0);this.error$=new Gv;this.subscription=new CD;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:_D.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ia(t.internalTextTracks,()=>(0,cd.default)(this.internalTracks),a=>{Rt(a)&&this.setInternal(a)},{equal:(a,n)=>Rt(a)&&Rt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(sa(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(ia(t.externalTextTracks,()=>(0,cd.default)(this.externalTracks),a=>{Rt(a)&&this.setExternal(a)},{equal:(a,n)=>Rt(a)&&Rt(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(sa(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ia(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(ia(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){ra(this.video);let{textTracks:e}=this.video;this.subscription.add(Cr(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(zv(Cr(e,"addtrack"),Cr(e,"removetrack"),Wv(["init"])).pipe(sa(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Qv((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(zv(Cr(e,"change"),Wv(["init"])).pipe(sa(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),sa(i=>i&&this.htmlTextTrackToITextTrack(i).id),Qv()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Cr(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=a=>{let n=a.target?.cues??null;n&&n.length&&(this.applyCueSettings(a.target?.cues??null),a.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add(Cr(e,"removetrack").subscribe(i=>{i.track?.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;Rt(t.align)&&(r.align=t.align),Rt(t.position)&&(r.position=t.position),Rt(t.size)&&(r.size=t.size),Rt(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){ra(this.video);let t=[...this.video.textTracks];return e?t:t.filter(s.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:OD(e),a=this.externalTracks.has(r),n=(a?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r)?.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){ra(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(BD(e)||!ND(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){ra(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){ra(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Qe=dd;var ji=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 Yv=s=>{let e=s;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},pd=s=>{let e=Yv(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Kv=s=>{let e=Yv(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};import{fromEvent as Oe,map as $t,merge as Bo,filterChanged as Jv,isNonNullable as Zv,Subject as UD,filter as hd,mapTo as fd,combine as qD,once as jD,shareReplay as Ne,throttle as HD,ErrorCategory as zD,ValueSubject as ey,Subscription as WD}from"@vkontakte/videoplayer-shared";var FD=3,Xv=(s,e,t=FD)=>{let i=0,r=0;for(let a=0;a<s.length;a++){let n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};var Me=s=>{let e=k=>Oe(s,k).pipe(fd(void 0),Ne(1)),t=new WD,i=()=>t.unsubscribe(),r=Bo(Oe(s,"progress"),Oe(s,"timeupdate")).pipe($t(()=>Xv(s.buffered,s.currentTime)),Ne(1)),a=$.browser.isSafari?qD({play:e("play").pipe(jD()),playing:e("playing")}).pipe(fd(void 0),Ne(1)):e("playing"),n=Oe(s,"volumechange").pipe($t(()=>({muted:s.muted,volume:s.volume})),Ne(1)),o=Oe(s,"ratechange").pipe($t(()=>s.playbackRate),Ne(1)),u=Oe(s,"error").pipe(hd(()=>!!(s.error||s.played.length)),$t(()=>{let k=s.error;return{id:k?`MediaError#${k.code}`:"HtmlVideoError",category:zD.VIDEO_PIPELINE,message:k?k.message:"Error event from HTML video element",thrown:s.error??void 0}}),Ne(1)),l=Oe(s,"timeupdate").pipe($t(()=>s.currentTime),Ne(1)),p=["waiting","seeking","seeked","timeupdate"],c=new UD,d=.3,h;t.add(Bo(...p.map(k=>Oe(s,k))).subscribe(k=>{let F=s.currentTime;s.loop&&Zv(h)&&Zv(F)&&h>=s.duration-d&&F<=d&&c.next(h),h=F}));let f=e("pause").pipe(hd(()=>!s.error&&h!==s.duration),Ne(1)),m=Oe(s,"enterpictureinpicture").pipe(Ne(1)),S=Oe(s,"leavepictureinpicture").pipe(Ne(1)),g=new ey(Kv(s));t.add(m.subscribe(()=>g.next(!0))),t.add(S.subscribe(()=>g.next(!1)));let v=new ey(pd(s)),T=Oe(s,"fullscreenchange").pipe(Ne(1));t.add(T.pipe($t(()=>pd(s))).subscribe(v));let y=.1,x=1e3,A=Oe(s,"timeupdate").pipe($t(k=>s.duration-s.currentTime<y),Jv(),Ne(1)),R=Bo(A.pipe(hd(k=>!s.loop&&k)),Oe(s,"ended")).pipe(HD(x),fd(void 0),Ne(1)),B=Bo(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(k=>Oe(s,k)),A.pipe($t(k=>({type:k?"ended":"unknown"})))).pipe($t(k=>$.browser.isFirefox&&k.type==="ended"?s.readyState<2:s.readyState<3),Jv(),Ne(1));return{playing$:a,pause$:f,canplay$:e("canplay"),ended$:R,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$:Oe(s,"durationchange").pipe($t(()=>s.duration),Ne(1)),isBuffering$:B,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:S,destroy:i}};import{VideoQuality as li}from"@vkontakte/videoplayer-shared";var Mt=s=>{switch(s){case"mobile":return li.Q_144P;case"lowest":return li.Q_240P;case"low":return li.Q_360P;case"sd":case"medium":return li.Q_480P;case"hd":case"high":return li.Q_720P;case"fullhd":case"full":return li.Q_1080P;case"quadhd":case"quad":return li.Q_1440P;case"ultrahd":case"ultra":return li.Q_2160P}};var Ue=D(Ge(),1),bd=D(Pe(),1),zi=D(oi(),1);import{isNonNullable as K,isNullable as Oo,now as gy,isHigher as No,isHigherOrEqual as Hi,isInvariantQuality as Fo,isLowerOrEqual as _r,videoSizeToQuality as Sy,assertNotEmptyArray as Uo,assertNonNullable as vy}from"@vkontakte/videoplayer-shared";var md=!1,Ft={},oy=s=>{md=s},uy=()=>{Ft={}},ly=s=>{s(Ft)},aa=(s,e)=>{md&&(Ft.meta=Ft.meta??{},Ft.meta[s]=e)},Fe=class{constructor(e){this.name=e}next(e){if(!md)return;Ft.series=Ft.series??{};let t=Ft.series[this.name]??[];t.push([Date.now(),e]),Ft.series[this.name]=t}};import{isHigher as tB,isHigherOrEqual as NH,isLower as cy,isLowerOrEqual as FH,isNonNullable as Co,isNullable as iB,videoHeightToQuality as Vo}from"@vkontakte/videoplayer-shared";function dy(s,e,t){return!s.max&&s.min===e?"high_quality":!s.min&&s.max===t?"traffic_saving":"unknown"}function Vr(s,e,t){return iB(s)||Co(s.min)&&Co(s.max)&&cy(s.max,s.min)||Co(s.min)&&e&&tB(s.min,e)||Co(s.max)&&t&&cy(s.max,t)}function py({limits:s,highestAvailableHeight:e,lowestAvailableHeight:t}){return Vr({max:s?.max?Vo(s.max):void 0,min:s?.min?Vo(s.min):void 0},e?Vo(e):void 0,t?Vo(t):void 0)}var yy=new Fe("best_bitrate"),qo=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;var Or=s=>(e,t)=>s*(Number(e.bitrate)-Number(t.bitrate)),Tt=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=gy()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},jo='Assertion "ABR Tracks is empty array" failed',_o=new WeakMap,hy=new WeakMap,fy=new WeakMap,Wi=(s,e,t,i)=>{let r=[...e].sort(Or(1)),a=[...t].sort(Or(1)),n=a.filter(u=>K(u.bitrate)&&K(s.bitrate)?s.bitrate/u.bitrate>i:!0),o=(0,Ue.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,Ue.default)(a,-1);return o&&(0,bd.default)(n,o)?o:n.length?(0,Ue.default)(n,-1):(0,Ue.default)(a,0)},Qi=(s,e,t,i)=>{let r=_o.get(e);r||(r=[...e].sort(Or(1)),_o.set(e,r));let a=_o.get(t);a||(a=[...t].sort(Or(1)),_o.set(t,a));let n=fy.get(s);n||(n=a.filter(u=>K(u.bitrate)&&K(s.bitrate)?s.bitrate/u.bitrate>i:!0),fy.set(s,n));let o=(0,Ue.default)(a,Math.round(a.length*r.indexOf(s)/(r.length+1)))??(0,Ue.default)(a,-1);return o&&(0,bd.default)(n,o)?o:n.length?(0,Ue.default)(n,-1):(0,Ue.default)(a,0)},my=s=>"quality"in s,Ho=(s,e,t,i)=>{let r=K(i?.last?.bitrate)&&K(t?.bitrate)&&i.last.bitrate<t.bitrate?s.trackCooldownIncreaseQuality:s.trackCooldownDecreaseQuality,a=t&&i&&i.history[t.id]&&gy()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!a&&i.recordSelection(t),a&&i?.last){let n=i.last;i?.recordSwitch(n);let o=my(n)?"video":"audio",u=my(n)?n.quality:n.bitrate;return e({message:`
8
8
  [last ${o} selected] ${u}
9
- `}),n}return i?.recordSwitch(t),t},rB=(s,e)=>Math.log(e)/Math.log(s),vy=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&$.display.pixelRatio){let a=$.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,p=rB(n,o*a+u)+l;Number.isFinite(p)&&(r*=p)}}return K(t?.min)&&Hi(t.min,s.highQualityLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},fy=new WeakMap,ut=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:f,panelSize:m})=>{Uo(s,jo);let{containerSizeFactor:S,containerSizeLimit:g}=vy({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&K(o)?o:1,T=fy.get(s);T||(T=s.filter(E=>!Fo(E.quality)).sort((E,I)=>No(E.quality,I.quality)?-1:1),fy.set(s,T));let y=(0,Ue.default)(T,-1)?.quality,x=(0,Ue.default)(T,0)?.quality,A=Vr(r,x,y),R=v*qo(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},B=null;for(let E of T){let I=!0;if(g)if(E.size)I=E.size.width<=g.width&&E.size.height<=g.height;else{let W=g&&by(g);I=W?_r(E.quality,W):!0}if(!I){w[E.quality]="FitsContainer";continue}let N=h||t,L=K(N)&&isFinite(N)&&K(E.bitrate)?N-a>=E.bitrate*R:!0,H=r?.min===E.quality;if(!L&&!H){w[E.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&u&&!Fo(u.quality)&&(n??0)<i.minBufferToSwitchUp&&No(E.quality,u.quality)){w[E.quality]="Buffer";continue}if(!!c&&Hi(E.quality,c)&&!H){w[E.quality]="DroppedFramesLimit";continue}if(!!d&&Hi(E.quality,d)&&!H){w[E.quality]="StallsLimit";continue}let Ie=A||(Oo(r?.max)||_r(E.quality,r.max))&&(Oo(r?.min)||Hi(E.quality,r.min)),Ee=K(p)&&!p?_r(E.quality,i.backgroundVideoQualityLimit):!0;if(!Ie||!Ee){w[E.quality]="FitsQualityLimits";continue}B||(B=E)}B&&B.bitrate&&Sy.next(B.bitrate);let P=B??(0,Ue.default)(T,-1)??s[0],F=l?.last,C=Ho(i,f,P,l);return K(l)&&C.quality!==F?.quality&&f({message:`
9
+ `}),n}return i?.recordSwitch(t),t},rB=(s,e)=>Math.log(e)/Math.log(s),Ty=({tuning:s,container:e,limits:t,panelSize:i})=>{let r=s.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(s.usePixelRatio&&$.display.pixelRatio){let a=$.display.pixelRatio;if(s.pixelRatioMultiplier)r*=s.pixelRatioMultiplier*(a-1)+1;else{let n=s.pixelRatioLogBase,[o=0,u=0,l=0]=s.pixelRatioLogCoefficients,p=rB(n,o*a+u)+l;Number.isFinite(p)&&(r*=p)}}return K(t?.min)&&Hi(t.min,s.highQualityLimit)&&(r*=2),{containerSizeLimit:s.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},by=new WeakMap,ut=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:f,panelSize:m})=>{Uo(s,jo);let{containerSizeFactor:S,containerSizeLimit:g}=Ty({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&K(o)?o:1,T=by.get(s);T||(T=s.filter(E=>!Fo(E.quality)).sort((E,I)=>No(E.quality,I.quality)?-1:1),by.set(s,T));let y=(0,Ue.default)(T,-1)?.quality,x=(0,Ue.default)(T,0)?.quality,A=Vr(r,x,y),R=v*qo(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},B=null;for(let E of T){let I=!0;if(g)if(E.size)I=E.size.width<=g.width&&E.size.height<=g.height;else{let z=g&&Sy(g);I=z?_r(E.quality,z):!0}if(!I){w[E.quality]="FitsContainer";continue}let N=h||t,L=K(N)&&isFinite(N)&&K(E.bitrate)?N-a>=E.bitrate*R:!0,H=r?.min===E.quality;if(!L&&!H){w[E.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&u&&!Fo(u.quality)&&(n??0)<i.minBufferToSwitchUp&&No(E.quality,u.quality)){w[E.quality]="Buffer";continue}if(!!c&&Hi(E.quality,c)&&!H){w[E.quality]="DroppedFramesLimit";continue}if(!!d&&Hi(E.quality,d)&&!H){w[E.quality]="StallsLimit";continue}let Ie=A||(Oo(r?.max)||_r(E.quality,r.max))&&(Oo(r?.min)||Hi(E.quality,r.min)),Ee=K(p)&&!p?_r(E.quality,i.backgroundVideoQualityLimit):!0;if(!Ie||!Ee){w[E.quality]="FitsQualityLimits";continue}B||(B=E)}B&&B.bitrate&&yy.next(B.bitrate);let k=B??(0,Ue.default)(T,-1)??s[0],F=l?.last,C=Ho(i,f,k,l);return K(l)&&C.quality!==F?.quality&&f({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
12
  ${s.map(E=>`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate}, size: ${E.size?.width}:${E.size?.height} }`).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,Wi.default)(i??{}).map(([E,I])=>`${E}: ${I}`).join(`
16
+ ${(0,zi.default)(i??{}).map(([E,I])=>`${E}: ${I}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
@@ -34,19 +34,19 @@ var Yw=Object.create;var mh=Object.defineProperty;var Kw=Object.getOwnPropertyDe
34
34
  minQualityLimit: ${r?.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,Wi.default)(w).map(([E,I])=>`${E}: ${I}`).join(`
37
+ ${(0,zi.default)(w).map(([E,I])=>`${E}: ${I}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
40
  [best video track] ${B?.quality}
41
41
  [selected video track] ${C?.quality}
42
- `}),C},Nr=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:f,panelSize:m})=>{Uo(s,jo);let{containerSizeFactor:S,containerSizeLimit:g}=vy({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&K(o)?o:1,T=s.filter(I=>!Fo(I.quality)).sort((I,N)=>No(I.quality,N.quality)?-1:1),y=(0,Ue.default)(T,-1)?.quality,x=(0,Ue.default)(T,0)?.quality,A=Vr(r,x,y),R=v*qo(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},P=T.filter(I=>{let N=!0;if(g)if(I.size)N=I.size.width<=g.width&&I.size.height<=g.height;else{let q=g&&by(g);N=q?_r(I.quality,q):!0}if(!N)return w[I.quality]="FitsContainer",!1;let L=h||t,H=K(L)&&isFinite(L)&&K(I.bitrate)?L-a>=I.bitrate*R:!0,X=r?.min===I.quality;if(!H&&!X)return w[I.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&u&&!Fo(u.quality)&&(n??0)<i.minBufferToSwitchUp&&No(I.quality,u.quality))return w[I.quality]="Buffer",!1;if(!!c&&Hi(I.quality,c)&&!X)return w[I.quality]="DroppedFramesLimit",!1;if(!!d&&Hi(I.quality,d)&&!X)return w[I.quality]="StallsLimit",!1;let Ee=A||(Oo(r?.max)||_r(I.quality,r.max))&&(Oo(r?.min)||Hi(I.quality,r.min)),W=K(p)&&!p?_r(I.quality,i.backgroundVideoQualityLimit):!0;return!Ee||!W?(w[I.quality]="FitsQualityLimits",!1):!0})[0];P&&P.bitrate&&Sy.next(P.bitrate);let F=P??(0,Ue.default)(T,-1)??s[0],C=l?.last,E=Ho(i,f,F,l);return K(l)&&E.quality!==C?.quality&&f({message:`
42
+ `}),C},Nr=(s,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:p,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:f,panelSize:m})=>{Uo(s,jo);let{containerSizeFactor:S,containerSizeLimit:g}=Ty({container:e,tuning:i,limits:r,panelSize:m}),v=i.considerPlaybackRate&&K(o)?o:1,T=s.filter(I=>!Fo(I.quality)).sort((I,N)=>No(I.quality,N.quality)?-1:1),y=(0,Ue.default)(T,-1)?.quality,x=(0,Ue.default)(T,0)?.quality,A=Vr(r,x,y),R=v*qo(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),w={},k=T.filter(I=>{let N=!0;if(g)if(I.size)N=I.size.width<=g.width&&I.size.height<=g.height;else{let q=g&&Sy(g);N=q?_r(I.quality,q):!0}if(!N)return w[I.quality]="FitsContainer",!1;let L=h||t,H=K(L)&&isFinite(L)&&K(I.bitrate)?L-a>=I.bitrate*R:!0,X=r?.min===I.quality;if(!H&&!X)return w[I.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&K(i.minBufferToSwitchUp)&&u&&!Fo(u.quality)&&(n??0)<i.minBufferToSwitchUp&&No(I.quality,u.quality))return w[I.quality]="Buffer",!1;if(!!c&&Hi(I.quality,c)&&!X)return w[I.quality]="DroppedFramesLimit",!1;if(!!d&&Hi(I.quality,d)&&!X)return w[I.quality]="StallsLimit",!1;let Ee=A||(Oo(r?.max)||_r(I.quality,r.max))&&(Oo(r?.min)||Hi(I.quality,r.min)),z=K(p)&&!p?_r(I.quality,i.backgroundVideoQualityLimit):!0;return!Ee||!z?(w[I.quality]="FitsQualityLimits",!1):!0})[0];k&&k.bitrate&&yy.next(k.bitrate);let F=k??(0,Ue.default)(T,-1)??s[0],C=l?.last,E=Ho(i,f,F,l);return K(l)&&E.quality!==C?.quality&&f({message:`
43
43
  [VIDEO TRACKS ABR]
44
44
  [available video tracks]
45
45
  ${s.map(I=>`{ id: ${I.id}, quality: ${I.quality}, bitrate: ${I.bitrate}, size: ${I.size?.width}:${I.size?.height} }`).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,Wi.default)(i??{}).map(([I,N])=>`${I}: ${N}`).join(`
49
+ ${(0,zi.default)(i??{}).map(([I,N])=>`${I}: ${N}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
@@ -67,19 +67,19 @@ var Yw=Object.create;var mh=Object.defineProperty;var Kw=Object.getOwnPropertyDe
67
67
  minQualityLimit: ${r?.min},
68
68
 
69
69
  [limited video tracks]
70
- ${(0,Wi.default)(w).map(([I,N])=>`${I}: ${N}`).join(`
70
+ ${(0,zi.default)(w).map(([I,N])=>`${I}: ${N}`).join(`
71
71
  `)||"All tracks are available"}
72
72
 
73
- [best video track] ${P?.quality}
73
+ [best video track] ${k?.quality}
74
74
  [selected video track] ${E?.quality}
75
- `}),E},Fr=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Uo(t,jo);let p=r.considerPlaybackRate&&K(a)?a:1,c=[...t].sort(Or(-1)),d=s.bitrate;gy(d);let h=p*qo(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=zi(s,e,t,r.minVideoAudioRatio),S=l||i;K(S)&&isFinite(S)&&(f=c.find(T=>K(T.bitrate)&&K(m?.bitrate)?S-d>=T.bitrate*h&&T.bitrate>=m.bitrate:!1)),f||(f=m);let g=o?.last,v=f&&Ho(r,u,f,o);return K(o)&&v?.bitrate!==g?.bitrate&&u({message:`
75
+ `}),E},Fr=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Uo(t,jo);let p=r.considerPlaybackRate&&K(a)?a:1,c=[...t].sort(Or(-1)),d=s.bitrate;vy(d);let h=p*qo(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Wi(s,e,t,r.minVideoAudioRatio),S=l||i;K(S)&&isFinite(S)&&(f=c.find(T=>K(T.bitrate)&&K(m?.bitrate)?S-d>=T.bitrate*h&&T.bitrate>=m.bitrate:!1)),f||(f=m);let g=o?.last,v=f&&Ho(r,u,f,o);return K(o)&&v?.bitrate!==g?.bitrate&&u({message:`
76
76
  [AUDIO TRACKS ABR]
77
77
  [available audio tracks]
78
78
  ${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
79
79
  `)}
80
80
 
81
81
  [tuning]
82
- ${(0,Wi.default)(r??{}).map(([T,y])=>`${T}: ${y}`).join(`
82
+ ${(0,zi.default)(r??{}).map(([T,y])=>`${T}: ${y}`).join(`
83
83
  `)}
84
84
 
85
85
  [limit params]
@@ -93,14 +93,14 @@ var Yw=Object.create;var mh=Object.defineProperty;var Kw=Object.getOwnPropertyDe
93
93
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
94
94
 
95
95
  [selected audio track] ${v?.id}
96
- `}),v},Ur=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Uo(t,jo);let p=r.considerPlaybackRate&&K(a)?a:1,c=dy.get(t);c||(c=[...t].sort(Or(-1)),dy.set(t,c));let d=s.bitrate;gy(d);let h=p*qo(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Qi(s,e,t,r.minVideoAudioRatio),S=l||i;K(S)&&isFinite(S)&&(f=c.find(T=>K(T.bitrate)&&K(m?.bitrate)?S-d>=T.bitrate*h&&T.bitrate>=m.bitrate:!1)),f||(f=m);let g=o?.last,v=f&&Ho(r,u,f,o);return K(o)&&v?.bitrate!==g?.bitrate&&u({message:`
96
+ `}),v},Ur=(s,e,t,{estimatedThroughput:i,tuning:r,playbackRate:a,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Uo(t,jo);let p=r.considerPlaybackRate&&K(a)?a:1,c=hy.get(t);c||(c=[...t].sort(Or(-1)),hy.set(t,c));let d=s.bitrate;vy(d);let h=p*qo(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),f,m=Qi(s,e,t,r.minVideoAudioRatio),S=l||i;K(S)&&isFinite(S)&&(f=c.find(T=>K(T.bitrate)&&K(m?.bitrate)?S-d>=T.bitrate*h&&T.bitrate>=m.bitrate:!1)),f||(f=m);let g=o?.last,v=f&&Ho(r,u,f,o);return K(o)&&v?.bitrate!==g?.bitrate&&u({message:`
97
97
  [AUDIO TRACKS ABR]
98
98
  [available audio tracks]
99
99
  ${t.map(T=>`{ id: ${T.id}, bitrate: ${T.bitrate} }`).join(`
100
100
  `)}
101
101
 
102
102
  [tuning]
103
- ${(0,Wi.default)(r??{}).map(([T,y])=>`${T}: ${y}`).join(`
103
+ ${(0,zi.default)(r??{}).map(([T,y])=>`${T}: ${y}`).join(`
104
104
  `)}
105
105
 
106
106
  [limit params]
@@ -114,7 +114,7 @@ var Yw=Object.create;var mh=Object.defineProperty;var Kw=Object.getOwnPropertyDe
114
114
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
115
115
 
116
116
  [selected audio track] ${v?.id}
117
- `}),v};var de=s=>new URL(s).hostname;import{assertNever as Ly,assertNonNullable as Dy,combine as kB,debounce as AB,ErrorCategory as By,filter as Cy,filterChanged as RB,isNonNullable as yd,map as Go,merge as Vy,observableFrom as $B,once as MB,Subscription as LB,ValueSubject as Td,videoQualityToHeight as _y,videoSizeToQuality as DB}from"@vkontakte/videoplayer-shared";var Ay=D(Ge(),1);var Ty=D(ke(),1),yy=s=>{if(s instanceof DOMException&&(0,Ty.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},Le=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!yy(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return yy(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as zo,isNullable as lB,assertNonNullable as ua}from"@vkontakte/videoplayer-shared";var Ey=D(Bi(),1);import{isNonNullable as Iy,assertNonNullable as Wo,now as sB}from"@vkontakte/videoplayer-shared";function ve(){return sB()}function md(s){return ve()-s}function bd(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function wy(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function qr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,p,c,d=!1,h="arraybuffer",f=7e3,m=2e3,S=()=>{if(u)return;Wo(p);let C=md(p),E;if(C<m){E=m-C,setTimeout(S,E);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,A()},g=C=>(a=C,F),v=C=>(c=C,F),T=()=>(h="json",F),y=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,c&&c(),t&&t()}},x=C=>(d=C,F),A=()=>{p=ve(),n=new r,n.open("get",s);let C=0,E,I=0,N=()=>(Wo(p),Math.max(p,Math.max(E||0,I||0)));if(a&&n.addEventListener("progress",L=>{let H=ve();a.updateChunk&&L.loaded>C&&(a.updateChunk(N(),L.loaded-C),C=L.loaded,E=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;Wo(n);let L=n.status;if(L>=200&&L<300){let{response:H,responseType:X}=n,re=H?.byteLength;if(typeof re=="number"&&a){let ce=re-C;ce&&a.updateChunk&&a.updateChunk(N(),ce)}X==="json"&&(!H||!(0,Ey.default)(H).length)?y():(c&&c(),e(H))}else y()}),n.addEventListener("error",()=>{y()}),d){let L=()=>{Wo(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(I=ve(),n.removeEventListener("readystatechange",L))};n.addEventListener("readystatechange",L)}return n.responseType=h,n.send(),F},F={withBitrateReporting:g,withParallel:x,withJSONResponse:T,withRetryCount:C=>(l=C,F),withRetryInterval:(C,E)=>(Iy(C)&&(m=C),Iy(E)&&(f=E),F),withTimeout:C=>(o=C,F),withFinally:v,send:A,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return F}var na=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var xy=D(Bi(),1);var oa=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ve(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=ve()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=qr(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ve()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ve();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,xy.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as cB}from"@vkontakte/videoplayer-shared";import{isNonNullable as Py}from"@vkontakte/videoplayer-shared";var V=(s,e)=>Py(s)&&Py(e)&&s.readyState==="open"&&aB(s,e);function aB(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var ky=D(oi(),1);import{getWindow as nB}from"@vkontakte/videoplayer-shared";var gd=class{constructor(e,t,i,r){this.tag=e;this.time=t;this.data=i;this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:""}`}toDevNullEntry(){let e=(0,ky.default)(this.data).map(([t,i])=>`${t}:${i}`).join(",");return{key:this.tag,strings:[e,this.stack??""],numbers:[this.time]}}},oB=(s,e="warn")=>{let t=nB(),i=[];function r(a,n=!1){let o=t.performance?.timing?.navigationStart??0,u=new gd(s,Math.round((Date.now()-o)/1e3),a,n?new Error().stack:void 0);i.push(u),e&&t.console[e](u.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let a=i;return i=[],a},r},_=oB("vp_dash_live_debug",!1);var Qo=1e4,Sd=3;var dB=6e4,pB=10,hB=1,fB=500,la=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 cB,this.chunkRateEstimator=new na(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=bd(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&&(_({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",_({m:"ldp.catchUp.2"}),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()?(_({m:"ldp.play.1"}),this._playVideoElement()):(_({m:"ldp.play.2"}),this._notifyBuffering(!0))):(_({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,_({m:"startPlay",url:e.jidxUrl}),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=bd(e),_({m:"ldp.reinit",url: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;_({m:"iv"}),e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(_({m:"iv.err",e:e.error?.code+":"+e.error?.message}),t(`Video element error: ${e.error?.code}, details: ${e.error?.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"),_({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*($.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!cy({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Ay.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||zo(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(_({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.mediaSource?.addEventListener("sourceclose",o=>{_({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{_({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{wy(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new oa(Sd,Qo,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,p=!1,c=()=>{let y=a&&(!p||p===this.rep);return y||t("Not running!"),y},d=(y,x,A)=>{u&&u.abort(),u=qr(this.urlResolver.resolve(y,!1),x,A,()=>this._retryCallback()).withTimeout(Qo).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Sd).withFinally(()=>{u=null}).send()},h=(y,x,A)=>{ua(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),x,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let x=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${x}=>${y}`),i.playbackRate=y)},m=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let A=ve()-1e4,R=0;for(let B=0;B<this.bufferStates.length;B++){let P=this.bufferStates[B];y=Math.min(y,P.buf),P.ts<A&&R++}this.bufferStates.splice(0,R),t(`update playback rate; minBuffer=${y} drop=${R} jitter=${this.sourceJitter}`);let w=y-hB;this.sourceJitter>=0?w-=this.sourceJitter/2:this.sourceJitter-=1,w>3?f(1.15):w>1?f(1.1):w>.3?f(1.05):f(1)}},g=y=>{let x,A=()=>x&&x.start?x.start.length:0,R=L=>x.start[L]/1e3,w=L=>x.dur[L]/1e3,B=L=>x.fragIndex+L,P=(L,H)=>({chunkIdx:B(L),startTS:R(L),dur:w(L),discontinuity:H}),F=()=>{let L=0;if(x&&x.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,X=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,re=H;this.sourceJitter>1&&(re+=this.sourceJitter-1);let ce=x.dur.length-1;for(;ce>=0&&(re-=x.dur[ce],!(re<=0));--ce);L=Math.min(ce,x.dur.length-1-X),L=Math.max(L,0)}return P(L,!0)},C=L=>{let H=A();if(!(H<=0)){if(zo(L)){for(let X=0;X<H;X++)if(R(X)>L)return P(X)}return F()}},E=L=>{let H=A(),X=L?L.chunkIdx+1:0,re=X-x.fragIndex;if(!(H<=0)){if(!L||re<0||re-H>pB)return t(`Resync: offset=${re} bChunks=${H} chunk=`+JSON.stringify(L)),F();if(!(re>=H))return P(X-x.fragIndex,!1)}},I=(L,H,X)=>{l&&l.abort(),l=qr(this.urlResolver.resolve(L,!0,this.lowLatency),H,X,()=>this._retryCallback()).withTimeout(Qo).withRetryCount(Sd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(L,H)=>{I(y,X=>{if(!c())return;x=X;let re=!!x.lowLatency;re!==this.lowLatency&&m(re);let ce=0;for(let Ie=0;Ie<x.dur.length;++Ie)ce+=x.dur[Ie];ce>0&&(ua(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ce/x.dur.length)),r({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,L(C(H))},()=>this._handleNetworkError())},nextChunk:E}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),ua(this.filesFetcher),this.filesFetcher.abortAll()};return p={start:y=>{let{videoElement:x,logger:A}=this.params,R=g(e.jidxUrl),w,B,P,F,C=0,E,I,N,L=()=>{E&&(clearTimeout(E),E=void 0);let q=Math.max(fB,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),we=C+q,Ce=ve(),be=Math.min(1e4,we-Ce);C=Ce;let at=()=>{l||c()&&R.seek(()=>{c()&&(C=ve(),H(),L())})};be>0?E=window.setTimeout(()=>{this.paused?L():at()},be):at()},H=()=>{let q;for(;q=R.nextChunk(F);)F=q,Ee(q);let we=R.nextChunk(P);if(we){if(P&&we.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?L():(v(),_({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}Ie(we)}else L()},X=(q,we)=>{if(!c()||!this.sourceBuffer){_({m:"ab.0",c:[!c(),!this.sourceBuffer]});return}let Ce,be,at,Zt=pt=>{_({m:"ldp.postpone",t:pt}),window.setTimeout(()=>{c()&&X(q,we)},pt)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),_({m:"ldp.ab.1"}),Zt(100);else{let pt=ve(),Xe=x.currentTime;!this.paused&&x.buffered.length>1&&I===Xe&&pt-N>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),I!==Xe&&(I=Xe,N=pt);let ei=this._getBufferSizeSec();if(ei>30)_({m:"ldp.ab.3"}),A(`Buffered ${ei} seconds; delaying appendBuffer`),Zt(2e3);else try{if(this.params.config.useInvalidBufferFix&&V(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(q),this.videoPlayStarted?(_({m:"ldp.ab.5"}),this.bufferStates.push({ts:pt,buf:ei}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(_({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),we&&we()}catch(ht){if(_({m:"ldp.ab.err",e:ht.name}),ht.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),at=this.sourceBuffer.buffered.length,at!==0&&(Ce=this.sourceBuffer.buffered.start(0),be=Xe,be-Ce>4&&this.sourceBuffer.remove(Ce,be-3)),Zt(1e3);else throw ht}}},re=()=>{B&&w&&(A([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(P)]),X(B,function(){B=null,H()}))},ce=q=>e.fragUrlTemplate.replace("%%id%%",q.chunkIdx),Ie=q=>{c()&&h(ce(q),(we,Ce)=>{if(c()){if(Ce/=1e3,B=we,P=q,n=q.startTS,Ce){let be=Math.min(10,q.dur/Ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*be:be}re()}},()=>this._handleNetworkError())},Ee=q=>{c()&&(ua(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ce(q),!1)))},W=q=>{c()&&(e.cachedHeader=q,X(q,()=>{w=!0,re()}))};a=!0,R.seek(q=>{if(c()){if(C=ve(),!q){L();return}F=q,!lB(y)||q.startTS>y?Ie(q):(P=q,H())}},y),e.cachedHeader?W(e.cachedHeader):d(e.headerUrl,W,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},p}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),zo(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,ua(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return zo(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let d,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),f=c/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}d=this._selectQuality(c),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(d,h)=>{let f=ve();if(this.chunkRateEstimator.addInterval(d,f,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-d,speed:S}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&md(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,d)=>{let h=a.updateChunk(c,d);return h&&l(),h},notifySwitch:c=>{let d=ve();c<o&&(n=d),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=qr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Qo).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;Le(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{_({m:"ldp.pve.1"}),t||(_({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},dB))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var My=D(oi(),1);import{debounce as mB,filter as Ry,fromEvent as bB,interval as gB,isHigher as SB,isInvariantQuality as vB,isLower as yB,merge as TB,Subject as $y,Subscription as IB}from"@vkontakte/videoplayer-shared";var vd=class{constructor(){this.onDroopedVideoFramesLimit$=new $y;this.subscription=new IB;this.playing=!1;this.tracks=[];this.forceChecker$=new $y;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!vB(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&SB(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??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(bB(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=gB(this.droppedFramesChecker.checkTime).pipe(Ry(()=>this.playing),Ry(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(mB(this.droppedFramesChecker.checkTime)),i=TB(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){let t=(0,My.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>yB(i,r)?-1:1)?.[0]?.[0];return 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}},ci=vd;import{map as EB,Observable as wB}from"@vkontakte/videoplayer-shared";import{fromEvent as xB}from"@vkontakte/videoplayer-shared";var ca=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var PB=(s,e)=>new wB(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||ca()))},{...i,...e});r.observe(s);let a=xB(document,"visibilitychange").pipe(EB(n=>!document.hidden||ca())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Ye=PB;var BB=["paused","playing","ready"],CB=["paused","playing","ready"],da=class{constructor(e){this.subscription=new LB;this.videoState=new O("stopped");this.representations$=new Td([]);this.droppedFramesManager=new ci;this.maxSeekBackTime$=new Td(1/0);this.zeroTime$=new Td(void 0);this.liveOffset=new ji;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:By.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),n=Mt(r.name)??DB(r.video),o=r.bitrate/1e3,u={...r.video};if(!n)continue;let l={id:a,quality:n,bitrate:o,size:u};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),yd(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Id.default)(CB,e)&&(n||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&(0,Id.default)(BB,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ne(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){_({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let u=r?.from;u&&u==="ready"&&(_({m:"dlp.sync.2"}),this.dash.catchUp()),_({m:"dlp.sync.3"}),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ne(this.params.source.url,u))}return;default:return Ly(e)}};this.textTracksManager=new Qe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:By.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Vy(this.videoState.stateChangeStarted$.pipe(Go(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Go(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{_({m:"dlp.s.1",t:a+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=Ae(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(de(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=Me(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Go(r=>r.map(({track:a})=>a)),Cy(r=>!!r.length),MB()).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(()=>{this.videoState.getTransition()?.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(RB(),Go(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(kB({zeroTime:this.zeroTime$.pipe(Cy(yd)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add($e(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ye(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&_y(r),min:a&&_y(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),_({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&(_({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":_({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":_({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return Ly(r.to)}},t)).add(Vy(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,$B(["init"])).pipe(AB(0)).subscribe(this.syncPlayback,t))}destroy(){_({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Re(this.video)}createLiveDashPlayer(){let e=new la({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,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&yd(t)?t:ut(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let l=e.find(({track:p})=>p.id===a)?.representation;Dy(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Dy(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),_({m:"dlp.seek",p:e,no:n,url:this.params.source.url}),this.dash.reinit(ne(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Oy=da;import{filterChanged as G0}from"@vkontakte/videoplayer-shared";import{assertNever as XB,assertNonNullable as JB,debounce as ZB,ErrorCategory as Gy,filter as Md,filterChanged as Ld,fromEvent as eC,isNonNullable as Yy,isNullable as tC,map as Dd,merge as eu,observableFrom as Bd,once as Ky,Subscription as iC,throttle as rC}from"@vkontakte/videoplayer-shared";var Ed=D(Ge(),1);import{videoSizeToQuality as VB}from"@vkontakte/videoplayer-shared";var Ny=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Mt(a):void 0)??VB({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Fy=({id:s,bitrate:e})=>({id:s,bitrate:e}),Uy=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e});var wd=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Ed.default)(i.split("."),0),isDefault:r}),Yo=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Ed.default)(r.split("."),0)});var qe=s=>s.type==="template";var Ko=class{constructor(e,t){this.fov=e,this.orientation=t}};var Xo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=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 qy=`attribute vec2 a_vertex;
117
+ `}),v};var de=s=>new URL(s).hostname;import{assertNever as By,assertNonNullable as Cy,combine as PB,debounce as AB,ErrorCategory as Vy,filter as _y,filterChanged as RB,isNonNullable as Id,map as Go,merge as Oy,observableFrom as $B,once as MB,Subscription as LB,ValueSubject as Ed,videoQualityToHeight as Ny,videoSizeToQuality as DB}from"@vkontakte/videoplayer-shared";var $y=D(Ge(),1);var Ey=D(Pe(),1),Iy=s=>{if(s instanceof DOMException&&(0,Ey.default)(["Failed to load because no supported source was found.","The element has no supported sources."],s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))},Le=async(s,e)=>{let t=s.muted;try{await s.play()}catch(i){if(!Iy(i))return!1;if(e&&e(),t)return console.warn(i),!1;s.muted=!0;try{await s.play()}catch(r){return Iy(r)&&(s.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Wo,isNullable as lB,assertNonNullable as ua}from"@vkontakte/videoplayer-shared";var xy=D(Bi(),1);import{isNonNullable as wy,assertNonNullable as zo,now as sB}from"@vkontakte/videoplayer-shared";function ve(){return sB()}function gd(s){return ve()-s}function Sd(s){let e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function ky(s,e,t){let i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function qr(s,e,t,i){let r=window.XMLHttpRequest,a,n,o,u=!1,l=0,p,c,d=!1,h="arraybuffer",f=7e3,m=2e3,S=()=>{if(u)return;zo(p);let C=gd(p),E;if(C<m){E=m-C,setTimeout(S,E);return}m*=2,m>f&&(m=f),n&&n.abort(),n=new r,A()},g=C=>(a=C,F),v=C=>(c=C,F),T=()=>(h="json",F),y=()=>{if(!u){if(--l>=0){S(),i&&i();return}u=!0,c&&c(),t&&t()}},x=C=>(d=C,F),A=()=>{p=ve(),n=new r,n.open("get",s);let C=0,E,I=0,N=()=>(zo(p),Math.max(p,Math.max(E||0,I||0)));if(a&&n.addEventListener("progress",L=>{let H=ve();a.updateChunk&&L.loaded>C&&(a.updateChunk(N(),L.loaded-C),C=L.loaded,E=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>y())),n.addEventListener("load",()=>{if(u)return;zo(n);let L=n.status;if(L>=200&&L<300){let{response:H,responseType:X}=n,re=H?.byteLength;if(typeof re=="number"&&a){let ce=re-C;ce&&a.updateChunk&&a.updateChunk(N(),ce)}X==="json"&&(!H||!(0,xy.default)(H).length)?y():(c&&c(),e(H))}else y()}),n.addEventListener("error",()=>{y()}),d){let L=()=>{zo(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(I=ve(),n.removeEventListener("readystatechange",L))};n.addEventListener("readystatechange",L)}return n.responseType=h,n.send(),F},F={withBitrateReporting:g,withParallel:x,withJSONResponse:T,withRetryCount:C=>(l=C,F),withRetryInterval:(C,E)=>(wy(C)&&(m=C),wy(E)&&(f=E),F),withTimeout:C=>(o=C,F),withFinally:v,send:A,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return F}var na=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let n=t-a.start,o=a.end-a.start;i+=n;let u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Py=D(Bi(),1);var oa=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ve(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=ve()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=qr(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ve()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ve();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Py.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as cB}from"@vkontakte/videoplayer-shared";import{isNonNullable as Ay}from"@vkontakte/videoplayer-shared";var V=(s,e)=>Ay(s)&&Ay(e)&&s.readyState==="open"&&aB(s,e);function aB(s,e){for(let t=0;t<s.activeSourceBuffers.length;++t)if(s.activeSourceBuffers[t]===e)return!0;return!1}var Ry=D(oi(),1);import{getWindow as nB}from"@vkontakte/videoplayer-shared";var vd=class{constructor(e,t,i,r){this.tag=e;this.time=t;this.data=i;this.stack=r}toString(){return`${this.tag}: ${this.time}: ${JSON.stringify(this.data)}${this.stack?`, stack: ${this.stack}`:""}`}toDevNullEntry(){let e=(0,Ry.default)(this.data).map(([t,i])=>`${t}:${i}`).join(",");return{key:this.tag,strings:[e,this.stack??""],numbers:[this.time]}}},oB=(s,e="warn")=>{let t=nB(),i=[];function r(a,n=!1){let o=t.performance?.timing?.navigationStart??0,u=new vd(s,Math.round((Date.now()-o)/1e3),a,n?new Error().stack:void 0);i.push(u),e&&t.console[e](u.toString())}return r.reset=()=>{i=[]},r.drain=()=>{let a=i;return i=[],a},r},_=oB("vp_dash_live_debug",!1);var Qo=1e4,yd=3;var dB=6e4,pB=10,hB=1,fB=500,la=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 cB,this.chunkRateEstimator=new na(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Sd(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&&(_({m:"ldp.catchUp.1"}),this.rep.stop()),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",_({m:"ldp.catchUp.2"}),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()?(_({m:"ldp.play.1"}),this._playVideoElement()):(_({m:"ldp.play.2"}),this._notifyBuffering(!0))):(_({m:"ldp.play.3"}),this.catchUp())}startPlay(e,t){this.autoQuality=t,_({m:"startPlay",url:e.jidxUrl}),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=Sd(e),_({m:"ldp.reinit",url: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;_({m:"iv"}),e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(_({m:"iv.err",e:e.error?.code+":"+e.error?.message}),t(`Video element error: ${e.error?.code}, details: ${e.error?.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"),_({m:"ldp.fs",t:r}),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,n=t&&1.62*($.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){a=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!py({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,$y.default)(this.manifest,-1).video.height})&&(u&&a.video.height>u||l&&a.video.height<l)||(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Wo(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(_({m:"sourceopen",c:e.codecs}),this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.mediaSource?.addEventListener("sourceclose",o=>{_({m:"sourceclose"})}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{_({m:"canplay"}),this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{ky(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,a({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new oa(yd,Qo,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,n=null,o=null,u=null,l=null,p=!1,c=()=>{let y=a&&(!p||p===this.rep);return y||t("Not running!"),y},d=(y,x,A)=>{u&&u.abort(),u=qr(this.urlResolver.resolve(y,!1),x,A,()=>this._retryCallback()).withTimeout(Qo).withBitrateReporting(this.bitrateSwitcher).withRetryCount(yd).withFinally(()=>{u=null}).send()},h=(y,x,A)=>{ua(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),x,A,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=y=>{let x=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${x}=>${y}`),i.playbackRate=y)},m=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let A=ve()-1e4,R=0;for(let B=0;B<this.bufferStates.length;B++){let k=this.bufferStates[B];y=Math.min(y,k.buf),k.ts<A&&R++}this.bufferStates.splice(0,R),t(`update playback rate; minBuffer=${y} drop=${R} jitter=${this.sourceJitter}`);let w=y-hB;this.sourceJitter>=0?w-=this.sourceJitter/2:this.sourceJitter-=1,w>3?f(1.15):w>1?f(1.1):w>.3?f(1.05):f(1)}},g=y=>{let x,A=()=>x&&x.start?x.start.length:0,R=L=>x.start[L]/1e3,w=L=>x.dur[L]/1e3,B=L=>x.fragIndex+L,k=(L,H)=>({chunkIdx:B(L),startTS:R(L),dur:w(L),discontinuity:H}),F=()=>{let L=0;if(x&&x.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,X=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,re=H;this.sourceJitter>1&&(re+=this.sourceJitter-1);let ce=x.dur.length-1;for(;ce>=0&&(re-=x.dur[ce],!(re<=0));--ce);L=Math.min(ce,x.dur.length-1-X),L=Math.max(L,0)}return k(L,!0)},C=L=>{let H=A();if(!(H<=0)){if(Wo(L)){for(let X=0;X<H;X++)if(R(X)>L)return k(X)}return F()}},E=L=>{let H=A(),X=L?L.chunkIdx+1:0,re=X-x.fragIndex;if(!(H<=0)){if(!L||re<0||re-H>pB)return t(`Resync: offset=${re} bChunks=${H} chunk=`+JSON.stringify(L)),F();if(!(re>=H))return k(X-x.fragIndex,!1)}},I=(L,H,X)=>{l&&l.abort(),l=qr(this.urlResolver.resolve(L,!0,this.lowLatency),H,X,()=>this._retryCallback()).withTimeout(Qo).withRetryCount(yd).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(L,H)=>{I(y,X=>{if(!c())return;x=X;let re=!!x.lowLatency;re!==this.lowLatency&&m(re);let ce=0;for(let Ie=0;Ie<x.dur.length;++Ie)ce+=x.dur[Ie];ce>0&&(ua(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ce/x.dur.length)),r({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,L(C(H))},()=>this._handleNetworkError())},nextChunk:E}},v=()=>{a=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),ua(this.filesFetcher),this.filesFetcher.abortAll()};return p={start:y=>{let{videoElement:x,logger:A}=this.params,R=g(e.jidxUrl),w,B,k,F,C=0,E,I,N,L=()=>{E&&(clearTimeout(E),E=void 0);let q=Math.max(fB,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),we=C+q,Ce=ve(),be=Math.min(1e4,we-Ce);C=Ce;let at=()=>{l||c()&&R.seek(()=>{c()&&(C=ve(),H(),L())})};be>0?E=window.setTimeout(()=>{this.paused?L():at()},be):at()},H=()=>{let q;for(;q=R.nextChunk(F);)F=q,Ee(q);let we=R.nextChunk(k);if(we){if(k&&we.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?L():(v(),_({m:"ldp.fetchChunkIdx.0"}),this._initPlayerWith(e));return}Ie(we)}else L()},X=(q,we)=>{if(!c()||!this.sourceBuffer){_({m:"ab.0",c:[!c(),!this.sourceBuffer]});return}let Ce,be,at,Zt=pt=>{_({m:"ldp.postpone",t:pt}),window.setTimeout(()=>{c()&&X(q,we)},pt)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),_({m:"ldp.ab.1"}),Zt(100);else{let pt=ve(),Xe=x.currentTime;!this.paused&&x.buffered.length>1&&I===Xe&&pt-N>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),I!==Xe&&(I=Xe,N=pt);let ei=this._getBufferSizeSec();if(ei>30)_({m:"ldp.ab.3"}),A(`Buffered ${ei} seconds; delaying appendBuffer`),Zt(2e3);else try{if(this.params.config.useInvalidBufferFix&&V(this.mediaSource,this.sourceBuffer))return;this.sourceBuffer.appendBuffer(q),this.videoPlayStarted?(_({m:"ldp.ab.5"}),this.bufferStates.push({ts:pt,buf:ei}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(_({m:"ldp.ab.4"}),this.videoPlayStarted=!0,this._playVideoElement()),we&&we()}catch(ht){if(_({m:"ldp.ab.err",e:ht.name}),ht.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),at=this.sourceBuffer.buffered.length,at!==0&&(Ce=this.sourceBuffer.buffered.start(0),be=Xe,be-Ce>4&&this.sourceBuffer.remove(Ce,be-3)),Zt(1e3);else throw ht}}},re=()=>{B&&w&&(A([`Appending chunk, sz=${B.byteLength}:`,JSON.stringify(k)]),X(B,function(){B=null,H()}))},ce=q=>e.fragUrlTemplate.replace("%%id%%",q.chunkIdx),Ie=q=>{c()&&h(ce(q),(we,Ce)=>{if(c()){if(Ce/=1e3,B=we,k=q,n=q.startTS,Ce){let be=Math.min(10,q.dur/Ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*be:be}re()}},()=>this._handleNetworkError())},Ee=q=>{c()&&(ua(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ce(q),!1)))},z=q=>{c()&&(e.cachedHeader=q,X(q,()=>{w=!0,re()}))};a=!0,R.seek(q=>{if(c()){if(C=ve(),!q){L();return}F=q,!lB(y)||q.startTS>y?Ie(q):(k=q,H())}},y),e.cachedHeader?z(e.cachedHeader):d(e.headerUrl,z,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},p}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Wo(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,ua(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Wo(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let d,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(h=this._getBufferSizeSec(),f=c/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}d=this._selectQuality(c),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${c}`)},a={updateChunk:(d,h)=>{let f=ve();if(this.chunkRateEstimator.addInterval(d,f,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-d,speed:S}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,o,u=!0,l=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&gd(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,d)=>{let h=a.updateChunk(c,d);return h&&l(),h},notifySwitch:c=>{let d=ve();c<o&&(n=d),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=qr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Qo).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;Le(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{_({m:"ldp.pve.1"}),t||(_({m:"ldp.pve.2"}),this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},dB))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Dy=D(oi(),1);import{debounce as mB,filter as My,fromEvent as bB,interval as gB,isHigher as SB,isInvariantQuality as vB,isLower as yB,merge as TB,Subject as Ly,Subscription as IB}from"@vkontakte/videoplayer-shared";var Td=class{constructor(){this.onDroopedVideoFramesLimit$=new Ly;this.subscription=new IB;this.playing=!1;this.tracks=[];this.forceChecker$=new Ly;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!vB(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&SB(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??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(bB(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=gB(this.droppedFramesChecker.checkTime).pipe(My(()=>this.playing),My(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(mB(this.droppedFramesChecker.checkTime)),i=TB(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){let t=(0,Dy.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>yB(i,r)?-1:1)?.[0]?.[0];return 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}},ci=Td;import{map as EB,Observable as wB}from"@vkontakte/videoplayer-shared";import{fromEvent as xB}from"@vkontakte/videoplayer-shared";var ca=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var kB=(s,e)=>new wB(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||ca()))},{...i,...e});r.observe(s);let a=xB(document,"visibilitychange").pipe(EB(n=>!document.hidden||ca())).subscribe(n=>t.next(n));return()=>{r.unobserve(s),a.unsubscribe()}}),Ye=kB;var BB=["paused","playing","ready"],CB=["paused","playing","ready"],da=class{constructor(e){this.subscription=new LB;this.videoState=new O("stopped");this.representations$=new Ed([]);this.droppedFramesManager=new ci;this.maxSeekBackTime$=new Ed(1/0);this.zeroTime$=new Ed(void 0);this.liveOffset=new ji;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Vy.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let a=r.name??r.index.toString(10),n=Mt(r.name)??DB(r.video),o=r.bitrate/1e3,u={...r.video};if(!n)continue;let l={id:a,quality:n,bitrate:o,size:u};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Id(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,wd.default)(CB,e)&&(n||o)){this.prepare();return}if(r?.to!=="paused"&&a.state==="requested"&&(0,wd.default)(BB,e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ne(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){_({m:"dlp.sync.1"}),this.videoState.startTransitionTo("playing");let u=r?.from;u&&u==="ready"&&(_({m:"dlp.sync.2"}),this.dash.catchUp()),_({m:"dlp.sync.3"}),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ne(this.params.source.url,u))}return;default:return By(e)}};this.textTracksManager=new Qe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Vy.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Oy(this.videoState.stateChangeStarted$.pipe(Go(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Go(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{_({m:"dlp.s.1",t:a+`:${r.from}-${r.to}`}),this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})})),this.video=Ae(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(de(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=Me(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(Go(r=>r.map(({track:a})=>a)),_y(r=>!!r.length),MB()).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(()=>{this.videoState.getTransition()?.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(RB(),Go(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(PB({zeroTime:this.zeroTime$.pipe(_y(Id)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add($e(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(We(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(Ye(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:a}})=>{this.dash.setAutoQualityLimits({max:r&&Ny(r),min:a&&Ny(a)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:a})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),_({m:"dlp.vse.s"}),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&(_({m:"dlp.vse.r"}),this.params.desiredState.playbackState.setState("ready"));break;case"paused":_({m:"dlp.vse.pa"}),this.params.desiredState.playbackState.setState("paused");break;case"playing":_({m:"dlp.vse.pl"}),this.params.desiredState.playbackState.setState("playing");break;default:return By(r.to)}},t)).add(Oy(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,$B(["init"])).pipe(AB(0)).subscribe(this.syncPlayback,t))}destroy(){_({m:"dlp.destroy"}),this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Re(this.video)}createLiveDashPlayer(){let e=new la({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,useInvalidBufferFix:this.params.tuning.useInvalidBufferFix||!1},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&Id(t)?t:ut(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),a=r?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||a!==o){let l=e.find(({track:p})=>p.id===a)?.representation;Cy(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;Cy(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),_({m:"dlp.seek",p:e,no:n,url:this.params.source.url}),this.dash.reinit(ne(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Fy=da;import{filterChanged as G0}from"@vkontakte/videoplayer-shared";import{assertNever as XB,assertNonNullable as JB,debounce as ZB,ErrorCategory as Ky,filter as Dd,filterChanged as Bd,fromEvent as eC,isNonNullable as Xy,isNullable as tC,map as Cd,merge as eu,observableFrom as Vd,once as Jy,Subscription as iC,throttle as rC}from"@vkontakte/videoplayer-shared";var xd=D(Ge(),1);import{videoSizeToQuality as VB}from"@vkontakte/videoplayer-shared";var Uy=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Mt(a):void 0)??VB({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},qy=({id:s,bitrate:e})=>({id:s,bitrate:e}),jy=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e});var kd=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,xd.default)(i.split("."),0),isDefault:r}),Yo=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,xd.default)(r.split("."),0)});var qe=s=>s.type==="template";var Ko=class{constructor(e,t){this.fov=e,this.orientation=t}};var Xo=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=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 Hy=`attribute vec2 a_vertex;
118
118
  attribute vec2 a_texel;
119
119
 
120
120
  varying vec2 v_texel;
@@ -125,7 +125,7 @@ void main(void) {
125
125
  // save texel vector to pass to fragment shader
126
126
  v_texel = a_texel;
127
127
  }
128
- `;var jy=`#ifdef GL_ES
128
+ `;var zy=`#ifdef GL_ES
129
129
  precision highp float;
130
130
  precision highp int;
131
131
  #else
@@ -168,17 +168,17 @@ void main(void) {
168
168
  // sample using new coordinates
169
169
  gl_FragColor = texture2D(u_texture, tc);
170
170
  }
171
- `;var pi=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 Ko(this.params.fov,this.params.orientation),this.cameraRotationManager=new Xo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(qy,this.gl.VERTEX_SHADER),i=this.createShader(jy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,p=t+r,c=e-i,d=t+r;return[a,n,o,u,l,p,c,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as NB,now as pa,once as FB,Subscription as UB,ValueSubject as Pd,isNonNullable as qB,safeStorage as kd,filterChanged as jB}from"@vkontakte/videoplayer-shared";var Ut=(s,e,t)=>t*e+(1-t)*s,xd=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Hy=(s,e,t,i)=>{let r=0,a=t,n=xd(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};var Jo="stalls_manager_metrics",Ad="stalls_manager_abr_params",Wy="stalls_manager_default_tuning_abr_params",Rd=class{constructor(){this.isSeeked$=new Pd(!1);this.isBuffering$=new Pd(!1);this.maxQualityLimit=void 0;this.currentStallsCount=0;this.sumStallsDuration=0;this.lastStallDuration=0;this.providerStartWatchingTimestamp=0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new UB;this.severeStallOccurred$=new Pd(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData(Ad):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=pa(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(pa()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Wy)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData(Ad),this.setStoredData(Wy,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Jo,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(Jo,[]),this.setStoredData(Ad,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>a&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){return JSON.parse(kd.get(e)??t)}setStoredData(e,t){kd.set(e,JSON.stringify(t))}removeStoredData(e){kd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Jo,"[]"),r=t/e,a=i.length?Ut(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Jo,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(FB()).subscribe(t=>this.providerStartWatchingTimestamp=pa())),this.subscription.add(this.currentStallDuration$.pipe(jB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(NB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=pa(),c=r&&this.currentStallsCount>=r,d=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&p-l>=i+o&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,qB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&pa()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},jr=Rd;import{combine as HB,map as WB,observeElementSize as zB,Subscription as QB,ValueSubject as $d,noop as GB}from"@vkontakte/videoplayer-shared";var Zo=class{constructor(){this.subscription=new QB;this.pipSize$=new $d(void 0);this.videoSize$=new $d(void 0);this.elementSize$=new $d(void 0);this.pictureInPictureWindowRemoveEventListener=GB}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(zB(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(HB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(WB(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as zy,map as YB,once as Qy}from"@vkontakte/videoplayer-shared";var hi=({subscription:s,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!$.browser.isSafari)return;let r=0,a=!1;s.add(e.volume.stateChangeStarted$.pipe(YB(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),zy(n=>!!n),Qy()).subscribe(()=>{r=performance.now(),a=!0})),s.add(i.playbackRateState$.pipe(zy(()=>a),Qy()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var ha=class{constructor(e){this.subscription=new iC;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ci;this.stallsManager=new jr;this.elementSizeManager=new Zo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Tt;this.audioTrackSwitchHistory=new Tt;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?.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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return XB(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new pi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 Qe(e.source.url),this.params=e,this.video=Ae(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(de(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=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;tC(this.observableVideo)&&(this.observableVideo=Me(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Gy.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Md(c=>!!c.length),Ky()).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(Dd(c=>c.to.state!=="none"),Ld());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.currentBuffer$,e.currentBuffer$),a(this.player.lastRequestFirstBytes$.pipe(Md(Yy),Ky()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Dd(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(ot(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),hi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add($e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),h=this.player.getCodecs();if(JB(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(wd(S));let g=[];for(let v of S.representations){let T=Fy(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(Yo(m));let S=[];for(let g of m.representations){let v=Ny({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=Uy(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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 o=eu(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$,eC(this.video,"progress")).pipe(Md(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(rC(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let f=this.selectVideoAudioRepresentations();if(!f)return;let[m,S]=f,g=[...this.videoTracksMap.keys()].find(T=>this.videoTracksMap.get(T)?.representation.id===m.id);Yy(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready"?await this.player.initRepresentations(m.id,S?.id,this.params.sourceHls):(await this.player.switchRepresentation("video",m.id,h),S&&await this.player.switchRepresentation("audio",S.id,h))},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.currentAudioRepresentation$.pipe(Ld()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(wd(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.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(Dd(({to:c})=>c==="ready"),Ld());this.subscription.add(eu(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Bd(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(eu(l,this.player.state$.stateChangeEnded$,Bd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=eu(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Bd(["init"])).pipe(ZB(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:zi,t=this.params.tuning.useNewAutoSelectVideoTrack?Ur:Fr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Nr,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:w})=>w===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=this.player.bufferLength$.getValue(),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current: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 x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{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}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Gy.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),Re(this.video),this.tracer.end()}};var pp=D(Gi(),1);var{NativeAbortSignal:n2,NativeAbortController:o2}=function(s){return{NativeAbortSignal:s.AbortSignal,NativeAbortController:s.AbortController}}(typeof self<"u"?self:global);function bT(s){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=s,e}function gT(s){if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason"),Object.defineProperty(s,"name",{value:"AbortError"})}catch{s=new Error("This operation was aborted"),s.name="AbortError"}return s}var tu=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Hr=class extends tu{constructor(){super(),this.listeners||tu.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 Yi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Yi;function i(){t.abort(this.reason),r()}function r(){for(let a of e)a.removeEventListener("abort",i)}for(let a of e)if(a.aborted){t.abort(a.reason);break}else a.addEventListener("abort",i);return t.signal}},Yi=class{constructor(){Object.defineProperty(this,"signal",{value:new Hr,writable:!0,configurable:!0})}abort(e){let t=gT(e),i=bT(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Yi.prototype[Symbol.toStringTag]="AbortController",Hr.prototype[Symbol.toStringTag]="AbortSignal");function iu(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Vd(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!iu({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,p){let c;p&&p.signal&&(c=p.signal,delete p.signal);let d=new t(l,p);return c&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),d},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let p=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(p){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(p.aborted)return Promise.reject(c);let d=new Promise((h,f)=>{p.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(u,l)])}return n(u,l)},Request:a}}var le=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window;var PC=()=>"fetch"in le,fa=PC()&&iu({fetch:le.fetch,Request:le.Request,AbortController:le.AbortController}),ST=fa?Vd({fetch:le.fetch,Request:le.Request,AbortController:le.AbortController}):void 0,Ke=fa?ST.fetch:le.fetch,v2=fa?ST.Request:le.Request,j=fa?Yi:le.AbortController,y2=fa?Hr:le.AbortSignal;var lE=D(ke(),1);var NT=D(OT(),1);import{ErrorCategory as ba}from"@vkontakte/videoplayer-shared";var Wr=s=>{if(!s)return{id:"EmptyResponse",category:ba.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:ba.NETWORK,message:`UV Error ${s}`};let e=(0,NT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ba.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ba.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ba.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as nE,assertNonNullable as Wt,ErrorCategory as Ji,filter as up,filterChanged as _0,flattenObject as pu,fromEvent as Zi,getTraceSubscriptionMethod as O0,getWindow as Ya,interval as N0,isNonNullable as gi,isNullable as Ka,map as lp,merge as Xa,now as F0,Subject as Si,Subscription as oE,SubscriptionRemovable as U0,ValueSubject as Z}from"@vkontakte/videoplayer-shared";var It=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var zr=s=>{let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as ga,assertNever as FT,ErrorCategory as Sa,flattenObject as Gr,fromEvent as UT,getWindow as jC,merge as HC,now as va,Subject as Yr,Subscription as WC,ValueSubject as Ud}from"@vkontakte/videoplayer-shared";var De=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Qr=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var su=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new Yr;this.manifestReceived=new Yr;this.firstBytesRequested=new Yr;this.firstBytesReceived=new Yr;this.lastConnectionType$=new Ud(void 0);this.lastConnectionReused$=new Ud(void 0);this.lastRequestFirstBytes$=new Ud(void 0);this.recoverableError$=new Yr;this.error$=new Yr;this.abortAllController=new j;this.subscription=new WC;this.fetchManifest=ga(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=It(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ru);return r?(t.log("success",Gr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Gr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ga(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){let p=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(p,jC().location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),p=E.toString();break}default:FT(t)}this.requestQuic&&(p=It(p));let h=this.abortAllController.signal,f;if(n){let E=new j;if(f=HC(UT(this.abortAllController.signal,"abort"),UT(n,"abort")).subscribe(()=>{try{E.abort()}catch(I){ru(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(I){ru(I)}h=E.signal}let m=0,S=va();d.log("startRequest",Gr({url:p,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested.next();let g=yield this.doFetch(p,{priority:a,headers:c,signal:h}),v=va();if(!g)return d.error("error",{message:"No response in request"}),d.end(),f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-S),!g.ok||!g.body){f?.unsubscribe();let E=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:E}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){f?.unsubscribe();let E=va(),I={requestStartedAt:S,requestEndedAt:E,duration:E-S};return d.log("endRequest",Gr(I)),d.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),this.throughputEstimator?.trackStream(E,u)}let y=T.getReader(),x,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=x?new Uint8Array(x):new Uint8Array(0),w=!1,B=E=>{f?.unsubscribe(),w=!0,ru(E)},P=ga(h,async function*({done:E,value:I}){if(m===0&&(this.lastRequestFirstBytes$.next(va()-S),this.firstBytesReceived.next()),h.aborted){f?.unsubscribe();return}if(!E&&I){if(l&&x)R.set(I,m),m+=I.byteLength;else{let N=new Uint8Array(R.length+I.length);N.set(R),N.set(I,R.length),R=N,m+=I.byteLength}r?.(new DataView(R.buffer),m),yield y?.read().then(P,B)}}.bind(this));yield y?.read().then(P,B),f?.unsubscribe();let F=va(),C={failed:w,requestStartedAt:S,requestEndedAt:F,duration:F-S};return w?(d.error("endRequest",Gr(C)),d.end(),null):(d.log("endRequest",Gr(C)),d.end(),R.buffer)}.bind(this));this.fetchByteRangeRepresentation=ga(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f).map(g=>({networkStatus:"none",bufferStatus:"none",status:"none",time:g.time,byte:g.byte}));return{initMetadata:h,initDataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=ga(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});if(!r)return null;let a=e.segments.map(n=>({...n,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:a}}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return this.fetchTemplateRepresentation(e,i)??null;default:FT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ke(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Sa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Sa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Sa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Sa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Sa.FATAL})}}},ru=s=>{if(!De(s))throw s};var Yd=D(cI(),1),LI=D(oi(),1),DI=D(PI(),1),BI=D(Ge(),1),Kd=D(Bi(),1);var kI=D(ke(),1),Gd=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,kI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as WV,isNullable as $I}from"@vkontakte/videoplayer-shared";var AI=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var RI=s=>{try{let e=HV(),t=s.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:a};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function HV(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
171
+ `;var pi=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 Ko(this.params.fov,this.params.orientation),this.cameraRotationManager=new Xo(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Hy,this.gl.VERTEX_SHADER),i=this.createShader(zy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,l=e+i,p=t+r,c=e-i,d=t+r;return[a,n,o,u,l,p,c,d]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as NB,now as pa,once as FB,Subscription as UB,ValueSubject as Ad,isNonNullable as qB,safeStorage as Rd,filterChanged as jB}from"@vkontakte/videoplayer-shared";var Ut=(s,e,t)=>t*e+(1-t)*s,Pd=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Wy=(s,e,t,i)=>{let r=0,a=t,n=Pd(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};var Jo="stalls_manager_metrics",$d="stalls_manager_abr_params",Qy="stalls_manager_default_tuning_abr_params",Md=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 UB;this.severeStallOccurred$=new Ad(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.duration=e.duration,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let t=(this.tuning.ignoreDynamicAbrForShortVideo?this.tuning.enabled&&this.duration>this.tuning.minTvtToBeCounted:this.tuning.enabled)?this.getStoredData($d):{};return{...this.abrParams,...t}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=pa(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=(pa()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(Qy)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===a&&i===n||(this.removeStoredData($d),this.setStoredData(Qy,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:a,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Jo,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((a,n)=>a+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let a=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(a,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(a=>a.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(a=>a.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(a=>a.containerSizeFactor))};this.setStoredData(Jo,[]),this.setStoredData($d,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:a,abrAdjustingSpeed:n,significantTvt:o}=this.tuning,u=n*Math.min(t/o,1),l=this.abrTuningParams;return e<i-r?l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer-u,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer-u,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor+u,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(l={bitrateFactorAtEmptyBuffer:Math.min(l.bitrateFactorAtEmptyBuffer+u,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(l.bitrateFactorAtFullBuffer+u,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(l.containerSizeFactor-u,this.abrParams.minContainerSizeFactor)}),e>a&&(l={bitrateFactorAtEmptyBuffer:Math.max(l.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(l.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(l.containerSizeFactor,this.abrParams.containerSizeFactor)}),l}getStoredData(e,t="{}"){return JSON.parse(Rd.get(e)??t)}setStoredData(e,t){Rd.set(e,JSON.stringify(t))}removeStoredData(e){Rd.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Jo,"[]"),r=t/e,a=i.length?Ut(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:a};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Jo,i)}updateStallData(){this.providerStartWatchingTimestamp&&!this.isSeeked$.getValue()&&(this.sumStallsDuration+=Math.min(this.lastStallDuration,this.tuning.maxPossibleStallDuration),this.currentStallsCount++)}subscribe(e){this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(e.playing$.pipe(FB()).subscribe(t=>this.providerStartWatchingTimestamp=pa())),this.subscription.add(this.currentStallDuration$.pipe(jB()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:a,ignoreStallsOnSeek:n}=this.tuning;if(NB(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),p=pa(),c=r&&this.currentStallsCount>=r,d=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&p-l>=i+o&&t>=i;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,qB(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&pa()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},a)),this.lastStallDuration=t}))}},jr=Md;import{combine as HB,map as zB,observeElementSize as WB,Subscription as QB,ValueSubject as Ld,noop as GB}from"@vkontakte/videoplayer-shared";var Zo=class{constructor(){this.subscription=new QB;this.pipSize$=new Ld(void 0);this.videoSize$=new Ld(void 0);this.elementSize$=new Ld(void 0);this.pictureInPictureWindowRemoveEventListener=GB}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(WB(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(HB({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(zB(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};import{filter as Gy,map as YB,once as Yy}from"@vkontakte/videoplayer-shared";var hi=({subscription:s,desiredState:e,videoElement$:t,observableVideo:i})=>{if(!$.browser.isSafari)return;let r=0,a=!1;s.add(e.volume.stateChangeStarted$.pipe(YB(()=>{let n=e.volume.getTransition(),o=t.getValue();return!o||!n?!1:!n.to.muted&&o.muted}),Gy(n=>!!n),Yy()).subscribe(()=>{r=performance.now(),a=!0})),s.add(i.playbackRateState$.pipe(Gy(()=>a),Yy()).subscribe(()=>{let n=t.getValue(),o=e.playbackRate.getState();n&&o!==n.playbackRate&&performance.now()-r<1e3&&(n.playbackRate=o)}))};var ha=class{constructor(e){this.subscription=new iC;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ci;this.stallsManager=new jr;this.elementSizeManager=new Zo;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Tt;this.audioTrackSwitchHistory=new Tt;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?.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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(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?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return XB(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new pi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 Qe(e.source.url),this.params=e,this.video=Ae(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(de(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=this.getPlayer(),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;tC(this.observableVideo)&&(this.observableVideo=Me(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Ky.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Dd(c=>!!c.length),Jy()).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(Cd(c=>c.to.state!=="none"),Bd());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.currentBuffer$,e.currentBuffer$),a(this.player.lastRequestFirstBytes$.pipe(Dd(Xy),Jy()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(Cd(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(ot(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),hi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add($e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),h=this.player.getCodecs();if(JB(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(kd(S));let g=[];for(let v of S.representations){let T=qy(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(Yo(m));let S=[];for(let g of m.representations){let v=Uy({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=jy(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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 o=eu(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$,eC(this.video,"progress")).pipe(Dd(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(rC(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition(),h=t.autoVideoTrackSwitching.getState();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let f=this.selectVideoAudioRepresentations();if(!f)return;let[m,S]=f,g=[...this.videoTracksMap.keys()].find(T=>this.videoTracksMap.get(T)?.representation.id===m.id);Xy(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();v&&this.params.output.autoVideoTrackLimits$.next(v.to),c==="manifest_ready"?await this.player.initRepresentations(m.id,S?.id,this.params.sourceHls):(await this.player.switchRepresentation("video",m.id,h),S&&await this.player.switchRepresentation("audio",S.id,h))},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.currentAudioRepresentation$.pipe(Bd()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(kd(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.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(Cd(({to:c})=>c==="ready"),Bd());this.subscription.add(eu(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Vd(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(eu(l,this.player.state$.stateChangeEnded$,Vd(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=eu(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Vd(["init"])).pipe(ZB(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:Wi,t=this.params.tuning.useNewAutoSelectVideoTrack?Ur:Fr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Nr,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:w})=>w===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=this.player.bufferLength$.getValue(),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current: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 x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{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}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ky.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),Re(this.video),this.tracer.end()}};var fp=D(Gi(),1);var{NativeAbortSignal:n2,NativeAbortController:o2}=function(s){return{NativeAbortSignal:s.AbortSignal,NativeAbortController:s.AbortController}}(typeof self<"u"?self:global);function ST(s){let e;try{e=new Event("abort")}catch{typeof document<"u"?document.createEvent?(e=document.createEvent("Event"),e.initEvent("abort",!1,!1)):(e=document.createEventObject(),e.type="abort"):e={type:"abort",bubbles:!1,cancelable:!1}}return e.reason=s,e}function vT(s){if(s===void 0)if(typeof document>"u")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason"),Object.defineProperty(s,"name",{value:"AbortError"})}catch{s=new Error("This operation was aborted"),s.name="AbortError"}return s}var tu=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Hr=class extends tu{constructor(){super(),this.listeners||tu.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 Yi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new Yi;function i(){t.abort(this.reason),r()}function r(){for(let a of e)a.removeEventListener("abort",i)}for(let a of e)if(a.aborted){t.abort(a.reason);break}else a.addEventListener("abort",i);return t.signal}},Yi=class{constructor(){Object.defineProperty(this,"signal",{value:new Hr,writable:!0,configurable:!0})}abort(e){let t=vT(e),i=ST(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Yi.prototype[Symbol.toStringTag]="AbortController",Hr.prototype[Symbol.toStringTag]="AbortSignal");function iu(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Od(s){typeof s=="function"&&(s={fetch:s});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!iu({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(l,p){let c;p&&p.signal&&(c=p.signal,delete p.signal);let d=new t(l,p);return c&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),d},a.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let p=a&&a.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(p){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(p.aborted)return Promise.reject(c);let d=new Promise((h,f)=>{p.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(u,l)])}return n(u,l)},Request:a}}var le=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window;var kC=()=>"fetch"in le,fa=kC()&&iu({fetch:le.fetch,Request:le.Request,AbortController:le.AbortController}),yT=fa?Od({fetch:le.fetch,Request:le.Request,AbortController:le.AbortController}):void 0,Ke=fa?yT.fetch:le.fetch,v2=fa?yT.Request:le.Request,j=fa?Yi:le.AbortController,y2=fa?Hr:le.AbortSignal;var dE=D(Pe(),1);var UT=D(FT(),1);import{ErrorCategory as ba}from"@vkontakte/videoplayer-shared";var zr=s=>{if(!s)return{id:"EmptyResponse",category:ba.PARSER,message:"Empty response"};if(s.length<=2&&s.match(/^\d+$/))return{id:`UVError#${s}`,category:ba.NETWORK,message:`UV Error ${s}`};let e=(0,UT.default)(s).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ba.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(s,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ba.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ba.PARSER,message:"Response is valid XML, but parser failed"}};import{abortable as uE,assertNonNullable as zt,ErrorCategory as Ji,filter as cp,filterChanged as _0,flattenObject as pu,fromEvent as Zi,getTraceSubscriptionMethod as O0,getWindow as Ya,interval as N0,isNonNullable as gi,isNullable as Ka,map as dp,merge as Xa,now as F0,Subject as Si,Subscription as lE,SubscriptionRemovable as U0,ValueSubject as Z}from"@vkontakte/videoplayer-shared";var It=s=>{let e=new URL(s);return e.searchParams.set("quic","1"),e.toString()};var Wr=s=>{let e=s.get("X-Delivery-Type"),t=s.get("X-Reused"),i=e===null?"http1":e??void 0,r=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:r}};import{abortable as ga,assertNever as qT,ErrorCategory as Sa,flattenObject as Gr,fromEvent as jT,getWindow as jC,merge as HC,now as va,Subject as Yr,Subscription as zC,ValueSubject as jd}from"@vkontakte/videoplayer-shared";var De=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);var Qr=s=>{let e=new URL(s);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var su=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested=new Yr;this.manifestReceived=new Yr;this.firstBytesRequested=new Yr;this.firstBytesReceived=new Yr;this.lastConnectionType$=new jd(void 0);this.lastConnectionReused$=new jd(void 0);this.lastRequestFirstBytes$=new jd(void 0);this.recoverableError$=new Yr;this.error$=new Yr;this.abortAllController=new j;this.subscription=new zC;this.fetchManifest=ga(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=It(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(ru);return r?(t.log("success",Gr({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",Gr({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=ga(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){let p=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(p,jC().location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),p=E.toString();break}default:qT(t)}this.requestQuic&&(p=It(p));let h=this.abortAllController.signal,f;if(n){let E=new j;if(f=HC(jT(this.abortAllController.signal,"abort"),jT(n,"abort")).subscribe(()=>{try{E.abort()}catch(I){ru(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(I){ru(I)}h=E.signal}let m=0,S=va();d.log("startRequest",Gr({url:p,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested.next();let g=yield this.doFetch(p,{priority:a,headers:c,signal:h}),v=va();if(!g)return d.error("error",{message:"No response in request"}),d.end(),f?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(v-S),!g.ok||!g.body){f?.unsubscribe();let E=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:E}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){f?.unsubscribe();let E=va(),I={requestStartedAt:S,requestEndedAt:E,duration:E-S};return d.log("endRequest",Gr(I)),d.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),this.throughputEstimator?.trackStream(E,u)}let y=T.getReader(),x,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=x?new Uint8Array(x):new Uint8Array(0),w=!1,B=E=>{f?.unsubscribe(),w=!0,ru(E)},k=ga(h,async function*({done:E,value:I}){if(m===0&&(this.lastRequestFirstBytes$.next(va()-S),this.firstBytesReceived.next()),h.aborted){f?.unsubscribe();return}if(!E&&I){if(l&&x)R.set(I,m),m+=I.byteLength;else{let N=new Uint8Array(R.length+I.length);N.set(R),N.set(I,R.length),R=N,m+=I.byteLength}r?.(new DataView(R.buffer),m),yield y?.read().then(k,B)}}.bind(this));yield y?.read().then(k,B),f?.unsubscribe();let F=va(),C={failed:w,requestStartedAt:S,requestEndedAt:F,duration:F-S};return w?(d.error("endRequest",Gr(C)),d.end(),null):(d.log("endRequest",Gr(C)),d.end(),R.buffer)}.bind(this));this.fetchByteRangeRepresentation=ga(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f).map(g=>({networkStatus:"none",bufferStatus:"none",status:"none",time:g.time,byte:g.byte}));return{initMetadata:h,initDataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=ga(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});if(!r)return null;let a=e.segments.map(n=>({...n,networkStatus:"none",bufferStatus:"none",status:"none",size:void 0}));return{initMetadata:null,initDataView:new DataView(r),segments:a}}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Wr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return this.fetchTemplateRepresentation(e,i)??null;default:qT(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await Ke(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Sa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Sa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Sa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Sa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:Sa.FATAL})}}},ru=s=>{if(!De(s))throw s};var Xd=D(pI(),1),BI=D(oi(),1),CI=D(AI(),1),VI=D(Ge(),1),Jd=D(Bi(),1);var RI=D(Pe(),1),Kd=s=>{let e=s.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,a,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,a,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[a,n]=r.toUpperCase(),o=a+n;return(0,RI.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as zV,isNullable as LI}from"@vkontakte/videoplayer-shared";var $I=s=>{if(s.includes("/")){let e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var MI=s=>{try{let e=HV(),t=s.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{r[u[0]]=u.slice(2)})}let a=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:a};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function HV(){let s="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<langtag>${`
172
172
  (?<language>${`(?:[a-z]{2,3}(?:-${s})?|[a-z]{4}|[a-z]{5,8})`})
173
173
  (-(?<script>[a-z]{4}))?
174
174
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
175
175
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
176
176
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
177
177
  (?:-(?<privateuse>(?:${e})))?
178
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var MI=s=>{if(!s?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},tt=(s,e)=>{let t=s;t=(0,Yd.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,LI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Yd.default)(t,n,(o,u)=>$I(a)?o:$I(u)?a:(0,DI.default)(a,parseInt(u,10),"0"))}return t},Jr=(s,e)=>{let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(B=>B.textContent?.trim()??""),o=(0,BI.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),p=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let g,v=a.getAttribute("mediaPresentationDuration"),T=[...a.getElementsByTagName("Period")],y=T.reduce((B,P)=>({...B,[P.id]:P.children}),{}),x=T.reduce((B,P)=>({...B,[P.id]:P.getAttribute("duration")}),{});v?g=MI(v):(0,Kd.default)(x).filter(B=>B).length&&!u?g=(0,Kd.default)(x).reduce((B,P)=>B+(MI(P)??0),0):m&&(g=parseInt(m,10));let A=0,R=a.getAttribute("profiles")?.split(",")??[];for(let B of T.map(P=>P.id))for(let P of y[B]){let F=P.getAttribute("id")??"id"+(A++).toString(10),C=P.getAttribute("mimeType")??"",E=P.getAttribute("codecs")??"",I=P.getAttribute("contentType")??C?.split("/")[0],N=P.getAttribute("profiles")?.split(",")??[],L=RI(P.getAttribute("lang")??"")??{},H=P.querySelector("Label")?.textContent?.trim()??void 0,X=P.querySelectorAll("Representation"),re=P.querySelector("SegmentTemplate"),ce=P.querySelector("Role")?.getAttribute("value")??void 0,Ie=I,Ee={id:F,language:L.language,isDefault:ce==="main",label:H,codecs:E,hdr:Ie==="video"&&Gd(E),mime:C,representations:[]};for(let W of X){let q=W.getAttribute("lang")??void 0,we=H??P.getAttribute("label")??W.getAttribute("label")??void 0,Ce=W.querySelector("BaseURL")?.textContent?.trim()??"",be=new URL(Ce||o,e).toString(),at=W.getAttribute("mimeType")??C,Zt=W.getAttribute("codecs")??E??"",pt;if(I==="text"){let Xe=W.getAttribute("id")||"",ei=L.privateuse?.includes("x-auto")||Xe.includes("_auto"),ht=W.querySelector("SegmentTemplate");if(ht){let Ts={representationId:W.getAttribute("id")??void 0,bandwidth:W.getAttribute("bandwidth")??void 0},Dn=parseInt(W.getAttribute("bandwidth")??"",10)/1e3,Bn=parseInt(ht.getAttribute("startNumber")??"",10)??1,cr=parseInt(ht.getAttribute("timescale")??"",10),Ju=ht.querySelectorAll("SegmentTimeline S")??[],dr=ht.getAttribute("media");if(!dr)continue;let Cn=[],Vn=0,_n="",pr=0,Is=Bn,Ve=0;for(let ft of Ju){let Pi=parseInt(ft.getAttribute("d")??"",10),nt=parseInt(ft.getAttribute("r")??"",10)||0,ti=parseInt(ft.getAttribute("t")??"",10);Ve=Number.isFinite(ti)?ti:Ve;let ki=Pi/cr*1e3,hr=Ve/cr*1e3;for(let xt=0;xt<nt+1;xt++){let ii=tt(dr,{...Ts,segmentNumber:Is.toString(10),segmentTime:(Ve+xt*Pi).toString(10)}),fr=(hr??0)+xt*ki,ws=fr+ki;Is++,Cn.push({time:{from:fr,to:ws},url:ii})}Ve+=(nt+1)*Pi,Vn+=(nt+1)*ki}pr=Ve/cr*1e3,_n=tt(dr,{...Ts,segmentNumber:Is.toString(10),segmentTime:Ve.toString(10)});let Es={time:{from:pr,to:1/0},url:_n},Ct={type:"template",baseUrl:be,segmentTemplateUrl:dr,initUrl:"",totalSegmentsDurationMs:Vn,segments:Cn,nextSegmentBeyondManifest:Es,timescale:cr};pt={id:Xe,kind:"text",segmentReference:Ct,profiles:[],duration:g,bitrate:Dn,mime:"",codecs:"",width:0,height:0,isAuto:ei}}else pt={id:Xe,isAuto:ei,kind:"text",url:be}}else{let Xe=W.getAttribute("contentType")??at?.split("/")[0]??I,ei=P.getAttribute("profiles")?.split(",")??[],ht=parseInt(W.getAttribute("width")??"",10),Ts=parseInt(W.getAttribute("height")??"",10),Dn=parseInt(W.getAttribute("bandwidth")??"",10)/1e3,Bn=W.getAttribute("frameRate")??"",cr=W.getAttribute("quality")??void 0,Ju=Bn?AI(Bn):void 0,dr=W.getAttribute("id")??"id"+(A++).toString(10),Cn=Xe==="video"?`${Ts}p`:Xe==="audio"?`${Dn}Kbps`:Zt,Vn=`${dr}@${Cn}`,_n=[...R,...N,...ei],pr,Is=W.querySelector("SegmentBase"),Ve=W.querySelector("SegmentTemplate")??re;if(Is){let Ct=W.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ft,Pi]=Ct.split("-").map(ii=>parseInt(ii,10)),nt={from:ft,to:Pi},ti=W.querySelector("SegmentBase")?.getAttribute("indexRange"),[ki,hr]=ti?ti.split("-").map(ii=>parseInt(ii,10)):[],xt=ti?{from:ki,to:hr}:void 0;pr={type:"byteRange",url:be,initRange:nt,indexRange:xt}}else if(Ve){let Ct={representationId:W.getAttribute("id")??void 0,bandwidth:W.getAttribute("bandwidth")??void 0},ft=parseInt(Ve.getAttribute("timescale")??"",10),Pi=Ve.getAttribute("initialization")??"",nt=Ve.getAttribute("media"),ti=parseInt(Ve.getAttribute("startNumber")??"",10)??1,ki=tt(Pi,Ct);if(!nt)throw new ReferenceError("No media attribute in SegmentTemplate");let hr=Ve.querySelectorAll("SegmentTimeline S")??[],xt=[],ii=0,fr="",ws=0;if(hr.length){let On=ti,mt=0;for(let mr of hr){let Pt=parseInt(mr.getAttribute("d")??"",10),Ai=parseInt(mr.getAttribute("r")??"",10)||0,Nn=parseInt(mr.getAttribute("t")??"",10);mt=Number.isFinite(Nn)?Nn:mt;let Zu=Pt/ft*1e3,zw=mt/ft*1e3;for(let Fn=0;Fn<Ai+1;Fn++){let Qw=tt(nt,{...Ct,segmentNumber:On.toString(10),segmentTime:(mt+Fn*Pt).toString(10)}),fh=(zw??0)+Fn*Zu,Gw=fh+Zu;On++,xt.push({time:{from:fh,to:Gw},url:Qw})}mt+=(Ai+1)*Pt,ii+=(Ai+1)*Zu}ws=mt/ft*1e3,fr=tt(nt,{...Ct,segmentNumber:On.toString(10),segmentTime:mt.toString(10)})}else if(WV(g)){let mt=parseInt(Ve.getAttribute("duration")??"",10)/ft*1e3,mr=Math.ceil(g/mt),Pt=0;for(let Ai=1;Ai<mr;Ai++){let Nn=tt(nt,{...Ct,segmentNumber:Ai.toString(10),segmentTime:Pt.toString(10)});xt.push({time:{from:Pt,to:Pt+mt},url:Nn}),Pt+=mt}ws=Pt,fr=tt(nt,{...Ct,segmentNumber:mr.toString(10),segmentTime:Pt.toString(10)})}let Ww={time:{from:ws,to:1/0},url:fr};pr={type:"template",baseUrl:be,segmentTemplateUrl:nt,initUrl:ki,totalSegmentsDurationMs:ii,segments:xt,nextSegmentBeyondManifest:Ww,timescale:ft}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Xe||!at)continue;let Es={video:"video",audio:"audio",text:"text"}[Xe];if(!Es)continue;Ie||=Es,pt={id:Vn,kind:Es,segmentReference:pr,profiles:_n,duration:g,bitrate:Dn,mime:at,codecs:Zt,width:ht,height:Ts,fps:Ju,quality:cr}}Ee.language||=q,Ee.label||=we,Ee.mime||=at,Ee.codecs||=Zt,Ee.hdr||=Ie==="video"&&Gd(Zt),Ee.representations.push(pt)}if(Ie){let W=r[Ie].find(q=>q.id===Ee.id);if(W&&Ee.representations.every(q=>q.segmentReference.type==="template"))for(let q of W.representations){let we=Ee.representations.find(at=>at.id===q.id);if(!we)continue;let Ce=we.segmentReference,be=q.segmentReference;be.segments.push(...Ce.segments),be.nextSegmentBeyondManifest=Ce.nextSegmentBeyondManifest}else r[Ie].push(Ee)}}return{duration:g,streams:r,baseUrls:n,live:S}};var ou=D(Ge(),1),Xd=D(ke(),1);import{assertNever as uu}from"@vkontakte/videoplayer-shared";var nu=s=>{let{webmDecodingInfo:e}=$.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:uu(s)}},CI=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...nu(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if($.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...nu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...nu(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...nu(s),...a,"HLS","HLS_ONDEMAND"];default:uu(e)}if($.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:uu(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},VI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=$.device.isMac&&$.browser.isSafari;if($.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:uu(s)}else $.video.nativeHlsSupported&&!u&&!$.browser.isChromiumBased?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Jd=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Zr=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,ou.default)(t.value.split("."),0)}for(let t of s){let i=(0,ou.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,ou.default)(e.value.split("."),0)},es=s=>{let e=s.map(i=>fi(i)),{codecs:t}=$.video;return YV().filter(i=>{if((0,Xd.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},ts=s=>{let e=s.map(i=>fi(i)),{codecs:t}=$.video;return KV().filter(i=>{if((0,Xd.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},fi=s=>s.split(".")[0].replace("0",""),YV=()=>["av1","vp9","hev1","avc1"],KV=()=>["opus","mp4a"];var KI=D(Ge(),1);var XV=(s,e={})=>{let i=e.timeout||1,r=performance.now();return le.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},JV=s=>le.clearTimeout(s),_I=s=>typeof s=="function"&&s?.toString().endsWith("{ [native code] }"),OI=!_I(le.requestIdleCallback)||!_I(le.cancelIdleCallback),Lt=OI?XV:le.requestIdleCallback,lt=OI?JV:le.cancelIdleCallback;import{abortable as sp,assertNonNullable as Dt,ErrorCategory as v0,fromEvent as y0,getExponentialDelay as T0,getWindow as YI,isHigher as I0,isNonNullable as oe,isNullable as ye,once as E0,Subject as w0,Subscription as x0,ValueSubject as za}from"@vkontakte/videoplayer-shared";var NI=D(Ge(),1);var lu=s=>s.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,a;i===0?(this.size=void 0,this.valid=!1,a=void 0):i===1?(this.size=void 0,this.valid=!1,a=void 0):i>e.byteLength?(this.size=i,this.valid=!1,a=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,a=i-this.cursor),this.content=new DataView(e.buffer,r,a)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var is=class extends Q{};import{assertNever as ZV}from"@vkontakte/videoplayer-shared";var ya=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:ZV(e)}}};var Ta=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 a=this.readString(4);this.compatibleBrands.push(a)}}};var Ia=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=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 Ea=class extends J{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var wa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xa=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var Ki=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var Pa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ka=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Aa=class extends J{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ra=class extends J{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var $a=class extends J{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 Ma=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var La=class extends J{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 Da=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ba=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ca=class extends J{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Va=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _a=class extends J{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 Oa=class extends J{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 Na=class extends J{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Fa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ua=class extends J{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 qa=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 t0={ftyp:Ta,moov:Ia,mvhd:Ea,moof:wa,mdat:xa,sidx:Ki,trak:Pa,mdia:Ma,mfhd:Ca,tkhd:La,traf:Va,tfhd:_a,tfdt:Oa,trun:Na,minf:Da,sv3d:ka,st3d:Aa,prhd:Ra,proj:Ba,equi:$a,uuid:ya,stbl:Fa,stsd:Ua,avc1:qa,unknown:is},jt=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!lu(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=t0[e];return i?new i(t,new s):new is(t,new s)}};var mi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{lu(t)&&(this.index[t.type]??=[],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 r0=new TextDecoder("ascii"),s0=s=>r0.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",a0=s=>{let e=new Ki(s,new jt),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},n0=(s,e)=>{let i=new jt().parse(s),r=new mi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},o0=s=>{let t=new jt().parse(s),i=new mi(t),r={},a=i.findAll("uuid"),n=(0,NI.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},u0=s=>{let t=new jt().parse(s);return new mi(t).find("sidx")?.timescale},l0=(s,e)=>{let i=new jt().parse(s),a=new mi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},c0=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new jt().parse(s),r=new mi(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},FI={validateData:s0,parseInit:c0,getIndexRange:()=>{},parseSegments:a0,parseFeedableSegmentChunk:n0,getChunkEndTime:l0,getServerLatencyTimestamps:o0,getTimescaleFromIndex:u0};var Ha=D(ke(),1);import{assertNonNullable as Zd,isNonNullable as HI,isNullable as p0}from"@vkontakte/videoplayer-shared";import{assertNever as d0}from"@vkontakte/videoplayer-shared";var UI={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"}},qI=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ja(s,t),r=i in UI,a=r?UI[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,p=ja(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+d):h=new DataView(s.buffer,s.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},ja=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Et=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return ja(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:d0(e)}},Xi=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=qI(i);if(!e(r))return;r.type==="master"&&Xi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},jI=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=qI(s);return Xi(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Et(o,n):a===17026?t=Et(o,n):a===17029&&(i=Et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var WI=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],h0=[231,22612,22743,167,171,163,160,175],f0=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,p=!1,c=0;return Xi(s,({tag:d,type:h,value:f,valueSize:m})=>{if(d===21419){let S=Et(f,h);l=ja(S)}else d!==21420&&(l=void 0);return d===408125543?(e=f.byteOffset,t=f.byteOffset+m):d===357149030?a=!0:d===290298740?n=!0:d===2807729?i=Et(f,h):d===17545?r=Et(f,h):d===21420&&l===475249515?u=Et(f,h):d===374648427?Xi(f,({tag:S,type:g,value:v})=>S===30321?(p=Et(v,g)===1,!1):!0):a&&n&&(0,Ha.default)(WI,d)&&(o=!0),!o}),Zd(e,"Failed to parse webm Segment start"),Zd(t,"Failed to parse webm Segment end"),Zd(r,"Failed to parse webm Segment duration"),i=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:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},m0=s=>{if(p0(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},b0=(s,e)=>{let t=!1,i=!1,r=o=>HI(o.time)&&HI(o.position),a=[],n;return Xi(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Et(l,u));break;case 183:break;case 241:n&&(n.position=Et(l,u));break;default:t&&(0,Ha.default)(WI,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:p}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},g0=s=>{let e=0,t=!1;try{Xi(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ha.default)(h0,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,Ha.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},zI={validateData:jI,parseInit:f0,getIndexRange:m0,parseSegments:b0,parseFeedableSegmentChunk:g0};var ct=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return zI;case"mp4":return FI}}throw new ReferenceError(`Unsupported mime type ${s}`)};var ep=D(Ge(),1);import{videoSizeToQuality as S0}from"@vkontakte/videoplayer-shared";var bi=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Mt(a):void 0)??S0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},Wa=({id:s,bitrate:e})=>({id:s,bitrate:e}),QI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),GI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),tp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,ep.default)(i.split("."),0),isDefault:r}),ip=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,ep.default)(r.split("."),0)}),rp=s=>"url"in s,it=s=>s.type==="template";var rs=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,manifest:o}){this.error$=new w0;this.playingRepresentation$=new za(void 0);this.playingRepresentationInit$=new za(void 0);this.currentSegmentLength$=new za(0);this.onLastSegment$=new za(!1);this.fullyBuffered$=new za(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new j;this.downloadAbortController=new j;this.subscription=new x0;this.startWith=sp(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Dt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=ct(t.mime),this.nativeBufferManager.init(t.mime,t.codecs),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Dt(i,"No init buffer for starting representation"),Dt(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a)}.bind(this));this.switchTo=sp(this.destroyAbortController.signal,async function*(e,t=!0){if(ye(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);Dt(r,`No such representation ${e}`),Dt(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let a=this.initData.get(r.id),n=this.segments.get(r.id);Dt(a,"No init buffer for switching representation"),Dt(n,"No segments for switching representation");let o=this.getCurrentPosition()??0,u=c=>c.segment.networkStatus!=="downloaded"||c.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,l=c=>{let d=this.representations.get(c.representationId);return Dt(d,"No itemRepresentation for previous track before switch"),c.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(d,r)},p=c=>t?u(c)&&l(c):u(c);this.bufferPlaybackQueue.filter(p).forEach(c=>c.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(c=>!p(c)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=sp(this.downloadAbortController.signal,async function*(){let e=T0(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=YI();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add(y0(i,"online").pipe(E0()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=a,this.getCurrentPosition=n,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=o?.baseUrls??[],this.representations=new Map(i.map(u=>[u.id,u]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){ye(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return oe(t)&&oe(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from}getRepresentationInitialTime(){return ye(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if(ye(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,KI.default)(e,-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=YI();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.__polyfill_cancelIdleCallback_h3d765enk1n)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_h3d765enk1n(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=bi(e),a=bi(t);i=oe(r)&&oe(a)&&I0(a.quality,r.quality)}else if(this.kind==="audio"){let r=Wa(e),a=Wa(t);i=oe(r?.bitrate)&&oe(a?.bitrate)&&a.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,Lt(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),a;this.initData.has(e.id)&&this.segments.has(e.id)?a=Promise.resolve():oe(r)?a=r:a=this.loadInit(e,t,i),await a}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,a);let{initMetadata:n,initDataView:o,segments:u}=await a??{};if(this.initDataPromises.delete(e.id),ye(o)||ye(u))return;n&&this.parsedInitData.set(e.id,n);let l=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,u),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:v0.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if(ye(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(o=>this.withinInterval(e,o.segment.time)),i=this.bufferPlaybackQueue.find(o=>o.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),a=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;oe(r)&&oe(i)&&oe(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),oe(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,n):await this.appendSegmentPartially(i,n)),oe(a)&&this.withinRemoveInterval(e,a.segment.time)&&await this.removeSegment(a,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){Dt(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(ye(t)||ye(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);oe(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let a=this.selectItemsToLoad();await this.loadItems(a,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??"");if(ye(t)||t.length===0)return;let i=t[t?.length-1];ye(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){Dt(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,a;oe(i)&&this.withinInterval(e,i)?(a=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(a=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&a>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;a-=u-o,r++}return n}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return oe(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return oe(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return oe(e)?e-i>t:!1}async appendSegmentFully(e,t){if(ye(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if(ye(e.segment.data)||ye(e.segment.loadedBytes)||ye(e.segment.feedingBytes)||ye(e.segment.fedBytes)||ye(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),a=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;a?.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=a.byteLength,await this.nativeBufferManager.append(a,t)&&(e.segment.fedBytes+=a.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,a=(r-i)/4;await this.nativeBufferManager.remove(0,r-a,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||oe(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let a=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)oe(o.size)&&a>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())oe(o.size)&&a>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size)}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())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as P0,isNonNullable as k0,isNullable as XI,now as JI}from"@vkontakte/videoplayer-shared";var cu=class extends rs{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(a,{...n,priority:i}),this.lastDataObtainedTimestampMs=JI(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),De(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,a=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=a);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(qe(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,a={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:a,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=JI(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:P0.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:a,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||XI(o)||XI(r)||n.aborted))for(let u of e){let{segment:l}=u,p=l.byte.from-r,c=l.byte.to-r,d=c-p+1,h=p<a,f=c<=a;l.size=d,h&&(l.networkStatus==="downloading"&&l.bufferStatus==="none"&&f?(l.data=new DataView(t.buffer,t.byteOffset+p,d),this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u),l.loadedBytes=Math.min(d,a-p),await this.onDownloadItem(u)):k0(l.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&l.networkStatus==="downloading"&&(l.loadedBytes=Math.min(d,a-p),f&&(this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u)),l.loadedBytes>l.feedingBytes&&(l.data=new DataView(t.buffer,t.byteOffset+p,l.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(qe(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as A0,isNullable as ap,now as ZI}from"@vkontakte/videoplayer-shared";var ss=class extends rs{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(a,{...n,priority:i});if(this.lastDataObtainedTimestampMs=ZI(),ap(o))return;let u=e[0],l=new DataView(o);u.segment.size=l.byteLength,u.segment.loadedBytes=l.byteLength,u.segment.data=l,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),De(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(n,o)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=ZI(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:A0.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!qe(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:a}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||ap(u)||ap(o.feedingBytes)||o.networkStatus!=="downloading"||a.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(n)))}updateRepresentationBaseUrl(e,t){if(!qe(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var np=D(Gi(),1),tE=D(Ge(),1);import{assertNonNullable as R0,ErrorCategory as $0,isNullable as Ht,ValueSubject as eE}from"@vkontakte/videoplayer-shared";var du=class extends ss{constructor(t,i,r,a){super(t,i,r,a);this.currentLiveSegmentServerLatency$=new eE(0);this.currentLowLatencySegmentLength$=new eE(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=a.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=(0,np.default)(t.streams[this.kind],r=>r.representations);for(let r of i){if(Ht(r)||!qe(r.segmentReference))return;let a=r.segmentReference.segments.map(p=>({...p,networkStatus:"none",bufferStatus:"none",size:void 0})),n=100,o=this.segments.get(r.id)??[],u=(0,tE.default)(o,-1)?.time.to??0,l=a?.findIndex(p=>u>=p.time.from+n&&u<=p.time.to+n);if(l===-1){let p=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,p)}else{let p=a.slice(l+1);this.segments.set(r.id,[...o,...p])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;R0(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t?.streams[this.kind],r=(0,np.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if(Ht(r))return;let a=this.segments.get(r.id);if(a?.length)return{from:a[0].time.from,to:a[a.length-1].time.to}}getRepresentationInitialTime(){if(Ht(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return Ht(t)||!qe(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),Ht(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:a,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);a&&n&&this.currentLiveSegmentServerLatency$.next(n-a),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if(Ht(t.segment.data)||Ht(r)||!qe(r))return;let a=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:n}=r;t.segment.time.to=a.getChunkEndTime(i,n)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!qe(a))return;let n=this.segments.get(r.id)??[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.from));if(o?.isCurrentLowLatency&&(o.time.to=t.segment.time.to,i=o.time.to-o.time.from,o.isCurrentLowLatency=!1),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let l=Math.round(t.segment.time.to*a.timescale/1e3).toString(10),p=tt(a.segmentTemplateUrl,{segmentTime:l});n.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:p,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){try{let a=this.tuning.dash.useFetchPriorityHints?i:"auto",n=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,a);this.initDataPromises.set(t.id,n);let{initMetadata:o,initDataView:u,segments:l}=await n??{};if(this.initDataPromises.delete(t.id),Ht(u)||Ht(l))return;o&&this.parsedInitData.set(t.id,o);let p=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,p);let c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(t.id,c),this.failedDownloads=0}catch(a){r&&this.error$.next({id:"LoadInits",category:$0.WTF,message:"loadInit threw",thrown:a})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],n=0,o=i.length-1;do a.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[a[0]]:a}};var Qa=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new du(e,t,i,r):qe(i[0].segmentReference)?new ss(e,t,i,r):new cu(e,t,i,r)}};import{ErrorCategory as D0,fromEvent as B0,isNullable as as,Subject as C0,Subscription as V0}from"@vkontakte/videoplayer-shared";import{assertNever as M0,ErrorCategory as iE,Subject as rE}from"@vkontakte/videoplayer-shared";var L0=18,sE=!1;try{sE=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=L0}catch(s){console.error(s)}var op=class{constructor(e){this.bufferFull$=new rE;this.error$=new rE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:iE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};sE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue[0];if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:iE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:M0(t)}}},aE=op;var pe=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var Ga=class{constructor(e){this.error$=new C0;this.subscription=new V0;this.mediaSource=e}init(e,t){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new aE(this.sourceBuffer),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(i=>this.error$.next(i))),this.subscription.add(B0(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:D0.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if(as(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!as(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(as(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return as(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||as(e)?0:pe(this.sourceBuffer.buffered,e)}async abortBuffer(e){return as(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var q0=["timeupdate","progress","play","seeked","stalled","waiting"],uE=["timeupdate","progress","loadeddata","playing","seeked"],hu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new oE;this.subscriptionRemovable=new U0;this.representationSubscription=new oE;this.forceEnded$=new Si;this.destroyController=new j;this.state$=new O("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new Si;this.manifestRequested=new Si;this.manifestReceived=new Si;this.firstBytesRequested=new Si;this.firstBytesReceived=new Si;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.isActiveLive$=new Z(!1);this.isLowLatency$=new Z(!1);this.liveDuration$=new Z(0);this.liveSeekableDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(0);this.liveStreamStatus$=new Z(void 0);this.currentBuffer$=new Z({from:0,to:0});this.bufferLength$=new Z(0);this.nativeBufferLength$=new Z(0);this.liveLatency$=new Z(void 0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.currentStallDuration$=new Z(0);this.videoLastDataObtainedTimestamp$=new Z(0);this.fetcherRecoverableError$=new Si;this.fetcherError$=new Si;this.initRepresentations=nE(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",pu({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={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};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),Wt(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=nE(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Ka(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ji.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new su({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.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ji.PARSER,message:"No playable video representations"})}initBuffer(){Wt(this.element),this.state$.setState("running"),this.subscription.add(Xa(...q0.map(t=>Zi(this.element,t)),Zi(Ya(),"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:Ji.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add(Xa(...e.map(t=>Zi(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add(Zi(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=N0(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:Ji.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){Wt(this.element),Wt(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",pu({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){gi(this.element)&&gi(this.source)&&gi(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&Ya().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),gi(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if(Ka(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){Wt(this.element),Wt(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",pu(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=F0(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,l=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,p=gi(this.videoBufferManager)&&u<a&&r-n>i,c=gi(this.audioBufferManager)&&l<a&&r-o>i;return(p||c)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Ka(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",pu(i)),i}parseManifest(e){try{return Jr(e??"",this.manifestUrlString)}catch(t){let i=Wr(e)??{id:"ManifestParsing",category:Ji.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,l)=>!!(this.element?.canPlayType?.(u)&&_e()?.isTypeSupported?.(`${u}; codecs="${l}"`)||o==="text"),r,a;for(let o of["video","audio"]){let l=e.streams[o].filter(({mime:c,codecs:d})=>i(o,c,d));t[o]=l;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:d})=>d);o==="audio"&&(a=ts(c),p=a[0]),o==="video"&&(r=es(c),this.forceVideoCodec&&(0,lE.default)(r,this.forceVideoCodec)?p=this.forceVideoCodec:p=r[0]),p&&(t[o]=l.filter(({codecs:d})=>fi(d)===p))}else{let c=new Set(l.map(({codecs:d})=>d));p=Zr(c),p&&(t[o]=l.filter(({codecs:d})=>d.startsWith(p)))}if(o==="video"){let c=this.tuning.preferHDR,d=t.video.some(f=>f.hdr),h=t.video.some(f=>!f.hdr);$.display.isHDR&&c&&d?t.video=t.video.filter(f=>f.hdr):h&&(t.video=t.video.filter(f=>!f.hdr))}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:a}),n}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){Wt(this.manifest),Wt(this.element);let a=l=>{this.representationSubscription.add(Zi(l,"error").pipe(up(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ji.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=Er();let n=Ya().document,o=n.createElement("source");if(a(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),ni())if(r){let l=n.createElement("source");a(l),l.type="application/x-mpegurl",l.src=r.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoNativeBufferManager=new Ga(this.source),this.videoBufferManager=Qa.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],gi(i)){this.audioNativeBufferManager=new Ga(this.source);let l=this.manifest.streams.audio.reduce((p,c)=>[...p,...c.representations],[]);this.audioBufferManager=Qa.getBufferManager("audio",this.audioNativeBufferManager,l,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{e&&(this.timeoutSourceOpenId=Ya().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:Ji.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&Ya().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Xa(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),Wt(this.videoBufferManager),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.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add(Xa(...uE.map(e=>Zi(this.element,e))).pipe(lp(e=>this.videoBufferManager?.getPlaybackBufferState()),up(gi),lp(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(Xa(...uE.map(e=>Zi(this.element,e))).pipe(lp(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),_0()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(up(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=O0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if(Ka(this.element)||Ka(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=(this.videoNativeBufferManager?.getBufferState()??[]).find(r=>e>=r.from&&e<=r.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await this.audioBufferManager?.maintain(e)}};import{assertNonNullable as fu,combine as j0,ErrorCategory as H0,filter as cp,filterChanged as W0,fromEvent as z0,isNonNullable as Q0,map as dp,merge as Ja}from"@vkontakte/videoplayer-shared";var mu=class extends hu{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){fu(this.manifest),fu(this.source);let e=[this.manifest.duration??0,...(0,pp.default)((0,pp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],t=>t.representations),t=>{let i=[];return t.duration&&i.push(t.duration),qe(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){fu(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){fu(this.element);let e=Ja(z0(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(cp(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(Ja(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=Ja(...this.bufferManagers.map(a=>a.fullyBuffered$)).pipe(dp(()=>this.bufferManagers.every(a=>a.fullyBuffered$.getValue()))),t=Ja(...this.bufferManagers.map(a=>a.onLastSegment$)).pipe(dp(()=>this.bufferManagers.some(a=>a.onLastSegment$.getValue()))),i=j0({allBuffersFull:e,someBufferEnded:t}).pipe(W0(),dp(({allBuffersFull:a,someBufferEnded:n})=>a&&n),cp(a=>a)),r=()=>{try{this.source?.endOfStream()}catch(a){this.error$.next({id:"EndOfStream",category:H0.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:a})}};this.representationSubscription.add(Ja(this.forceEnded$,i).pipe(cp(a=>Q0(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var ns=class extends ha{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe(G0()).subscribe(a=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:c}])=>c.id===a);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,l=this.params.desiredState.videoStream.getTransition();l&&l.to&&l.to.id===u.id&&this.params.desiredState.videoStream.setState(l.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(Yo(u));let p=this.player.calculateDurationFromSegments();p&&this.params.output.duration$.next(p/1e3)},r))}getPlayer(){return new mu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{assertNever as v_,assertNonNullable as y_,combine as T_,debounce as I_,ErrorCategory as IE,filter as Ip,filterChanged as un,fromEvent as E_,isNonNullable as EE,isNullable as w_,map as ln,merge as cn,observableFrom as ku,once as wE,Subscription as x_,throttle as P_}from"@vkontakte/videoplayer-shared";var TE=D(ke(),1),yp=D(Gi(),1);var Be=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as gp,assertNonNullable as ds,combine as ps,ErrorCategory as dt,filter as wu,filterChanged as an,flattenObject as nn,fromEvent as Gt,getTraceSubscriptionMethod as o_,interval as Sp,isNonNullable as on,isNullable as SE,map as hs,merge as ir,now as vp,Subject as Yt,Subscription as vE,SubscriptionRemovable as u_,tap as l_,throttle as c_,ValueSubject as ee}from"@vkontakte/videoplayer-shared";var gu=D(ke(),1),tr=D(Ge(),1),Su=D(Gi(),1);var fE=D($o(),1);import{assertNever as Y0,ErrorCategory as cE,Subject as dE}from"@vkontakte/videoplayer-shared";var K0=18,pE=!1;try{pE=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=K0}catch(s){console.error(s)}var hp=class{constructor(e,t=!1){this.bufferFull$=new dE;this.error$=new dE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:cE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};pE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:cE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:Y0(t)}}},hE=hp;var os=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as vi,assertNonNullable as je,ErrorCategory as zt,fromEvent as fp,getExponentialDelay as mp,isHigher as X0,isNonNullable as yi,isNullable as he,now as bu,once as J0,Subject as Z0,Subscription as e_,ValueSubject as er}from"@vkontakte/videoplayer-shared";var Za=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new er(0);this.currentLowLatencySegmentLength$=new er(0);this.currentSegmentLength$=new er(0);this.onLastSegment$=new er(!1);this.fullyBuffered$=new er(!1);this.playingRepresentation$=new er(void 0);this.playingRepresentationInit$=new er(void 0);this.error$=new Z0;this.gaps=[];this.subscription=new e_;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new j;this.switchAbortController=new j;this.destroyAbortController=new j;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=vi(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new hE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(fp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:zt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:zt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(fp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:zt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!V(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,os(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);je(i,"No init buffer for starting representation"),je(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=vi(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(he(a)||he(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),je(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();yi(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=vi(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(he(a)||he(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),je(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();yi(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=vi(this.destroyAbortController.signal,async function*(e){let t=(0,Su.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!it(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);je(r,`Representation not found by id ${i}`);let a=this.segments.get(i);je(a,"No segments for starting representation");let n=this.initData.get(i);if(je(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new j,vi(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);je(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(he(o)||he(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),je(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!V(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();yi(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(){!he(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(he(e)||he(this.downloadingRepresentationId)||he(this.playingRepresentationId)||he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||yi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),je(i,`No such representation ${this.playingRepresentationId}`),he(r)||he(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);yi(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=bi(i),f=bi(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&yi(h)&&yi(f)&&X0(h.quality,f.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||S?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let v=[...this.segments.entries()].map(([T,y])=>{let x=y.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;v&&(this.playingRepresentationId=v,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&os(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=[];if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,gu.default)(p,n))d="high";else{let h=(0,tr.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,tr.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;yi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,Su.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,Su.default)(e.streams[this.kind],i=>i.representations);for(let i of t){if(!i||!it(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,tr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,tr.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!it(r))return;let a=this.segments.get(i.id)??[],n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=tt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&lt&&lt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&lt&&lt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:d,time:{from:h,to:f}},m)=>{let S=h<=i&&f>=i,g=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(Be(this.sourceBuffer.buffered,h)&&Be(this.sourceBuffer.buffered,f)))&&g&&T});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){it(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await vi(o,async function*(){let p=mp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=bu(),!p)return;let c=new DataView(p),d=ct(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),De(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())it(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await vi(n,async function*(){let u=mp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),fp(window,"online").pipe(J0()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=bu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),De(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,tr.default)(e,0).byte.from,to:(0,tr.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=bu(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:zt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=bu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:zt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,gu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=ct(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,f=c<=r;if(!h)continue;let m=ct(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===d?S:m.parseFeedableSegmentChunk(S);g?.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Be(this.sourceBuffer.buffered,e.segment.time.from,100)&&Be(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:zt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",rp(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Lt(()=>(0,fE.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?vi(this.destroyAbortController.signal,async function*(){let u=mp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ct(e.mime),{priority:r,ignoreNetworkErrors:a})).then(async u=>{if(!u)return;let{init:l,dataView:p,segments:c}=u,d=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&it(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,u=>{a||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:zt.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}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||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||he(e))return!1;let r=[],a=0,n=u=>{u.sort((p,c)=>p.from-c.from);let l=[u[0]];for(let p=1;p<u.length;p++){let{from:c,to:d}=u[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(u[p])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=n(r);let l=rp(u)?u.size??0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,p=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let d of this.segments.values())for(let h of d)(0,gu.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};o(d)}}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 p of l)p.time.from>=e+u&&p.status==="fed"&&o(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!V(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||!V(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||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||he(e)?0:pe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:a}=this.sourceBuffer;for(let n=0;n<a.length;n++){let o=a.start(n)*1e3,u=a.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(a=>{if(r&&a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Lt(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:zt.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||he(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(p=>p.from-t<=n&&p.to+t>=o),l=e.filter(p=>n>=p.from&&n<p.to-t||o>p.from+t&&o<=p.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:zt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as en,assertNever as mE,fromEvent as bE,merge as t_,now as tn,Subject as us,ValueSubject as bp,flattenObject as ls,ErrorCategory as rn,SubscriptionRemovable as i_}from"@vkontakte/videoplayer-shared";var yu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new us;this.firstBytesManifest$=new us;this.firstBytesRequested$=new us;this.firstBytesReceived$=new us;this.lastConnectionType$=new bp(void 0);this.lastConnectionReused$=new bp(void 0);this.lastRequestFirstBytes$=new bp(void 0);this.recoverableError$=new us;this.error$=new us;this.abortAllController=new j;this.subscription=new i_;this.fetchManifest=en(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=It(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(vu);return r?(t.log("success",ls({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",ls({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=en(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1,ignoreNetworkErrors:p=!1}={}){let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(c,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),c=I.toString();break}default:mE(t)}this.requestQuic&&(c=It(c));let f=this.abortAllController.signal,m;if(n){let I=new j;if(m=t_(bE(this.abortAllController.signal,"abort"),bE(n,"abort")).subscribe(()=>{try{I.abort()}catch(N){vu(N)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(N){vu(N)}f=I.signal}let S=0,g=tn();h.log("startRequest",ls({url:c,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested$.next();let v=yield this.doFetch(c,{priority:a,headers:d,signal:f},{ignoreNetworkErrors:p}),T=tn();if(!v)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(T-g),!v.ok||!v.body){this.unsubscribeAbortSubscription(m);let I=`Fetch error ${v.status}: ${v.statusText}`;return h.error("error",{message:I}),h.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!o){this.unsubscribeAbortSubscription(m);let I=tn(),N={requestStartedAt:g,requestEndedAt:I,duration:I-g};return h.log("endRequest",ls(N)),h.end(),v.arrayBuffer()}let y=v.body;if(o){let I;[y,I]=v.body.tee(),this.throughputEstimator?.trackStream(I,u)}let x=y.getReader(),A,R=parseInt(v.headers.get("content-length")??"",10);Number.isFinite(R)&&(A=R),!A&&i&&(A=i.to-i.from+1);let w=A?new Uint8Array(A):new Uint8Array(0),B=!1,P=I=>{this.unsubscribeAbortSubscription(m),B=!0,vu(I)},F=en(f,async function*({done:I,value:N}){if(S===0&&(this.lastRequestFirstBytes$.next(tn()-g),this.firstBytesReceived$.next()),f.aborted){this.unsubscribeAbortSubscription(m);return}if(!I&&N){if(l&&A)w.set(N,S),S+=N.byteLength;else{let L=new Uint8Array(w.length+N.length);L.set(w),L.set(N,w.length),w=L,S+=N.byteLength}r?.(new DataView(w.buffer),S),yield x?.read().then(F,P)}}.bind(this));yield x?.read().then(F,P),this.unsubscribeAbortSubscription(m);let C=tn(),E={failed:B,requestStartedAt:g,requestEndedAt:C,duration:C-g};return B?(h.error("endRequest",ls(E)),h.end(),null):(h.log("endRequest",ls(E)),h.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=en(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=en(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,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:mE(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await Ke(e,t);if(r.ok)return r;if(i?.ignoreNetworkErrors)return;let a=await r.text(),n=parseInt(a);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:rn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:rn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:rn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:rn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:rn.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},vu=s=>{if(!De(s))throw s};import{isNullable as r_,ValueSubject as gE}from"@vkontakte/videoplayer-shared";var Ti=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new gE(e.initial),this.debounced$=new gE(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Fe(`raw_${t}`),this.smoothedSeries$=new Fe(`smoothed_${t}`),this.reportedSeries$=new Fe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(r_(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 Tu=class extends Ti{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ut(this.slow,e,this.params.emaAlphaSlow),this.fast=Ut(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Iu=class extends Ti{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=xd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ut(this.emaSmoothed,e,this.params.emaAlpha);let i=Hy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Eu=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?Ut(this.smoothed,t,this.params.emaAlpha):t}};var Qt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Tu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Iu({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 Eu({initial:e,label:"liveEdgeDelay",...t})}};var cs=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as s_,ValueSubject as a_}from"@vkontakte/videoplayer-shared";var sn=class s{constructor(e,t){this.currentRepresentation$=new a_(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!s_(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&it(t.segmentReference))}};var d_=["timeupdate","progress","play","seeked","stalled","waiting"],p_=["timeupdate","progress","loadeddata","playing","seeked"];var xu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new vE;this.subscriptionRemovable=new u_;this.representationSubscription=new vE;this.state$=new O("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Yt;this.manifestRequested$=new Yt;this.firstBytesManifest$=new Yt;this.manifestReceived$=new Yt;this.firstBytesRequested$=new Yt;this.firstBytesReceived$=new Yt;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.isActiveLive$=new ee(!1);this.isLowLatency$=new ee(!1);this.liveDuration$=new ee(0);this.liveSeekableDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(0);this.liveStreamStatus$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.fetcherRecoverableError$=new Yt;this.fetcherError$=new Yt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Yt;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new j;this.initManifest=gp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.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=gp(this.destroyController.signal,async function*(){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=Jr(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=Wr(e)??{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,p)=>!!(this.element?.canPlayType?.(l)&&_e()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";if(c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h),c&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let f=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(f).catch(m=>{this.error$.next({id:"updateManifest",category:dt.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:m})})}}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=ts(d),c=n[0]),u==="video"&&(a=es(d),this.forceVideoCodec&&(0,TE.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>fi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=Zr(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);$.display.isHDR&&d&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",nn(o)),o}.bind(this));this.initRepresentations=gp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",nn({initialVideo:e,initialAudio:t,sourceHls:i})),ds(this.manifest),ds(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(Gt(c,"error").pipe(wu(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Er();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),ni())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}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((c,d)=>[...c,...d.representations],[]);if(this.videoBufferManager=new Za("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],on(t)){let c=this.manifest.streams.audio.reduce((d,h)=>[...d,...h.representations],[]);this.audioBufferManager=new Za("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(sn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new sn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ir(...p_.map(c=>Gt(this.element,c))).pipe(hs(c=>this.element?pe(this.element.buffered,this.element.currentTime*1e3):0),an(),l_(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ir(Gt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(an()).subscribe(d=>this.liveStreamEndTimestamp=vp())),this.subscription.add(Gt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:d}=this.tuning.dash;this.livePauseWatchdogSubscription=Sp(d).subscribe(h=>{let f=ai(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,f+d,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Gt(this.element,"play").subscribe(d=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(ps({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(hs(({isActiveLive:d,isLowLatency:h})=>d&&h),an()).subscribe(d=>{this.isManualDecreasePlaybackInLive()||cs(this.element,1)})),this.representationSubscription.add(ps({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(wu(({bufferLength:d,isActiveLive:h,isLowLatency:f})=>h&&f&&!!d)).subscribe(({bufferLength:d})=>this.liveBuffer.next(d))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(d=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!d)return;let h=this.liveSeekableDuration$.getValue()-d/1e3;this.liveSeekableDuration$.next(Math.max(h,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+d/1e3)})),this.representationSubscription.add(ps({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(wu(({isLive:d})=>d),an((d,h)=>h.bufferLength<d.bufferLength),hs(({rtt:d,bufferLength:h,segmentServerLatency:f})=>{let m=ai(this.manifestUrlString,2);return(d/2+h+f+m)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ps({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:d,isActiveLive:h,isLowLatency:f})=>{if(!f||!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=d-m;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(v)>S&&(T=1+Math.sign(v)*g),cs(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(d=>{let h=0;if(d){let f=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add(ps({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(c_(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:d,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,m=ai(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,g=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,y=isFinite(d)?d:h,x=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let R="none";if(x?R="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),R="active_low_latency"):m!==0&&y<g?R="live_forward_buffering":y<g+T&&(R="live_with_target_offset"),isFinite(d)&&(c=d>c?d:c),R==="live_forward_buffering"||R==="live_with_target_offset"){let w=c-(g+v),B=this.normalizeLiveOffset(Math.trunc(m+w/f)),P=Math.abs(B-m),F=0;!d||P<=this.tuning.dashCmafLive.offsetCalculationError?F=m:B>0&&P>this.tuning.dashCmafLive.offsetCalculationError&&(F=B),this.manifestUrlString=ne(this.manifestUrlString,F,2)}(R==="live_with_target_offset"||R==="live_forward_buffering")&&(c=0,await this.updateLive())},d=>{this.error$.next({id:"updateLive",category:dt.VIDEO_PIPELINE,thrown:d,message:"Failed to update live with subscription"})}))}let u=ir(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(hs(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=ir(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(hs(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=ps({allBuffersFull:u,someBufferEnded:l}).pipe(an(),hs(({allBuffersFull:c,someBufferEnded:d})=>c&&d),wu(c=>c));if(this.representationSubscription.add(ir(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(ir(...this.bufferManagers.map(c=>c.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 c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(d=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){d();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)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),d()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,yp.default)((0,yp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],d=>d.representations),d=>{let h=[];return d.duration&&h.push(d.duration),it(d.segmentReference)&&d.segmentReference.totalSegmentsDurationMs&&h.push(d.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&on(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=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Sp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:dt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new yu({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.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Qt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){ds(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?vp()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){ds(this.element),this.state$.setState("running"),this.subscription.add(ir(...d_.map(e=>Gt(this.element,e)),Gt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:dt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Gt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Gt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Be(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let p=this.currentStallDuration$.getValue();p+=n,this.currentStallDuration$.next(p);let c={timeInWaiting:p},d=vp(),h=100,f=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(f);let m=this.audioBufferManager?.lastDataObtainedTimestamp??0,S=this.videoBufferManager?.getForwardBufferDuration()??0,g=this.audioBufferManager?.getForwardBufferDuration()??0,v=S<h&&d-f>r,T=this.audioBufferManager&&g<h&&d-m>r;if((!t||l)&&((v||T)&&p>r||p>=i))throw new Error(`Stall timeout exceeded: ${p} ms`);if(o&&p%a===0){let y=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(y),this.updateManifest()):this.seekLive(y).catch(x=>{this.error$.next({id:"stallIntervalCallback",category:dt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:x})}),c.liveLastOffset=y}else{let y=this.element.currentTime*1e3;this.videoBufferManager?.maintain(y),this.audioBufferManager?.maintain(y),c.position=y}this.tracer.log("stallIntervalCallback",nn(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Sp(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:dt.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){ds(this.element),ds(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Be(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(SE(this.element)||SE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",nn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){on(this.element)&&on(this.source)&&on(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=o_(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(r&&l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",nn(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as h_,map as f_,observeElementSize as m_,Subscription as b_,ValueSubject as Tp,noop as g_}from"@vkontakte/videoplayer-shared";var Pu=class{constructor(){this.subscription=new b_;this.pipSize$=new Tp(void 0);this.videoSize$=new Tp(void 0);this.elementSize$=new Tp(void 0);this.pictureInPictureWindowRemoveEventListener=g_}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(m_(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(h_({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(f_(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var rr=class{constructor(e){this.subscription=new x_;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ci;this.stallsManager=new jr;this.elementSizeManager=new Pu;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Tt;this.audioTrackSwitchHistory=new Tt;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?.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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return v_(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new pi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 Qe(e.source.url),this.params=e,this.video=Ae(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(de(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 xu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;w_(this.observableVideo)&&(this.observableVideo=Me(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:IE.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Ip(c=>!!c.length),wE()).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(ln(c=>c.to.state!=="none"),un());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Ip(EE),wE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(ln(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(ot(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),hi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add($e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),h=this.player.getCodecs();if(y_(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(tp(S));let g=[];for(let v of S.representations){let T=Wa(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(ip(m));let S=[];for(let g of m.representations){let v=bi({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=QI(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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 o=cn(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$,E_(this.video,"progress")).pipe(Ip(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(P_(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[f,m]=h,S=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===f.id);EE(S)&&(this.stallsManager.lastVideoTrackSelected=S);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(f.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),m){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,v)}},r)),this.subscription.add(T_({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:cn(ku([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(ln(c=>c.to)))}).pipe(ln(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),un()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),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(un()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(ip(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(un()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(tp(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.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(ln(({to:c})=>c==="ready"),un());this.subscription.add(cn(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ku(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(cn(l,this.player.state$.stateChangeEnded$,ku(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=cn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ku(["init"])).pipe(I_(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:zi,t=this.params.tuning.useNewAutoSelectVideoTrack?Ur:Fr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Nr,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:w})=>w===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=pe(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current: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 x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{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}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:IE.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),Re(this.video),this.tracer.end()}};var dn=class extends rr{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 Ep,merge as xE,filter as PE,filterChanged as kE,isNullable as wp,map as AE,ValueSubject as xp,isNonNullable as k_}from"@vkontakte/videoplayer-shared";var pn=class extends rr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new xp(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(kE()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.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(a.isLowLatency.stateChangeEnded$.pipe(AE(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Ep({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(AE(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u*1e3+l+t:void 0)).subscribe(i.liveTime$)).add(Ep({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:xE(r.playbackRateState$,new xp(1))}).pipe(PE(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||wp(p)||(t=u-p)})).add(Ep({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:xE(r.playbackRateState$,new xp(1))}).pipe(kE((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||wp(u)||wp(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=GI(u);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(PE(u=>k_(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as tO,assertNonNullable as iO,combine as rO,debounce as sO,ErrorCategory as WE,filter as Up,filterChanged as In,fromEvent as aO,isNonNullable as zE,isNullable as nO,map as En,merge as wn,observableFrom as Ou,once as QE,Subscription as oO}from"@vkontakte/videoplayer-shared";var HE=D(ke(),1),Np=D(Gi(),1);import{abortable as Cp,assertNonNullable as bs,combine as gs,ErrorCategory as wt,filter as Cu,filterChanged as vn,flattenObject as yn,fromEvent as Bt,getTraceSubscriptionMethod as H_,interval as Vp,isNonNullable as Tn,isNullable as qE,map as Ss,merge as ur,now as _p,Subject as Kt,Subscription as Op,SubscriptionRemovable as W_,tap as z_,throttle as jE,ValueSubject as te}from"@vkontakte/videoplayer-shared";var Mu=D(ke(),1),or=D(Ge(),1),Lu=D(Gi(),1);var OE=D($o(),1);import{assertNever as A_,ErrorCategory as RE,Subject as $E}from"@vkontakte/videoplayer-shared";var R_=18,ME=!1;try{ME=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=R_}catch(s){console.error(s)}var Pp=class{constructor(e,t=!1){this.bufferFull$=new $E;this.error$=new $E;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:RE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};ME&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:RE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:A_(t)}}},LE=Pp;import{abortable as Ii,assertNonNullable as He,ErrorCategory as ar,fromEvent as Mp,getExponentialDelay as Lp,isHigher as B_,isNonNullable as Ei,isNullable as fe,now as $u,once as C_,Subject as V_,Subscription as __,ValueSubject as nr}from"@vkontakte/videoplayer-shared";var kp=D(Ge(),1);import{videoSizeToQuality as $_,throttleFn as M_}from"@vkontakte/videoplayer-shared";var hn=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Mt(a):void 0)??$_({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},DE=({id:s,bitrate:e})=>({id:s,bitrate:e}),BE=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),CE=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),Ap=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,kp.default)(i.split("."),0),isDefault:r}),Rp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,kp.default)(r.split("."),0)}),$p=s=>"url"in s,rt=s=>s.type==="template";var VE=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},sr=(s,e)=>{for(let t of s)if(e(t))return t;return null},_E=s=>{let e=!1,t=M_(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as L_,Subscription as D_}from"@vkontakte/videoplayer-shared";var Au=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var Ru=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new D_;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(L_(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!V(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Au(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var fn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new nr(0);this.currentLowLatencySegmentLength$=new nr(0);this.currentSegmentLength$=new nr(0);this.onLastSegment$=new nr(!1);this.fullyBuffered$=new nr(!1);this.playingRepresentation$=new nr(void 0);this.playingRepresentationInit$=new nr(void 0);this.error$=new V_;this.gaps=[];this.subscription=new __;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new j;this.switchAbortController=new j;this.destroyAbortController=new j;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Ii(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);He(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new LE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.sourceBufferBufferedDiff=new Ru(this.mediaSource,this.sourceBuffer),this.subscription.add(Mp(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Mp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ar.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!V(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,os(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=pe(this.sourceBuffer.buffered,o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);He(i,"No init buffer for starting representation"),He(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Ii(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(fe(a)||fe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),He(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Ei(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ii(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(fe(a)||fe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),He(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Ei(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ii(this.destroyAbortController.signal,async function*(e){let t=(0,Lu.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!rt(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);He(r,`Representation not found by id ${i}`);let a=this.segments.get(i);He(a,"No segments for starting representation");let n=this.initData.get(i);if(He(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new j,Ii(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);He(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(fe(o)||fe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),He(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Ei(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!fe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(fe(e)||fe(this.downloadingRepresentationId)||fe(this.playingRepresentationId)||fe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Ei(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(He(t,`No such representation ${this.downloadingRepresentationId}`),He(i,`No such representation ${this.playingRepresentationId}`),fe(r)||fe(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);Ei(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=hn(i),f=hn(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Ei(h)&&Ei(f)&&B_(h.quality,f.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||S?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let v=[...this.segments.entries()].map(([T,y])=>{let x=y.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;v&&(this.playingRepresentationId=v,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&os(this.sourceBuffer.buffered)>=this.bufferLimit){let d=pe(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=null;if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Mu.default)(p,n))d="high";else{let h=(0,or.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p?.length&&pe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,or.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-pe(this.sourceBuffer.buffered,e)<u),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;Ei(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,Lu.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,Lu.default)(e.streams[this.kind],i=>i.representations)??[];for(let i of t){if(!i||!rt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,or.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;He(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!rt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=tt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&lt&&lt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&lt&&lt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:d,time:{from:h,to:f}},m)=>{let S=h<=i&&f>=i,g=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(Be(this.sourceBuffer.buffered,h)&&Be(this.sourceBuffer.buffered,f)))&&g&&T});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){rt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ii(o,async function*(){let p=Lp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=$u(),!p)return;let c=new DataView(p),d=ct(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),De(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())rt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ii(n,async function*(){let u=Lp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Mp(window,"online").pipe(C_()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=$u(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),De(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,or.default)(e,0).byte.from,to:(0,or.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=$u(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:ar.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=$u();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:ar.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Mu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=ct(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,f=c<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(m,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===d?m:ct(o.mime).parseFeedableSegmentChunk(m);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(fe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Be(this.sourceBuffer.buffered,e.segment.time.from,100)&&Be(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ar.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",$p(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Lt(()=>(0,OE.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=Lp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ct(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&rt(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),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:ar.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||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||fe(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{if(a>=t)return;r.push({...o.time});let u=$p(o)?o.size??0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&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,p=0;for(let c of this.segments.values())for(let d of c)(0,Mu.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(u)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===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=VE(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||!V(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||!V(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||!V(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||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||fe(e)?0:pe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let a=Math.round(r.from),n=Math.round(r.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Lt(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:ar.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(fe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||fe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Au(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];u||(u=c-t<=n&&d+t>=o),(n>=c&&n<d-t||o>c+t&&o<=d)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:ar.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,or.default)(e,-1)?.time.to:0)||0}};import{abortable as mn,assertNever as NE,fromEvent as FE,merge as O_,now as bn,Subject as fs,ValueSubject as Dp,flattenObject as ms,ErrorCategory as gn,SubscriptionRemovable as N_}from"@vkontakte/videoplayer-shared";var Bu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new fs;this.firstBytesManifest$=new fs;this.firstBytesRequested$=new fs;this.firstBytesReceived$=new fs;this.lastConnectionType$=new Dp(void 0);this.lastConnectionReused$=new Dp(void 0);this.lastRequestFirstBytes$=new Dp(void 0);this.recoverableError$=new fs;this.error$=new fs;this.abortAllController=new j;this.subscription=new N_;this.fetchManifest=mn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=It(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Du);return r?(t.log("success",ms({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",ms({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=mn(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){let p=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(p,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),p=E.toString();break}default:NE(t)}this.requestQuic&&(p=It(p));let h=this.abortAllController.signal,f;if(n){let E=new j;if(f=O_(FE(this.abortAllController.signal,"abort"),FE(n,"abort")).subscribe(()=>{try{E.abort()}catch(I){Du(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(I){Du(I)}h=E.signal}let m=0,S=bn();d.log("startRequest",ms({url:p,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested$.next();let g=yield this.doFetch(p,{priority:a,headers:c,signal:h}),v=bn();if(!g)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(v-S),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);let E=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:E}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let E=bn(),I={requestStartedAt:S,requestEndedAt:E,duration:E-S};return d.log("endRequest",ms(I)),d.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),this.throughputEstimator?.trackStream(E,u)}let y=T.getReader(),x,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=x?new Uint8Array(x):new Uint8Array(0),w=!1,B=E=>{this.unsubscribeAbortSubscription(f),w=!0,Du(E)},P=mn(h,async function*({done:E,value:I}){if(m===0&&(this.lastRequestFirstBytes$.next(bn()-S),this.firstBytesReceived$.next()),h.aborted){this.unsubscribeAbortSubscription(f);return}if(!E&&I){if(l&&x)R.set(I,m),m+=I.byteLength;else{let N=new Uint8Array(R.length+I.length);N.set(R),N.set(I,R.length),R=N,m+=I.byteLength}r?.(new DataView(R.buffer),m),yield y?.read().then(P,B)}}.bind(this));yield y?.read().then(P,B),this.unsubscribeAbortSubscription(f);let F=bn(),C={failed:w,requestStartedAt:S,requestEndedAt:F,duration:F-S};return w?(d.error("endRequest",ms(C)),d.end(),null):(d.log("endRequest",ms(C)),d.end(),R.buffer)}.bind(this));this.fetchByteRangeRepresentation=mn(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=mn(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=zr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:NE(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Ke(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:gn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:gn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:gn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:gn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:gn.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Du=s=>{if(!De(s))throw s};import{isNullable as F_,ValueSubject as U_}from"@vkontakte/videoplayer-shared";var Sn=class s{constructor(e,t){this.currentRepresentation$=new U_(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!F_(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var Q_=["progress","play","seeked","stalled","waiting"],G_=["timeupdate","progress","loadeddata","playing","seeked"];var Vu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Op;this.subscriptionRemovable=new W_;this.representationSubscription=new Op;this.state$=new O("none");this.currentVideoRepresentation$=new te(void 0);this.currentVideoRepresentationInit$=new te(void 0);this.currentAudioRepresentation$=new te(void 0);this.currentVideoSegmentLength$=new te(0);this.currentAudioSegmentLength$=new te(0);this.error$=new Kt;this.manifestRequested$=new Kt;this.firstBytesManifest$=new Kt;this.manifestReceived$=new Kt;this.firstBytesRequested$=new Kt;this.firstBytesReceived$=new Kt;this.lastConnectionType$=new te(void 0);this.lastConnectionReused$=new te(void 0);this.lastRequestFirstBytes$=new te(void 0);this.currentLiveTextRepresentation$=new te(null);this.isLive$=new te(!1);this.isActiveLive$=new te(!1);this.isLowLatency$=new te(!1);this.liveDuration$=new te(0);this.liveSeekableDuration$=new te(0);this.liveAvailabilityStartTime$=new te(0);this.liveStreamStatus$=new te(void 0);this.bufferLength$=new te(0);this.liveLatency$=new te(void 0);this.liveLoadBufferLength$=new te(0);this.livePositionFromPlayer$=new te(0);this.currentStallDuration$=new te(0);this.videoLastDataObtainedTimestamp$=new te(0);this.fetcherRecoverableError$=new Kt;this.fetcherError$=new Kt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Kt;this.gapWatchdogActive=!1;this.destroyController=new j;this.initManifest=Cp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:wt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Cp(this.destroyController.signal,async function*(){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:wt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Jr(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=Wr(e)??{id:"ManifestParsing",category:wt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,p)=>!!(this.element?.canPlayType?.(l)&&_e()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=ts(d),c=n[0]),u==="video"&&(a=es(d),this.forceVideoCodec&&(0,HE.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>fi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=Zr(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);$.display.isHDR&&d&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",yn(o)),o}.bind(this));this.initRepresentations=Cp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",yn({initialVideo:e,initialAudio:t,sourceHls:i})),bs(this.manifest),bs(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Op,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(Bt(d,"error").pipe(Cu(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:wt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Er();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),ni())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}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((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new fn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Tn(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new fn("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}Sn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Sn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ur(...G_.map(d=>Bt(this.element,d))).pipe(Ss(d=>this.element?pe(this.element.buffered,this.element.currentTime*1e3):0),vn(),z_(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ur(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(vn()).subscribe(h=>this.liveStreamEndTimestamp=_p())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Vp(1e3).subscribe(h=>{let f=ai(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Bt(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(gs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ss(({isActiveLive:h,isLowLatency:f})=>h&&f),vn()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||cs(this.element,1)})),this.representationSubscription.add(gs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Cu(({bufferLength:h,isActiveLive:f,isLowLatency:m})=>f&&m&&!!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 f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(gs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Cu(({isLive:h})=>h),vn((h,f)=>f.bufferLength<h.bufferLength),Ss(({rtt:h,bufferLength:f,segmentServerLatency:m})=>{let S=ai(this.manifestUrlString,2);return(h/2+f+m+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(gs({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:m})=>{if(!m||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-S;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(T)>g&&(y=1+Math.sign(T)*v),cs(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let m=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(gs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(jE(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,S=ai(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,x=isFinite(h)?h:f,A=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),R=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(R);let w="none";if(A?w="active_low_latency":this.isLowLatency$.getValue()&&R?(this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&x<v?w="live_forward_buffering":x<v+y&&(w="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),w==="live_forward_buffering"||w==="live_with_target_offset"){let B=d-(v+T),P=this.normolizeLiveOffset(Math.trunc(S+B/m)),F=Math.abs(P-S),C=0;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?C=S:P>0&&F>this.tuning.dashCmafLive.offsetCalculationError&&(C=P),this.manifestUrlString=ne(this.manifestUrlString,C,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:wt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=ur(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Ss(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=ur(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Ss(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=gs({allBuffersFull:l,someBufferEnded:p}).pipe(vn(),Ss(({allBuffersFull:d,someBufferEnded:h})=>d&&h),Cu(d=>d));if(this.representationSubscription.add(ur(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:wt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(ur(...this.bufferManagers.map(d=>d.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 d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:wt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,Np.default)((0,Np.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),rt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&Tn(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=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Vp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:wt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Bu({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.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Qt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){bs(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?_p()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){bs(this.element),this.state$.setState("running");let e=Bt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(jE(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(ur(...Q_.map(t=>Bt(this.element,t)),Bt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:wt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Bt(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(Bt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Be(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=_p(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&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 h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(f=>{this.error$.next({id:"stallIntervalCallback",category:wt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:f})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",yn(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Vp(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:wt.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){bs(this.element),bs(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Be(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(qE(this.element)||qE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",yn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Tn(this.element)&&Tn(this.source)&&Tn(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=H_(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(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",yn({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as Y_,map as K_,observeElementSize as X_,Subscription as J_,ValueSubject as Fp,noop as Z_}from"@vkontakte/videoplayer-shared";var _u=class{constructor(){this.subscription=new J_;this.pipSize$=new Fp(void 0);this.videoSize$=new Fp(void 0);this.elementSize$=new Fp(void 0);this.pictureInPictureWindowRemoveEventListener=Z_}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(X_(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(Y_({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(K_(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var lr=class{constructor(e){this.subscription=new oO;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ci;this.stallsManager=new jr;this.elementSizeManager=new _u;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Tt;this.audioTrackSwitchHistory=new Tt;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?.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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&k(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return tO(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new pi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 Qe(e.source.url),this.params=e,this.video=Ae(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(de(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 Vu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;nO(this.observableVideo)&&(this.observableVideo=Me(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:WE.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Up(c=>!!c.length),QE()).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(En(c=>c.to.state!=="none"),In());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(Up(zE),QE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(En(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(ot(this.video,t.isLooped,r)),this.subscription.add($e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),h=this.player.getCodecs();if(iO(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(Ap(S));let g=[];for(let v of S.representations){let T=DE(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(Rp(m));let S=[];for(let g of m.representations){let v=hn({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=BE(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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&&_E(o)||null;this.subscription.add(wn(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$,aO(this.video,"progress")).pipe(Up(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let m=sr(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===h.id);zE(m)&&(this.stallsManager.lastVideoTrackSelected=m);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready")await this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,g)}},r)),this.subscription.add(rO({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:wn(Ou([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(En(c=>c.to)))}).pipe(En(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),In()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),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(In()).subscribe(c=>{let d=sr(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Rp(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(In()).subscribe(c=>{let d=sr(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Ap(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.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(En(({to:c})=>c==="ready"),In());this.subscription.add(wn(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ou(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(wn(l,this.player.state$.stateChangeEnded$,Ou(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=wn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ou(["init"])).pipe(sO(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:zi,t=this.params.tuning.useNewAutoSelectVideoTrack?Ur:Fr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Nr,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=sr(this.videoTracksMap.keys(),w=>w.id===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=sr(this.videoStreamsMap.keys(),w=>w.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=pe(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=g?.id&&sr(this.audioStreamsMap.keys(),w=>w.id===g.id)||this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current: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 x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{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}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;A&&R?(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=R):A&&!R&&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(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:WE.DOM,thrown:e}))}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),Re(this.video),this.tracer.end()}};var xn=class extends lr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as qp,merge as GE,filter as YE,filterChanged as KE,isNullable as jp,map as XE,ValueSubject as Hp,isNonNullable as uO}from"@vkontakte/videoplayer-shared";var Pn=class extends lr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Hp(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(KE()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.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(a.isLowLatency.stateChangeEnded$.pipe(XE(u=>u.to)).subscribe(this.player.isLowLatency$)).add(qp({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(XE(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(YE(u=>uO(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(qp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:GE(r.playbackRateState$,new Hp(1))}).pipe(YE(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||jp(p)||(t=u-p)})).add(qp({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:GE(r.playbackRateState$,new Hp(1))}).pipe(KE((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||jp(u)||jp(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=CE(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 JE="X-Playback-Duration",Wp=async s=>{let e=await Ke(s),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(JE)?parseInt(e.headers.get(JE),10):void 0};import{assertNever as vO,combine as yO,debounce as TO,ErrorCategory as Uu,filter as IO,filterChanged as EO,isNonNullable as tw,isNullable as qu,map as iw,merge as wO,observableFrom as xO,Subscription as PO,ValueSubject as Gp,VideoQuality as kO}from"@vkontakte/videoplayer-shared";var Qp=D(gc(),1);import{videoSizeToQuality as lO,getExponentialDelay as cO}from"@vkontakte/videoplayer-shared";var dO=s=>{let e=null;if(s.QUALITY&&(e=Mt(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=lO({width:t,height:i})}return e??null},pO=(s,e)=>{let t=s.split(`
179
- `),i=[],r=[];for(let a=0;a<t.length;a++){let n=t[a],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,Qp.default)(o[1].split(",").map(S=>S.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,c=dO(l),d;l.BANDWIDTH&&(d=parseInt(l.BANDWIDTH,10)/1e3||void 0),!d&&l["AVERAGE-BANDWIDTH"]&&(d=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[S,g]=l.RESOLUTION.split("x").map(v=>parseInt(v,10));S&&g&&(f={width:S,height:g})}let m=new URL(t[++a],e).toString();c&&i.push({id:p,quality:c,url:m,bandwidth:d,size:f,fps:h})}if(u){let l=(0,Qp.default)(u[1].split(",").map(h=>{let f=h.indexOf("=");return[h.substring(0,f),h.substring(f+1)]}).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,d=l.NAME;p&&c&&r.push({type:"internal",id:c,label:d,language:c,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},hO=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),zp=0,ZE=async(s,e=s,t,i)=>{let a=await(await Ke(s,i)).text();zp+=1;try{let{qualityManifests:n,textTracks:o}=pO(a,e);return{qualityManifests:n,textTracks:o}}catch{if(zp<=t.manifestRetryMaxCount)return await hO(cO(zp-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),ZE(s,e,t)}return{qualityManifests:[],textTracks:[]}},Nu=ZE;import{isNonNullable as fO,Subscription as mO,throttle as bO,ValueSubject as ew,Subject as gO,ErrorCategory as SO}from"@vkontakte/videoplayer-shared";var Fu=class{constructor(e,t,i,r,a){this.subscription=new mO;this.abortControllers={destroy:new j,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new ew(null);this.getCurrentTime$=new ew(null);this.error$=new gO;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(bO(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 Ke(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
180
- `),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),p=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+p},url:l}),a=a+p,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(fO(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new j;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??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:SO.WTF,thrown:t,message:e})}};var kn=class{constructor(e){this.subscription=new PO;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Gp([]);this.liveOffset=new ji;this.manifestStartTime$=new Gp(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),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?.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"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(k(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return vO(t)}};this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:kO.INVARIANT,url:this.params.source.url};let t=(i,r)=>Nu(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Fu(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Qe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Uu.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Uu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),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(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Gp(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Uu.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Me(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add($e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ye(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.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(EO(),iw(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(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&tw(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===c);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(de(d.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.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(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(yO({startTime:this.manifestStartTime$.pipe(IO(tw)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(iw(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=wO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,xO(["init"])).pipe(TO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){let e=this.selectManifest();if(qu(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}=t?.to??i??{};for(let[l,p]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,c)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ne(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Wp(n).then(o=>{if(!qu(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(qu(u)||!isFinite(u))&&Ke(n).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let c=new URL(p,n).toString();Wp(c).then(d=>{qu(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ne(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as AO,debounce as RO,ErrorCategory as Yp,fromEvent as Kp,isNonNullable as $O,isNullable as MO,map as rw,merge as sw,observableFrom as aw,Subscription as LO,ValueSubject as nw,VideoQuality as DO}from"@vkontakte/videoplayer-shared";var An=class{constructor(e){this.subscription=new LO;this.videoState=new O("stopped");this.manifests$=new nw([]);this.unmuteAfterBrowserResetsHappened=new nw(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);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?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?k(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return AO(t)}};this.textTracksManager=new Qe(e.source.url),this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:DO.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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Nu(ne(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Yp.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Yp.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Me(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(rw(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),hi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add($e(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&$O(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(de(f.url)))}let c=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(rw(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!$.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(sw(Kp(o,"addtrack"),Kp(o,"removetrack"),Kp(o,"change"),aw(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=sw(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,aw(["init"])).pipe(RO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){let e=this.selectManifest();if(MO(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:a,min:n}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Yp.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var lw=D(oi(),1),Xp=D(Bi(),1),cw=D(Ge(),1);import{assertNever as BO,assertNonNullable as ow,debounce as CO,ErrorCategory as uw,isHigherOrEqual as VO,isLowerOrEqual as _O,isNonNullable as OO,merge as NO,observableFrom as FO,Subscription as UO,map as qO}from"@vkontakte/videoplayer-shared";var Rn=class{constructor(e){this.subscription=new UO;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new Qe;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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?k(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return BO(e)}};this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),(0,lw.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Xp.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:uw.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Me(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(qO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),hi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add($e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ye(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),k(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&OO(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(u),p.playbackRate=u)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),k(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=NO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,FO(["init"])).pipe(CO(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),Re(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;ow(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];ow(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=It(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(de(t))}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:uw.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=ut(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),n=(0,Xp.default)(this.trackUrls).map(l=>l.track);if(!r||!a||Vr(e,n[0].quality,(0,cw.default)(n,-1)?.quality)){i();return}let o=e.max?_O(r,e.max):!0,u=e.min?VO(r,e.min):!0;o&&u||i(e)}};import{assertNever as pw,debounce as zO,merge as hw,observableFrom as QO,Subscription as GO,map as fw,ValueSubject as YO,ErrorCategory as Zp,VideoQuality as KO}from"@vkontakte/videoplayer-shared";import{ErrorCategory as jO}from"@vkontakte/videoplayer-shared";var dw=["stun:videostun.mycdn.me:80"],HO=1e3,WO=3,Jp=()=>null,ju=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=Jp;this.externalStopCallback=Jp;this.externalErrorCallback=Jp;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:dw}]};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:jO.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{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),HO)}normalizeOptions(e={}){let t={stunServerList:dw,maxRetryNumber:WO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var $n=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new YO(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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),k(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&k(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&k(this.params.desiredState.playbackState,"paused");return;default:return pw(e)}};this.subscription=new GO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ae(e.container,e.tuning),this.liveStreamClient=new ju(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),Re(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Zp.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(hw(this.videoState.stateChangeStarted$.pipe(fw(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(fw(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Me(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(Ye(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(()=>{this.videoState.getTransition()?.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($e(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 pw(n.to)}},i)).add(hw(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,QO(["init"])).pipe(zO(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(de(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:KO.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.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:Zp.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),k(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Zp.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var vs=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Mn,assertNonNullable as Xt,ErrorCategory as Hu,filter as yw,isNonNullable as Tw,isNullable as rN,map as sN,merge as aN,once as nN,Subject as ie,Subscription as Iw,ValueSubject as U,flattenObject as eh,devNull as oN,getWindow as uN}from"@vkontakte/videoplayer-shared";import{Observable as XO,map as mw,Subscription as JO,Subject as ZO}from"@vkontakte/videoplayer-shared";var bw=s=>new XO(e=>{let t=new JO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(mw(({from:l,to:p})=>`${l}-${p}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(mw(({type:l})=>l!==void 0)),n=new ZO,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval),_({m:"hangup.set",l,id:o})})),t.add(r.subscribe(()=>{_({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(_({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval),_({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as eN,Subscription as tN,combine as iN,filter as Sw,once as vw}from"@vkontakte/videoplayer-shared";function gw(){return new(window.AudioContext||window.webkitAudioContext)}var ys=class s{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new j;this.subscriptions=new tN;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Sw(a=>!!a.type),vw()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){$.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(iN({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Sw(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),vw()).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=gw();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:s.errorId,category:eN.VIDEO_PIPELINE,message:e?.message??`${s.errorId} exception`,thrown:e})}};var lN={chunkDuration:5e3,maxParallelRequests:5},Ln=class{constructor(e){this.current$=new U({type:void 0});this.providerError$=new ie;this.noAvailableProvidersError$=new ie;this.volumeMultiplierError$=new ie;this.providerOutput={position$:new U(0),duration$:new U(1/0),volume$:new U({muted:!1,volume:1}),availableVideoStreams$:new U([]),currentVideoStream$:new U(void 0),availableVideoTracks$:new U([]),currentVideoTrack$:new U(void 0),availableVideoCodecs$:new U([]),availableAudioStreams$:new U([]),currentAudioStream$:new U(void 0),availableAudioTracks$:new U([]),availableAudioCodecs$:new U([]),currentVideoSegmentLength$:new U(0),currentAudioSegmentLength$:new U(0),isAudioAvailable$:new U(!0),autoVideoTrackLimitingAvailable$:new U(!1),autoVideoTrackLimits$:new U(void 0),currentBuffer$:new U(void 0),currentNativeBuffer$:new U(void 0),isBuffering$:new U(!0),error$:new ie,fetcherError$:new ie,fetcherRecoverableError$:new ie,warning$:new ie,willSeekEvent$:new ie,soundProhibitedEvent$:new ie,seekedEvent$:new ie,loopedEvent$:new ie,endedEvent$:new ie,manifestRequested$:new ie,firstBytesManifest$:new ie,manifestReceived$:new ie,firstBytesRequested$:new ie,firstBytesReceived$:new ie,firstBytesEvent$:new ie,loadedMetadataEvent$:new ie,firstFrameEvent$:new ie,canplay$:new ie,isLive$:new U(void 0),isLiveEnded$:new U(null),canPlayLiveTailBuffer$:new U(!1),isLowLatency$:new U(!1),canChangePlaybackSpeed$:new U(!0),liveTime$:new U(void 0),liveBufferTime$:new U(void 0),liveLatency$:new U(void 0),severeStallOccurred$:new ie,availableTextTracks$:new U([]),currentTextTrack$:new U(void 0),hostname$:new U(void 0),httpConnectionType$:new U(void 0),httpConnectionReused$:new U(void 0),inPiP$:new U(!1),inFullscreen$:new U(!1),element$:new U(void 0),elementVisible$:new U(!0),availableSources$:new U(void 0),is3DVideo$:new U(!1),playbackState$:new U(""),getCurrentTime$:new U(null)};this.subscription=new Iw;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=ql([...VI(this.params.tuning),...CI(this.params.tuning)]).filter(l=>Tw(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,th.default)(r,l)),...t.filter(l=>(0,th.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",eh(a)),this.screenFormatsIterator=new vs(a);let n=[...Jd(!0),...Jd(!1)];this.chromecastFormatsIterator=new vs(n.filter(l=>Tw(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ys.isSupported()&&(this.volumeMultiplierManager=new ys(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){_.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new vs(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(rN(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Hu.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Mn(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Xt(u),this.params.tuning.useNewDashProvider?new xn({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtual&&!$.device.isMobile?new ns({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&$.device.isMobile?new ns({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new dn({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Xt(u),this.params.tuning.useNewDashProvider?new Pn({...o,source:u}):new pn({...o,source:u})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let u=this.applyFailoverHost(t[e]);return Xt(u),new An({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Xt(u),new kn({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Xt(u),new Rn({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Xt(u),new Oy({...o,source:u,config:{...lN,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Xt(u),new $n({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 Mn(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o={meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof Ot){let{chromecastConnector:l}=this.params.dependencies.chromecastInitializer;return Xt(l),new Ns({...o,chromecastConnector:l})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return Xt(u),new ta({...o,connection:u})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Mn(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Mn(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 Mn(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,Ew.default)((0,ih.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new Iw,t=!1,i=0;e.add(aN(this.providerOutput.error$.pipe(yw(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),bw({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(sN(a=>({id:`ProviderHangup:${a}`,category:Hu.WTF,message:`A ${a} 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 a=this.params.desiredState.playbackState.transitionEnded$.pipe(yw(({to:n})=>n==="playing"),nN()).subscribe(()=>t=!0);e.add(a)}));let r=()=>{let a=_.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&uN().console.log(`===== DASH_LIVE DEBUG START ====
178
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var DI=s=>{if(!s?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=i?.[1]==="-"?-1:1,a={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},tt=(s,e)=>{let t=s;t=(0,Xd.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of(0,BI.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Xd.default)(t,n,(o,u)=>LI(a)?o:LI(u)?a:(0,CI.default)(a,parseInt(u,10),"0"))}return t},Jr=(s,e)=>{let i=new DOMParser().parseFromString(s,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],n=Array.from(a.querySelectorAll("MPD > BaseURL").values()).map(B=>B.textContent?.trim()??""),o=(0,VI.default)(n,0)??"",u=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),p=a.getAttribute("publishTime"),c=a.getElementsByTagName("vk:Attrs")[0],d=c?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=c?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,f=c?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,m=c?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;u&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:f==="yes"});let g,v=a.getAttribute("mediaPresentationDuration"),T=[...a.getElementsByTagName("Period")],y=T.reduce((B,k)=>({...B,[k.id]:k.children}),{}),x=T.reduce((B,k)=>({...B,[k.id]:k.getAttribute("duration")}),{});v?g=DI(v):(0,Jd.default)(x).filter(B=>B).length&&!u?g=(0,Jd.default)(x).reduce((B,k)=>B+(DI(k)??0),0):m&&(g=parseInt(m,10));let A=0,R=a.getAttribute("profiles")?.split(",")??[];for(let B of T.map(k=>k.id))for(let k of y[B]){let F=k.getAttribute("id")??"id"+(A++).toString(10),C=k.getAttribute("mimeType")??"",E=k.getAttribute("codecs")??"",I=k.getAttribute("contentType")??C?.split("/")[0],N=k.getAttribute("profiles")?.split(",")??[],L=MI(k.getAttribute("lang")??"")??{},H=k.querySelector("Label")?.textContent?.trim()??void 0,X=k.querySelectorAll("Representation"),re=k.querySelector("SegmentTemplate"),ce=k.querySelector("Role")?.getAttribute("value")??void 0,Ie=I,Ee={id:F,language:L.language,isDefault:ce==="main",label:H,codecs:E,hdr:Ie==="video"&&Kd(E),mime:C,representations:[]};for(let z of X){let q=z.getAttribute("lang")??void 0,we=H??k.getAttribute("label")??z.getAttribute("label")??void 0,Ce=z.querySelector("BaseURL")?.textContent?.trim()??"",be=new URL(Ce||o,e).toString(),at=z.getAttribute("mimeType")??C,Zt=z.getAttribute("codecs")??E??"",pt;if(I==="text"){let Xe=z.getAttribute("id")||"",ei=L.privateuse?.includes("x-auto")||Xe.includes("_auto"),ht=z.querySelector("SegmentTemplate");if(ht){let Ts={representationId:z.getAttribute("id")??void 0,bandwidth:z.getAttribute("bandwidth")??void 0},Dn=parseInt(z.getAttribute("bandwidth")??"",10)/1e3,Bn=parseInt(ht.getAttribute("startNumber")??"",10)??1,cr=parseInt(ht.getAttribute("timescale")??"",10),Ju=ht.querySelectorAll("SegmentTimeline S")??[],dr=ht.getAttribute("media");if(!dr)continue;let Cn=[],Vn=0,_n="",pr=0,Is=Bn,Ve=0;for(let ft of Ju){let ki=parseInt(ft.getAttribute("d")??"",10),nt=parseInt(ft.getAttribute("r")??"",10)||0,ti=parseInt(ft.getAttribute("t")??"",10);Ve=Number.isFinite(ti)?ti:Ve;let Pi=ki/cr*1e3,hr=Ve/cr*1e3;for(let xt=0;xt<nt+1;xt++){let ii=tt(dr,{...Ts,segmentNumber:Is.toString(10),segmentTime:(Ve+xt*ki).toString(10)}),fr=(hr??0)+xt*Pi,ws=fr+Pi;Is++,Cn.push({time:{from:fr,to:ws},url:ii})}Ve+=(nt+1)*ki,Vn+=(nt+1)*Pi}pr=Ve/cr*1e3,_n=tt(dr,{...Ts,segmentNumber:Is.toString(10),segmentTime:Ve.toString(10)});let Es={time:{from:pr,to:1/0},url:_n},Ct={type:"template",baseUrl:be,segmentTemplateUrl:dr,initUrl:"",totalSegmentsDurationMs:Vn,segments:Cn,nextSegmentBeyondManifest:Es,timescale:cr};pt={id:Xe,kind:"text",segmentReference:Ct,profiles:[],duration:g,bitrate:Dn,mime:"",codecs:"",width:0,height:0,isAuto:ei}}else pt={id:Xe,isAuto:ei,kind:"text",url:be}}else{let Xe=z.getAttribute("contentType")??at?.split("/")[0]??I,ei=k.getAttribute("profiles")?.split(",")??[],ht=parseInt(z.getAttribute("width")??"",10),Ts=parseInt(z.getAttribute("height")??"",10),Dn=parseInt(z.getAttribute("bandwidth")??"",10)/1e3,Bn=z.getAttribute("frameRate")??"",cr=z.getAttribute("quality")??void 0,Ju=Bn?$I(Bn):void 0,dr=z.getAttribute("id")??"id"+(A++).toString(10),Cn=Xe==="video"?`${Ts}p`:Xe==="audio"?`${Dn}Kbps`:Zt,Vn=`${dr}@${Cn}`,_n=[...R,...N,...ei],pr,Is=z.querySelector("SegmentBase"),Ve=z.querySelector("SegmentTemplate")??re;if(Is){let Ct=z.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[ft,ki]=Ct.split("-").map(ii=>parseInt(ii,10)),nt={from:ft,to:ki},ti=z.querySelector("SegmentBase")?.getAttribute("indexRange"),[Pi,hr]=ti?ti.split("-").map(ii=>parseInt(ii,10)):[],xt=ti?{from:Pi,to:hr}:void 0;pr={type:"byteRange",url:be,initRange:nt,indexRange:xt}}else if(Ve){let Ct={representationId:z.getAttribute("id")??void 0,bandwidth:z.getAttribute("bandwidth")??void 0},ft=parseInt(Ve.getAttribute("timescale")??"",10),ki=Ve.getAttribute("initialization")??"",nt=Ve.getAttribute("media"),ti=parseInt(Ve.getAttribute("startNumber")??"",10)??1,Pi=tt(ki,Ct);if(!nt)throw new ReferenceError("No media attribute in SegmentTemplate");let hr=Ve.querySelectorAll("SegmentTimeline S")??[],xt=[],ii=0,fr="",ws=0;if(hr.length){let On=ti,mt=0;for(let mr of hr){let kt=parseInt(mr.getAttribute("d")??"",10),Ai=parseInt(mr.getAttribute("r")??"",10)||0,Nn=parseInt(mr.getAttribute("t")??"",10);mt=Number.isFinite(Nn)?Nn:mt;let Zu=kt/ft*1e3,Gw=mt/ft*1e3;for(let Fn=0;Fn<Ai+1;Fn++){let Yw=tt(nt,{...Ct,segmentNumber:On.toString(10),segmentTime:(mt+Fn*kt).toString(10)}),bh=(Gw??0)+Fn*Zu,Kw=bh+Zu;On++,xt.push({time:{from:bh,to:Kw},url:Yw})}mt+=(Ai+1)*kt,ii+=(Ai+1)*Zu}ws=mt/ft*1e3,fr=tt(nt,{...Ct,segmentNumber:On.toString(10),segmentTime:mt.toString(10)})}else if(zV(g)){let mt=parseInt(Ve.getAttribute("duration")??"",10)/ft*1e3,mr=Math.ceil(g/mt),kt=0;for(let Ai=1;Ai<mr;Ai++){let Nn=tt(nt,{...Ct,segmentNumber:Ai.toString(10),segmentTime:kt.toString(10)});xt.push({time:{from:kt,to:kt+mt},url:Nn}),kt+=mt}ws=kt,fr=tt(nt,{...Ct,segmentNumber:mr.toString(10),segmentTime:kt.toString(10)})}let Qw={time:{from:ws,to:1/0},url:fr};pr={type:"template",baseUrl:be,segmentTemplateUrl:nt,initUrl:Pi,totalSegmentsDurationMs:ii,segments:xt,nextSegmentBeyondManifest:Qw,timescale:ft}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Xe||!at)continue;let Es={video:"video",audio:"audio",text:"text"}[Xe];if(!Es)continue;Ie||=Es,pt={id:Vn,kind:Es,segmentReference:pr,profiles:_n,duration:g,bitrate:Dn,mime:at,codecs:Zt,width:ht,height:Ts,fps:Ju,quality:cr}}Ee.language||=q,Ee.label||=we,Ee.mime||=at,Ee.codecs||=Zt,Ee.hdr||=Ie==="video"&&Kd(Zt),Ee.representations.push(pt)}if(Ie){let z=r[Ie].find(q=>q.id===Ee.id);if(z&&Ee.representations.every(q=>q.segmentReference.type==="template"))for(let q of z.representations){let we=Ee.representations.find(at=>at.id===q.id);if(!we)continue;let Ce=we.segmentReference,be=q.segmentReference;be.segments.push(...Ce.segments),be.nextSegmentBeyondManifest=Ce.nextSegmentBeyondManifest}else r[Ie].push(Ee)}}return{duration:g,streams:r,baseUrls:n,live:S}};var ou=D(Ge(),1),Zd=D(Pe(),1);import{assertNever as uu}from"@vkontakte/videoplayer-shared";var nu=s=>{let{webmDecodingInfo:e}=$.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(s){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:uu(s)}},_I=({webmCodec:s,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...nu(s),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],a=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if($.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...nu(s),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...nu(s),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...nu(s),...a,"HLS","HLS_ONDEMAND"];default:uu(e)}if($.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:uu(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},OI=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],n=[...r,...i],o,u=$.device.isMac&&$.browser.isSafari;if($.device.isAndroid)switch(s){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=n;break}default:uu(s)}else $.video.nativeHlsSupported&&!u&&!$.browser.isChromiumBased?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},ep=s=>s?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Zr=s=>{if(s.size===0)return;if(s.size===1){let t=s.values().next();return(0,ou.default)(t.value.split("."),0)}for(let t of s){let i=(0,ou.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=s.values().next();return(0,ou.default)(e.value.split("."),0)},es=s=>{let e=s.map(i=>fi(i)),{codecs:t}=$.video;return YV().filter(i=>{if((0,Zd.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},ts=s=>{let e=s.map(i=>fi(i)),{codecs:t}=$.video;return KV().filter(i=>{if((0,Zd.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},fi=s=>s.split(".")[0].replace("0",""),YV=()=>["av1","vp9","hev1","avc1"],KV=()=>["opus","mp4a"];var JI=D(Ge(),1);var XV=(s,e={})=>{let i=e.timeout||1,r=performance.now();return le.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},JV=s=>le.clearTimeout(s),NI=s=>typeof s=="function"&&s?.toString().endsWith("{ [native code] }"),FI=!NI(le.requestIdleCallback)||!NI(le.cancelIdleCallback),Lt=FI?XV:le.requestIdleCallback,lt=FI?JV:le.cancelIdleCallback;import{abortable as np,assertNonNullable as Dt,ErrorCategory as v0,fromEvent as y0,getExponentialDelay as T0,getWindow as XI,isHigher as I0,isNonNullable as oe,isNullable as ye,once as E0,Subject as w0,Subscription as x0,ValueSubject as Wa}from"@vkontakte/videoplayer-shared";var UI=D(Ge(),1);var lu=s=>s.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,a;i===0?(this.size=void 0,this.valid=!1,a=void 0):i===1?(this.size=void 0,this.valid=!1,a=void 0):i>e.byteLength?(this.size=i,this.valid=!1,a=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,a=i-this.cursor),this.content=new DataView(e.buffer,r,a)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var is=class extends Q{};import{assertNever as ZV}from"@vkontakte/videoplayer-shared";var ya=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:ZV(e)}}};var Ta=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 a=this.readString(4);this.compatibleBrands.push(a)}}};var Ia=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var J=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 Ea=class extends J{constructor(e,t){super(e,t),this.valid&&(this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16())}};var wa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xa=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var Ki=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),a=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}}};var ka=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Pa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Aa=class extends J{constructor(e,t){if(super(e,t),!this.valid)return;switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ra=class extends J{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var $a=class extends J{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 Ma=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var La=class extends J{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 Da=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ba=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ca=class extends J{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Va=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var _a=class extends J{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 Oa=class extends J{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 Na=class extends J{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Fa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ua=class extends J{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 qa=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 t0={ftyp:Ta,moov:Ia,mvhd:Ea,moof:wa,mdat:xa,sidx:Ki,trak:ka,mdia:Ma,mfhd:Ca,tkhd:La,traf:Va,tfhd:_a,tfdt:Oa,trun:Na,minf:Da,sv3d:Pa,st3d:Aa,prhd:Ra,proj:Ba,equi:$a,uuid:ya,stbl:Fa,stsd:Ua,avc1:qa,unknown:is},jt=class s{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(a,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(o){if(!(o instanceof RangeError))throw o}if(!n||!lu(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=t0[e];return i?new i(t,new s):new is(t,new s)}};var mi=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{lu(t)&&(this.index[t.type]??=[],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 r0=new TextDecoder("ascii"),s0=s=>r0.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",a0=s=>{let e=new Ki(s,new jt),t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},n0=(s,e)=>{let i=new jt().parse(s),r=new mi(i),a=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&a.length))return null;let o=a[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(s.buffer,l,c)},o0=s=>{let t=new jt().parse(s),i=new mi(t),r={},a=i.findAll("uuid"),n=(0,UI.default)(a,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},u0=s=>{let t=new jt().parse(s);return new mi(t).find("sidx")?.timescale},l0=(s,e)=>{let i=new jt().parse(s),a=new mi(i).findAll("traf"),n=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,d)=>c+d,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},c0=s=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new jt().parse(s),r=new mi(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},qI={validateData:s0,parseInit:c0,getIndexRange:()=>{},parseSegments:a0,parseFeedableSegmentChunk:n0,getChunkEndTime:l0,getServerLatencyTimestamps:o0,getTimescaleFromIndex:u0};var Ha=D(Pe(),1);import{assertNonNullable as tp,isNonNullable as WI,isNullable as p0}from"@vkontakte/videoplayer-shared";import{assertNever as d0}from"@vkontakte/videoplayer-shared";var jI={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"}},HI=s=>{let e=s.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=ja(s,t),r=i in jI,a=r?jI[i].type:"binary",n=s.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(s.buffer,s.byteOffset+t+1,o-1),l=n&255>>o,p=ja(u),c=l*2**((o-1)*8)+p,d=t+o,h;return d+c>s.byteLength?h=new DataView(s.buffer,s.byteOffset+d):h=new DataView(s.buffer,s.byteOffset+d,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:d,tagSize:d+c,value:h,valueSize:c}},ja=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{let t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Et=(s,e)=>{switch(e){case"int":return s.getInt8(0);case"uint":return ja(s);case"float":return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case"string":return new TextDecoder("ascii").decode(s);case"utf8":return new TextDecoder("utf-8").decode(s);case"date":return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case"master":return s;case"binary":return s;default:d0(e)}},Xi=(s,e)=>{let t=0;for(;t<s.byteLength;){let i=new DataView(s.buffer,s.byteOffset+t),r=HI(i);if(!e(r))return;r.type==="master"&&Xi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},zI=s=>{if(s.getUint32(0)!==440786851)return!1;let e,t,i,r=HI(s);return Xi(r.value,({tag:a,type:n,value:o})=>(a===17143?e=Et(o,n):a===17026?t=Et(o,n):a===17029&&(i=Et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var QI=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],h0=[231,22612,22743,167,171,163,160,175],f0=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,l,p=!1,c=0;return Xi(s,({tag:d,type:h,value:f,valueSize:m})=>{if(d===21419){let S=Et(f,h);l=ja(S)}else d!==21420&&(l=void 0);return d===408125543?(e=f.byteOffset,t=f.byteOffset+m):d===357149030?a=!0:d===290298740?n=!0:d===2807729?i=Et(f,h):d===17545?r=Et(f,h):d===21420&&l===475249515?u=Et(f,h):d===374648427?Xi(f,({tag:S,type:g,value:v})=>S===30321?(p=Et(v,g)===1,!1):!0):a&&n&&(0,Ha.default)(QI,d)&&(o=!0),!o}),tp(e,"Failed to parse webm Segment start"),tp(t,"Failed to parse webm Segment end"),tp(r,"Failed to parse webm Segment duration"),i=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:p,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},m0=s=>{if(p0(s.cuesSeekPosition))return;let e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},b0=(s,e)=>{let t=!1,i=!1,r=o=>WI(o.time)&&WI(o.position),a=[],n;return Xi(s,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&a.push(n),n={};break;case 179:n&&(n.time=Et(l,u));break;case 183:break;case 241:n&&(n.position=Et(l,u));break;default:t&&(0,Ha.default)(QI,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{let{time:l,position:p}=o,c=a[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},g0=s=>{let e=0,t=!1;try{Xi(s,i=>i.tag===524531317?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ha.default)(h0,i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||=(0,Ha.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},GI={validateData:zI,parseInit:f0,getIndexRange:m0,parseSegments:b0,parseFeedableSegmentChunk:g0};var ct=s=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(s);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return GI;case"mp4":return qI}}throw new ReferenceError(`Unsupported mime type ${s}`)};var ip=D(Ge(),1);import{videoSizeToQuality as S0}from"@vkontakte/videoplayer-shared";var bi=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Mt(a):void 0)??S0({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},za=({id:s,bitrate:e})=>({id:s,bitrate:e}),YI=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),KI=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),rp=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,ip.default)(i.split("."),0),isDefault:r}),sp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,ip.default)(r.split("."),0)}),ap=s=>"url"in s,it=s=>s.type==="template";var rs=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,manifest:o}){this.error$=new w0;this.playingRepresentation$=new Wa(void 0);this.playingRepresentationInit$=new Wa(void 0);this.currentSegmentLength$=new Wa(0);this.onLastSegment$=new Wa(!1);this.fullyBuffered$=new Wa(!1);this.initData=new Map;this.initDataPromises=new Map;this.idleCallbacks=new Map;this.parsedInitData=new Map;this.segments=new Map;this.bufferPlaybackQueue=[];this.downloadingBufferItems=[];this.preloadOnly=!1;this.failedDownloads=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.currentVirtualBufferSize=0;this.baseUrls=[];this.baseUrlsIndex=0;this.maintainPlaybackBufferMutex=!1;this.maintainNativeBufferMutex=!1;this.bufferClearingMutex=!1;this.abortNativeBufferMutex=!1;this.switchMutex=!1;this.destroyAbortController=new j;this.downloadAbortController=new j;this.subscription=new x0;this.startWith=np(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Dt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.containerParser=ct(t.mime),this.nativeBufferManager.init(t.mime,t.codecs,this.tuning.dash.useAbortMSEFix),yield this.loadInits(t);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);Dt(i,"No init buffer for starting representation"),Dt(r,"No segments for starting representation"),await this.nativeBufferManager.addInitSegment(i),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a)}.bind(this));this.switchTo=np(this.destroyAbortController.signal,async function*(e,t=!0){if(ye(this.downloadingRepresentationId)||e===this.downloadingRepresentationId||e===this.switchingRepresentationId)return;this.switchMutex=!0,this.switchingRepresentationId=e;let i=this.representations.get(this.downloadingRepresentationId),r=this.representations.get(e);Dt(r,`No such representation ${e}`),Dt(i,`No such representation ${this.downloadingRepresentationId}`),yield this.loadInitIfNeeded(r,"high");let a=this.initData.get(r.id),n=this.segments.get(r.id);Dt(a,"No init buffer for switching representation"),Dt(n,"No segments for switching representation");let o=this.getCurrentPosition()??0,u=c=>c.segment.networkStatus!=="downloaded"||c.segment.time.to-o>this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment,l=c=>{let d=this.representations.get(c.representationId);return Dt(d,"No itemRepresentation for previous track before switch"),c.segment.networkStatus!=="downloaded"||this.forceSwitchCondition(d,r)},p=c=>t?u(c)&&l(c):u(c);this.bufferPlaybackQueue.filter(p).forEach(c=>c.segment.bufferStatus="none"),this.bufferPlaybackQueue=this.bufferPlaybackQueue.filter(c=>!p(c)),this.downloadingRepresentationId=e,this.switchingRepresentationId=null,this.bufferPlaybackQueue.length?(this.abortDownload(),yield this.maintain()):yield this.seek(o),this.switchMutex=!1}.bind(this));this.waitExponentialDownloadDelay=np(this.downloadAbortController.signal,async function*(){let e=T0(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(t=>{let i=XI();this.loadByteRangeSegmentsTimeoutId=i.setTimeout(t,e),this.subscription.add(y0(i,"online").pipe(E0()).subscribe(()=>{t(),i.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}))})}.bind(this));this.kind=e,this.nativeBufferManager=t,this.fetcher=r,this.tuning=a,this.getCurrentPosition=n,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.baseUrls=o?.baseUrls??[],this.representations=new Map(i.map(u=>[u.id,u]))}async seek(e){await this.abort(),await this.clearBuffer(),await this.maintain(e)}async maintain(e=this.getCurrentPosition()){ye(e)||(await this.maintainPlaybackBuffer(e),await this.maintainNativeBuffer(),this.actualizeLastSegmentInfo(e))}getForwardPlaybackBufferDuration(e=this.getCurrentPosition()){let t=this.getPlaybackBufferState();return oe(t)&&oe(e)?t.to-e:0}getPlaybackBufferState(){if(!this.bufferPlaybackQueue.length)return null;let t=this.bufferPlaybackQueue[0].segment.time.from,i=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segment.time.to;return{from:t,to:i}}async abort(){this.abortDownload(),await this.abortNativeBuffer()}findSegmentStartTime(e){let t=this.downloadingRepresentationId??this.playingRepresentationId??"";return this.segments.get(t)?.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from}getRepresentationInitialTime(){return ye(this.playingRepresentationId)?0:(this.segments.get(this.playingRepresentationId)?.[0].time.from??0)/1e3}calculateDurationFromSegments(){if(ye(this.playingRepresentationId))return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,JI.default)(e,-1)?.time.to:0)||0}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){let e=XI();if(this.initData.clear(),this.initDataPromises.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.downloadAbortController.abort(),this.destroyAbortController.abort(),this.subscription.unsubscribe(),e.__polyfill_cancelIdleCallback_e2b3kd3ekf2)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_e2b3kd3ekf2(t);this.idleCallbacks.clear(),e.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}forceSwitchCondition(e,t){let i=!0;if(this.kind==="video"){let r=bi(e),a=bi(t);i=oe(r)&&oe(a)&&I0(a.quality,r.quality)}else if(this.kind==="audio"){let r=za(e),a=za(t);i=oe(r?.bitrate)&&oe(a?.bitrate)&&a.bitrate>r.bitrate}return i}async clearBuffer(){this.bufferClearingMutex=!0,await this.nativeBufferManager.clear(this.destroyAbortController.signal),this.bufferPlaybackQueue.forEach(e=>e.segment.bufferStatus="none"),this.bufferPlaybackQueue=[],this.bufferClearingMutex=!1}abortDownload(){this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortDownloadingItems(),this.maintainPlaybackBufferMutex=!1}abortDownloadingItems(){for(let e of this.downloadingBufferItems)e.segment.networkStatus==="downloading"&&(e.segment.networkStatus="none",e.segment.size=0,e.segment.loadedBytes=0,e.segment.feedingBytes=0,e.segment.fedBytes=0,e.segment.data=null);this.downloadingBufferItems=[]}async abortNativeBuffer(){this.abortNativeBufferMutex=!0;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0,i=await this.nativeBufferManager.abortBuffer(t);return this.abortNativeBufferMutex=!1,this.maintainNativeBufferMutex=!1,i}async loadInits(e){await this.loadInit(e,"high",!0);for(let[t,i]of this.representations)this.idleCallbacks.set(i.id,Lt(async r=>await this.loadInitIfNeeded(i,"low",!1)))}async loadInitIfNeeded(e,t="auto",i=!1){let r=this.initDataPromises.get(e.id),a;this.initData.has(e.id)&&this.segments.has(e.id)?a=Promise.resolve():oe(r)?a=r:a=this.loadInit(e,t,i),await a}async loadInit(e,t="auto",i=!1){try{let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r);this.initDataPromises.set(e.id,a);let{initMetadata:n,initDataView:o,segments:u}=await a??{};if(this.initDataPromises.delete(e.id),ye(o)||ye(u))return;n&&this.parsedInitData.set(e.id,n);let l=o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,u),this.failedDownloads=0}catch(r){i&&this.error$.next({id:"LoadInits",category:v0.WTF,message:"loadInit threw",thrown:r})}}async maintainNativeBuffer(){let e=this.getCurrentPosition();if(ye(e)||this.maintainNativeBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex||this.preloadOnly)return;this.maintainNativeBufferMutex=!0;let t=this.bufferPlaybackQueue.find(o=>this.withinInterval(e,o.segment.time)),i=this.bufferPlaybackQueue.find(o=>o.segment.bufferStatus!=="fed"),r=this.initData.get(i?.representationId??""),a=this.bufferPlaybackQueue[0],n=this.downloadAbortController.signal;oe(r)&&oe(i)&&oe(t)&&this.playingRepresentationId!==i.representationId&&this.withinAppendInterval(e,i.segment.time)&&(i===t||t.segment.bufferStatus==="fed")&&(await this.abortNativeBuffer(),await this.nativeBufferManager.addInitSegment(r,this.downloadAbortController.signal),this.playingRepresentationId=i.representationId,this.playingRepresentation$.next(this.playingRepresentationId)),oe(i)&&this.withinAppendInterval(e,i.segment.time)&&(i.segment.loadedBytes===i.segment.size&&i.segment.bufferStatus==="none"?await this.appendSegmentFully(i,n):await this.appendSegmentPartially(i,n)),oe(a)&&this.withinRemoveInterval(e,a.segment.time)&&await this.removeSegment(a,n),this.pruneVirtualBuffer(e),this.maintainNativeBufferMutex=!1}async maintainPlaybackBuffer(e){Dt(this.downloadingRepresentationId);let t=this.segments.get(this.downloadingRepresentationId),i=this.representations.get(this.downloadingRepresentationId);if(ye(t)||ye(i)||this.maintainPlaybackBufferMutex||this.abortNativeBufferMutex||this.bufferClearingMutex||this.switchMutex)return;this.maintainPlaybackBufferMutex=!0;let r=t.find(n=>e>=n.time.from&&e<n.time.to);oe(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from),this.downloadingBufferItems.length||(this.downloadingBufferItems=this.selectDownloadingItems(e,t)),await this.processCachedItems();let a=this.selectItemsToLoad();await this.loadItems(a,i),this.maintainPlaybackBufferMutex=!1}actualizeLastSegmentInfo(e){let t=this.segments.get(this.downloadingRepresentationId??"");if(ye(t)||t.length===0)return;let i=t[t?.length-1];ye(i)||(this.fullyBuffered$.next(i.time.to-e-this.getForwardPlaybackBufferDuration(e)<this.tuning.dash.bufferTolerance),this.onLastSegment$.next(e-i.time.from>0))}selectDownloadingItems(e,t){Dt(this.downloadingRepresentationId);let i=this.getPlaybackBufferState(),r,a;oe(i)&&this.withinInterval(e,i)?(a=this.forwardBufferTarget-this.getForwardPlaybackBufferDuration(e),r=this.bufferPlaybackQueue[this.bufferPlaybackQueue.length-1].segmentIndex+1):(a=this.forwardBufferTarget,r=t.findIndex(o=>this.withinInterval(e,o.time))),r=r===-1?0:r;let n=[];for(;r<t.length&&a>0;){n.push({representationId:this.downloadingRepresentationId,segmentIndex:r,segment:t[r]});let{from:o,to:u}=t[r].time;a-=u-o,r++}return n}async processCachedItems(){let e=[...this.downloadingBufferItems];for(;e.length&&e[0].segment.networkStatus==="downloaded";)await this.onDownloadItem(e[0]),e.shift()}withinInterval(e,{from:t,to:i},r=this.tuning.dash.bufferTolerance){return oe(e)?e+r>=t&&e<i:!1}withinAppendInterval(e,{from:t,to:i}){let{actionTimeShiftFromSegment:r}=this.tuning.dash;return oe(e)?e+r>=t&&e+r<i||this.withinInterval(e,{from:t,to:i}):!1}withinRemoveInterval(e,{to:t}){let{actionTimeShiftFromSegment:i}=this.tuning.dash;return oe(e)?e-i>t:!1}async appendSegmentFully(e,t){if(ye(e.segment.data))return;e.segment.feedingBytes=e.segment.size,await this.nativeBufferManager.append(e.segment.data,t)&&(e.segment.fedBytes=e.segment.size,this.onItemFullyAppended(e))}async appendSegmentPartially(e,t){if(ye(e.segment.data)||ye(e.segment.loadedBytes)||ye(e.segment.feedingBytes)||ye(e.segment.fedBytes)||ye(e.segment.size))return;let i=e.segment.data,r=new DataView(i.buffer,i.byteOffset+e.segment.feedingBytes,i.byteLength-e.segment.feedingBytes),a=e.segment.loadedBytes!==e.segment.size?this.parseFeedableSegmentChunk(r):r;a?.byteLength&&(e.segment.bufferStatus="partially_fed",e.segment.feedingBytes+=a.byteLength,await this.nativeBufferManager.append(a,t)&&(e.segment.fedBytes+=a.byteLength,e.segment.fedBytes===e.segment.size&&this.onItemFullyAppended(e)))}parseFeedableSegmentChunk(e){return this.containerParser.parseFeedableSegmentChunk(e,!1)}onItemFullyDownloaded(e){e.segment.networkStatus="downloaded"}onItemFullyAppended(e){e.segment.bufferStatus="fed"}async removeSegment(e,t){let{from:i,to:r}=e.segment.time,a=(r-i)/4;await this.nativeBufferManager.remove(0,r-a,t)&&(e.segment.fedBytes=0,e.segment.feedingBytes=0,e.segment.bufferStatus="none",this.bufferPlaybackQueue.shift())}async onDownloadItem(e){if(!this.downloadingBufferItems.find(i=>i===e))return;let t=this.getCurrentPosition();return this.downloadingBufferItems=this.downloadingBufferItems.filter(i=>i!==e||i.segment.networkStatus!=="downloaded"),(this.preloadOnly||oe(t)&&!this.withinRemoveInterval(t,e.segment.time))&&!this.bufferPlaybackQueue.find(i=>i===e)&&this.bufferPlaybackQueue.push(e),this.maintainNativeBuffer()}pruneVirtualBuffer(e){let{maxVirtualBufferSize:t,virtualBufferPruneSize:i,bufferPruningSafeZone:r}=this.tuning.dash;if(this.currentVirtualBufferSize<t)return;let a=this.currentVirtualBufferSize-t+i;for(let n of this.segments.values())for(let o of n)oe(o.size)&&a>0&&o.time.to<=e-r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size);for(let n of this.segments.values())for(let o of[...n].reverse())oe(o.size)&&a>0&&o.time.from>=e+r&&o.bufferStatus==="none"&&o.networkStatus==="downloaded"&&!this.bufferPlaybackQueue.find(u=>u.segment===o)&&!this.downloadingBufferItems.find(u=>u.segment===o)&&(o.data=null,o.networkStatus="none",this.currentVirtualBufferSize-=o.size,a-=o.size)}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())this.updateRepresentationBaseUrl(t,e)}};import{ErrorCategory as k0,isNonNullable as P0,isNullable as ZI,now as eE}from"@vkontakte/videoplayer-shared";var cu=class extends rs{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{await this.fetcher.fetch(a,{...n,priority:i}),this.lastDataObtainedTimestampMs=eE(),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),De(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=0,t=0,i=[],r=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,a=this.preloadOnly?this.forwardBufferTarget:0,n=0;for(;n<this.downloadingBufferItems.length&&this.downloadingBufferItems[n].segment.networkStatus==="none"&&(e<=r||t<=a);){let o=this.downloadingBufferItems[n].segment;o.networkStatus="downloading",o.size=1/0,o.loadedBytes=0,o.feedingBytes=0,o.fedBytes=0,i.push(this.downloadingBufferItems[n]),e+=o.byte.to+1-o.byte.from,t+=o.time.to+1-o.time.from,n++}return i}prepareFetchParams(e,t){if(qe(t.segmentReference))throw new Error("Representation is not byte range type");let{signal:i}=this.downloadAbortController,r=t.segmentReference.url,a={from:e[0].segment.byte.from,to:e[e.length-1].segment.byte.to};return{url:r,range:a,onProgress:async(o,u)=>{if(!i.aborted)try{this.lastDataObtainedTimestampMs=eE(),await this.onSomeDataLoaded({downloadingItems:e,dataView:o,loaded:u,signal:i,globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:k0.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}},signal:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,globalFrom:r,loaded:a,signal:n}){let o=this.representations.get(i);if(!(!this.downloadingBufferItems.length||ZI(o)||ZI(r)||n.aborted))for(let u of e){let{segment:l}=u,p=l.byte.from-r,c=l.byte.to-r,d=c-p+1,h=p<a,f=c<=a;l.size=d,h&&(l.networkStatus==="downloading"&&l.bufferStatus==="none"&&f?(l.data=new DataView(t.buffer,t.byteOffset+p,d),this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u),l.loadedBytes=Math.min(d,a-p),await this.onDownloadItem(u)):P0(l.feedingBytes)&&this.tuning.dash.enableSubSegmentBufferFeeding&&l.networkStatus==="downloading"&&(l.loadedBytes=Math.min(d,a-p),f&&(this.currentVirtualBufferSize+=l.size,this.onItemFullyDownloaded(u)),l.loadedBytes>l.feedingBytes&&(l.data=new DataView(t.buffer,t.byteOffset+p,l.loadedBytes),await this.onDownloadItem(u))))}}updateRepresentationBaseUrl(e,t){if(qe(e.segmentReference))throw new Error("Representation is not byte range type");e.segmentReference.url=t}};import{ErrorCategory as A0,isNullable as op,now as tE}from"@vkontakte/videoplayer-shared";var ss=class extends rs{constructor(e,t,i,r){super(e,t,i,r)}async loadItems(e,t,i="auto"){let{signal:r}=this.downloadAbortController;if(r.aborted||!e.length)return;let{url:a,...n}=this.prepareFetchParams(e,t);if(this.failedDownloads&&await this.waitExponentialDownloadDelay(),!r.aborted)try{let o=await this.fetcher.fetch(a,{...n,priority:i});if(this.lastDataObtainedTimestampMs=tE(),op(o))return;let u=e[0],l=new DataView(o);u.segment.size=l.byteLength,u.segment.loadedBytes=l.byteLength,u.segment.data=l,this.onItemFullyDownloaded(u),await this.onDownloadItem(u),this.failedDownloads=0}catch(o){this.abortDownloadingItems(),De(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}selectItemsToLoad(){let e=[];for(let t of this.downloadingBufferItems){let i=t.segment;i.networkStatus="downloading",i.size=1/0,i.loadedBytes=0,i.feedingBytes=0,i.fedBytes=0,e.push(t)}return e}prepareFetchParams(e,t){let i=this.getFetchUrl(e,t).toString(),{signal:r}=this.downloadAbortController;return{url:i,onProgress:async(n,o)=>{if(!r.aborted)try{this.lastDataObtainedTimestampMs=tE(),await this.onSomeDataLoaded({downloadingItems:e,dataView:n,loaded:o,signal:r,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:A0.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}},signal:r,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}}getFetchUrl(e,t){if(!qe(t.segmentReference))throw new Error("Representation is not template type");return new URL(e[0].segment.url,t.segmentReference.baseUrl)}async onSomeDataLoaded({downloadingItems:e,dataView:t,representationId:i,loaded:r,signal:a}){let n=e[0],{segment:o}=n,u=this.representations.get(i);!this.downloadingBufferItems.length||op(u)||op(o.feedingBytes)||o.networkStatus!=="downloading"||a.aborted||(o.loadedBytes=r,o.loadedBytes>o.feedingBytes&&this.tuning.dash.enableSubSegmentBufferFeeding&&(o.data=new DataView(t.buffer,t.byteOffset,o.loadedBytes),await this.onDownloadItem(n)))}updateRepresentationBaseUrl(e,t){if(!qe(e.segmentReference))throw new Error("Representation is not template type");e.segmentReference.baseUrl=t}};var up=D(Gi(),1),rE=D(Ge(),1);import{assertNonNullable as R0,ErrorCategory as $0,isNullable as Ht,ValueSubject as iE}from"@vkontakte/videoplayer-shared";var du=class extends ss{constructor(t,i,r,a){super(t,i,r,a);this.currentLiveSegmentServerLatency$=new iE(0);this.currentLowLatencySegmentLength$=new iE(0);this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.isActiveLowLatency=a.isActiveLowLatency}updateManifest(t){if(!t||[...this.segments.values()].every(r=>!r.length))return;let i=(0,up.default)(t.streams[this.kind],r=>r.representations);for(let r of i){if(Ht(r)||!qe(r.segmentReference))return;let a=r.segmentReference.segments.map(p=>({...p,networkStatus:"none",bufferStatus:"none",size:void 0})),n=100,o=this.segments.get(r.id)??[],u=(0,rE.default)(o,-1)?.time.to??0,l=a?.findIndex(p=>u>=p.time.from+n&&u<=p.time.to+n);if(l===-1){let p=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,p)}else{let p=a.slice(l+1);this.segments.set(r.id,[...o,...p])}this.representations.set(r.id,r)}}proceedLowLatencyLive(){let t=this.downloadingRepresentationId;R0(t);let i=this.segments.get(t);if(i?.length){let r={representationId:t,segmentIndex:i.length-1,segment:i[i.length-1]};this.updateLowLatencyLive(r)}}getLiveSegmentsToLoadState(t){let i=t?.streams[this.kind],r=(0,up.default)(i,n=>n.representations).find(n=>n.id===this.downloadingRepresentationId);if(Ht(r))return;let a=this.segments.get(r.id);if(a?.length)return{from:a[0].time.from,to:a[a.length-1].time.to}}getRepresentationInitialTime(){if(Ht(this.playingRepresentationId))return 0;let t=this.representations.get(this.playingRepresentationId)?.segmentReference;return Ht(t)||!qe(t)?0:this.getActualLiveStartingSegments(t)[0].time.from+this.tuning.dash.bufferTolerance}prepareFetchParams(t,i){return{...super.prepareFetchParams(t,i),isLowLatency:this.isActiveLowLatency()}}async onSomeDataLoaded({downloadingItems:t,...i}){await super.onSomeDataLoaded({downloadingItems:t,...i}),this.isActiveLowLatency()&&this.updateLowLatencyItemTime(t[0])}onItemFullyDownloaded(t){if(super.onItemFullyDownloaded(t),Ht(t.segment.data)||!this.isActiveLowLatency())return;let i=t.segment.data,r=this.containerParser,{serverDataReceivedTimestamp:a,serverDataPreparedTime:n}=r.getServerLatencyTimestamps(i);a&&n&&this.currentLiveSegmentServerLatency$.next(n-a),this.updateLowLatencyItemTime(t),this.updateLowLatencyLive(t)}updateLowLatencyItemTime(t){let i=t.segment.data,r=this.representations.get(t.representationId)?.segmentReference;if(Ht(t.segment.data)||Ht(r)||!qe(r))return;let a=this.containerParser;if(t.segment.isCurrentLowLatency){let{timescale:n}=r;t.segment.time.to=a.getChunkEndTime(i,n)}}updateLowLatencyLive(t){let i=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!qe(a))return;let n=this.segments.get(r.id)??[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.from));if(o?.isCurrentLowLatency&&(o.time.to=t.segment.time.to,i=o.time.to-o.time.from,o.isCurrentLowLatency=!1),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(t.segment.time.to))&&this.isActiveLowLatency()){let l=Math.round(t.segment.time.to*a.timescale/1e3).toString(10),p=tt(a.segmentTemplateUrl,{segmentTime:l});n.push({networkStatus:"none",bufferStatus:"none",time:{from:t.segment.time.to,to:t.segment.time.to+this.tuning.dash.bufferTolerance},url:p,isCurrentLowLatency:!0})}}this.currentLowLatencySegmentLength$.next(i)}parseFeedableSegmentChunk(t){return this.containerParser.parseFeedableSegmentChunk(t,!0)}getFetchUrl(t,i){let r=super.getFetchUrl(t,i);return this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes"),r}async loadInit(t,i="auto",r=!1){try{let a=this.tuning.dash.useFetchPriorityHints?i:"auto",n=this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,a);this.initDataPromises.set(t.id,n);let{initMetadata:o,initDataView:u,segments:l}=await n??{};if(this.initDataPromises.delete(t.id),Ht(u)||Ht(l))return;o&&this.parsedInitData.set(t.id,o);let p=this.getActualLiveStartingSegments(t.segmentReference);this.segments.has(t.id)||this.segments.set(t.id,p);let c=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(t.id,c),this.failedDownloads=0}catch(a){r&&this.error$.next({id:"LoadInits",category:$0.WTF,message:"loadInit threw",thrown:a})}}getActualLiveStartingSegments(t){let i=t.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],n=0,o=i.length-1;do a.unshift(i[o]),n+=i[o].time.to-i[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[a[0]]:a}};var Qa=class{static getBufferManager(e,t,i,r){return r.manifest?.live?new du(e,t,i,r):qe(i[0].segmentReference)?new ss(e,t,i,r):new cu(e,t,i,r)}};import{ErrorCategory as D0,fromEvent as B0,isNullable as as,Subject as C0,Subscription as V0}from"@vkontakte/videoplayer-shared";import{assertNever as M0,ErrorCategory as sE,Subject as aE}from"@vkontakte/videoplayer-shared";var L0=18,nE=!1;try{nE=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=L0}catch(s){console.error(s)}var lp=class{constructor(e,t=!1){this.bufferFull$=new aE;this.error$=new aE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:sE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};nE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:sE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:M0(t)}}},oE=lp;var pe=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){let r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};var Ga=class{constructor(e){this.error$=new C0;this.subscription=new V0;this.mediaSource=e}init(e,t,i=!1){this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e}; codecs="${t}"`),this.sourceBufferTaskQueue=new oE(this.sourceBuffer,i),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(r=>this.error$.next(r))),this.subscription.add(B0(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:D0.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"})))}addInitSegment(e,t){return this.sourceBufferTaskQueue.append(e,t)}append(e,t){return this.sourceBufferTaskQueue.append(e,t)}remove(e,t,i){return this.sourceBufferTaskQueue.remove(e,t,i)}async clear(e){let t=this.getBufferState();if(as(t))return Promise.resolve(!1);let i=!0;await this.sourceBufferTaskQueue.abort();for(let r of t)i&&=await this.sourceBufferTaskQueue.remove(r.from,r.to,e);return i}warmUpMediaSource(){!as(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}getBufferState(){if(as(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length)return null;let e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++)e.push({from:this.sourceBuffer.buffered.start(t)*1e3,to:this.sourceBuffer.buffered.end(t)*1e3});return e}getForwardBufferDuration(e){return as(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||as(e)?0:pe(this.sourceBuffer.buffered,e)}async abortBuffer(e){return as(this.sourceBuffer)?!1:this.sourceBufferTaskQueue.abort(e)}destroy(){if(this.subscription.unsubscribe(),this.sourceBufferTaskQueue?.destroy(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null}};var q0=["timeupdate","progress","play","seeked","stalled","waiting"],cE=["timeupdate","progress","loadeddata","playing","seeked"],hu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.nativeBufferManagers=[];this.subscription=new lE;this.subscriptionRemovable=new U0;this.representationSubscription=new lE;this.forceEnded$=new Si;this.destroyController=new j;this.state$=new O("none");this.currentVideoRepresentation$=new Z(void 0);this.currentVideoRepresentationInit$=new Z(void 0);this.currentAudioRepresentation$=new Z(void 0);this.currentVideoSegmentLength$=new Z(0);this.currentAudioSegmentLength$=new Z(0);this.error$=new Si;this.manifestRequested=new Si;this.manifestReceived=new Si;this.firstBytesRequested=new Si;this.firstBytesReceived=new Si;this.lastConnectionType$=new Z(void 0);this.lastConnectionReused$=new Z(void 0);this.lastRequestFirstBytes$=new Z(void 0);this.currentLiveTextRepresentation$=new Z(null);this.isLive$=new Z(!1);this.isActiveLive$=new Z(!1);this.isLowLatency$=new Z(!1);this.liveDuration$=new Z(0);this.liveSeekableDuration$=new Z(0);this.liveAvailabilityStartTime$=new Z(0);this.liveStreamStatus$=new Z(void 0);this.currentBuffer$=new Z({from:0,to:0});this.bufferLength$=new Z(0);this.nativeBufferLength$=new Z(0);this.liveLatency$=new Z(void 0);this.liveLoadBufferLength$=new Z(0);this.livePositionFromPlayer$=new Z(0);this.currentStallDuration$=new Z(0);this.videoLastDataObtainedTimestamp$=new Z(0);this.fetcherRecoverableError$=new Si;this.fetcherError$=new Si;this.initRepresentations=uE(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",pu({initialVideo:e,initialAudio:t,sourceHls:i})),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r={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};this.createBuffers(r,e,t,i),this.initRepresentationSubscriptions(),yield this.waitStreamToOpen(),this.setSourceDuration(),zt(this.videoBufferManager),yield Promise.all([this.videoBufferManager.startWith(e),t?this.audioBufferManager?.startWith(t):Promise.resolve()]),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.fetchManifest=uE(this.destroyController.signal,async function*(){try{return yield this.fetcher.fetchManifest(this.manifestUrlString)}catch(e){Ka(this.manifest)&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ji.NETWORK,message:"Failed to load manifest",thrown:e})}}.bind(this));this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new su({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.initTracerSubscription()}async initManifest(e,t,i){this.tracer.log("initManifest"),this.state$.startTransitionTo("manifest_ready"),this.element=e,this.manifestUrlString=this.prepareManifestUrlString(t,i),this.manifest=await this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ji.PARSER,message:"No playable video representations"})}initBuffer(){zt(this.element),this.state$.setState("running"),this.subscription.add(Xa(...q0.map(t=>Zi(this.element,t)),Zi(Ya(),"online")).subscribe(()=>this.tick(),t=>this.error$.next({id:"DashVKPlayer",category:Ji.WTF,message:"Internal logic error",thrown:t})));let e=[...this.source?.activeSourceBuffers??[]];this.subscription.add(Xa(...e.map(t=>Zi(t,"updateend"))).subscribe(t=>this.reinitDecoderIfNeeded())),this.subscription.add(Zi(this.element,"waiting").subscribe(t=>{this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=N0(this.tuning.dash.stallWatchdogInterval).subscribe(()=>this.stallWatchdogIntervalCallback(),i=>this.error$.next({id:"StallWatchdogCallback",category:Ji.NETWORK,message:"Can't restore DASH after stall.",thrown:i})),this.subscriptionRemovable.add(this.stallWatchdogSubscription)}))}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}async seek(e,t=!1){zt(this.element),zt(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),this.element.currentTime=i/1e3,await this.videoBufferManager.seek(i),await this.audioBufferManager?.seek(i),this.tracer.log("seek",pu({requestedPosition:e,forcePrecise:t,position:i}))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){gi(this.element)&&gi(this.source)&&gi(e)&&this.isStreamEnded&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.nativeBufferManagers.forEach(t=>t.warmUpMediaSource())}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}get isStreamEnded(){return this.source?.readyState==="ended"}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setBufferTarget(e){this.bufferManagers.forEach(t=>t.setTarget(e))}setPreloadOnly(e){this.bufferManagers.forEach(t=>t.setPreloadOnly(e))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.nativeBufferManagers.forEach(e=>e.destroy()),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&Ya().clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),gi(this.source)&&this.isStreamNotOpen&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}get isStreamNotOpen(){return this.source?.readyState!=="open"}async reinitDecoderIfNeeded(e=!1){let t=this.videoNativeBufferManager?.getBufferState()??[];if(Ka(this.element)||!t.length)return;let i=this.element.currentTime*1e3;this.element.readyState<3&&t.some(r=>i>=r.from&&i<=r.to)&&(e?await this.seek(i):this.element.currentTime=this.element.currentTime)}async stallWatchdogIntervalCallback(){zt(this.element),zt(this.source);let{stallWatchdogInterval:e}=this.tuning.dash;if(this.isStreamNotOpen)return;let t=this.currentStallDuration$.getValue()+e;this.currentStallDuration$.next(t);let i={timeInWaiting:t};if(await this.reinitDecoderIfNeeded(t%1e3===0),this.isStallExceeded(t))throw new Error(`Stall timeout exceeded: ${t} ms`);await this.restoreAfterDeepStall(i),this.tracer.log("stallIntervalCallback",pu(i))}isStallExceeded(e){let{crashOnStallTimeout:t,crashOnStallTWithoutDataTimeout:i}=this.tuning.dash,r=F0(),a=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,l=this.audioBufferManager?.getForwardPlaybackBufferDuration()??0,p=gi(this.videoBufferManager)&&u<a&&r-n>i,c=gi(this.audioBufferManager)&&l<a&&r-o>i;return(p||c)&&e>i||e>=t}async updateManifest(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=await this.fetchManifest();if(Ka(e))return null;let t=this.parseManifest(e);if(!t)return null;let i=this.getResultManifest(t);return this.tracer.log("updateManifestEnd",pu(i)),i}parseManifest(e){try{return Jr(e??"",this.manifestUrlString)}catch(t){let i=zr(e)??{id:"ManifestParsing",category:Ji.PARSER,message:"Failed to parse MPD manifest",thrown:t};this.error$.next(i)}}getResultManifest(e){let t={text:e.streams.text,video:[],audio:[]},i=(o,u,l)=>!!(this.element?.canPlayType?.(u)&&_e()?.isTypeSupported?.(`${u}; codecs="${l}"`)||o==="text"),r,a;for(let o of["video","audio"]){let l=e.streams[o].filter(({mime:c,codecs:d})=>i(o,c,d));t[o]=l;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let c=l.map(({codecs:d})=>d);o==="audio"&&(a=ts(c),p=a[0]),o==="video"&&(r=es(c),this.forceVideoCodec&&(0,dE.default)(r,this.forceVideoCodec)?p=this.forceVideoCodec:p=r[0]),p&&(t[o]=l.filter(({codecs:d})=>fi(d)===p))}else{let c=new Set(l.map(({codecs:d})=>d));p=Zr(c),p&&(t[o]=l.filter(({codecs:d})=>d.startsWith(p)))}if(o==="video"){let c=this.tuning.preferHDR,d=t.video.some(f=>f.hdr),h=t.video.some(f=>!f.hdr);$.display.isHDR&&c&&d?t.video=t.video.filter(f=>f.hdr):h&&(t.video=t.video.filter(f=>!f.hdr))}}let n={...e,streams:t};return this.tuning.dash.codecsPrioritizeEnabled&&(n.codecs={video:r,audio:a}),n}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}createBuffers(e,t,i,r){zt(this.manifest),zt(this.element);let a=l=>{this.representationSubscription.add(Zi(l,"error").pipe(cp(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ji.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=Er();let n=Ya().document,o=n.createElement("source");if(a(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),ni())if(r){let l=n.createElement("source");a(l),l.type="application/x-mpegurl",l.src=r.url,this.element.appendChild(l)}else this.element.disableRemotePlayback=!0;let u=this.manifest.streams.video.reduce((l,p)=>[...l,...p.representations],[]);if(this.videoNativeBufferManager=new Ga(this.source),this.videoBufferManager=Qa.getBufferManager("video",this.videoNativeBufferManager,u,e),this.bufferManagers=[this.videoBufferManager],this.nativeBufferManagers=[this.videoNativeBufferManager],gi(i)){this.audioNativeBufferManager=new Ga(this.source);let l=this.manifest.streams.audio.reduce((p,c)=>[...p,...c.representations],[]);this.audioBufferManager=Qa.getBufferManager("audio",this.audioNativeBufferManager,l,e),this.bufferManagers.push(this.audioBufferManager),this.nativeBufferManagers.push(this.audioNativeBufferManager)}}async waitStreamToOpen(){if(this.isStreamNotOpen){let e=this.tuning.dash.sourceOpenTimeout>=0;await new Promise(t=>{e&&(this.timeoutSourceOpenId=Ya().setTimeout(()=>{if(this.isStreamNotOpen){t();return}this.error$.next({id:"OpenOfStream",category:Ji.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&Ya().clearTimeout(this.timeoutSourceOpenId),t()},{once:!0})})}}initRepresentationSubscriptions(){this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Xa(...this.bufferManagers.map(e=>e.error$)).subscribe(this.error$)),zt(this.videoBufferManager),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.initBufferLengthSubscription()}initBufferLengthSubscription(){this.representationSubscription.add(Xa(...cE.map(e=>Zi(this.element,e))).pipe(dp(e=>this.videoBufferManager?.getPlaybackBufferState()),cp(gi),dp(({from:e,to:t})=>({from:e/1e3,to:t/1e3}))).subscribe(this.currentBuffer$)),this.representationSubscription.add(Xa(...cE.map(e=>Zi(this.element,e))).pipe(dp(e=>Math.max(this.videoBufferManager?.getForwardPlaybackBufferDuration()??0,this.audioBufferManager?.getForwardPlaybackBufferDuration()??0)),_0()).subscribe(this.bufferLength$)),this.representationSubscription.add(this.nativeBufferLength$.pipe(cp(e=>e>this.tuning.dash.bufferEmptinessTolerance)).subscribe(e=>this.stopStallWatchdogSubscription()))}initTracerSubscription(){let e=O0(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}async tick(){if(Ka(this.element)||Ka(this.videoBufferManager)||this.isStreamNotOpen)return;let e=this.element.currentTime*1e3,i=(this.videoNativeBufferManager?.getBufferState()??[]).find(r=>e>=r.from&&e<=r.to);this.nativeBufferLength$.next(i?i.to-e:0),await this.videoBufferManager.maintain(e),await this.audioBufferManager?.maintain(e)}};import{assertNonNullable as fu,combine as j0,ErrorCategory as H0,filter as pp,filterChanged as z0,fromEvent as W0,isNonNullable as Q0,map as hp,merge as Ja}from"@vkontakte/videoplayer-shared";var mu=class extends hu{constructor(e){super(e)}prepareManifestUrlString(e,t){return e}initRepresentationSubscriptions(){super.initRepresentationSubscriptions(),this.initDisableStallWatchdogSubscription(),this.initEndOfVideoSubscription()}setSourceDuration(){fu(this.manifest),fu(this.source);let e=[this.manifest.duration??0,...(0,fp.default)((0,fp.default)([...this.manifest.streams.audio,...this.manifest.streams.video],t=>t.representations),t=>{let i=[];return t.duration&&i.push(t.duration),qe(t.segmentReference)&&t.segmentReference.totalSegmentsDurationMs&&i.push(t.segmentReference.totalSegmentsDurationMs),i})];this.source.duration=Math.max(...e)/1e3}async restoreAfterDeepStall(e){fu(this.element);let t=this.element.currentTime*1e3;await Promise.all([this.videoBufferManager?.maintain(t),this.audioBufferManager?.maintain(t)]),e.position=t}initDisableStallWatchdogSubscription(){fu(this.element);let e=Ja(W0(this.element,"ended"),this.forceEnded$),t=this.nativeBufferLength$.pipe(pp(i=>i>this.tuning.dash.bufferEmptinessTolerance));this.representationSubscription.add(Ja(e,t).subscribe(i=>this.stopStallWatchdogSubscription()))}initEndOfVideoSubscription(){let e=Ja(...this.bufferManagers.map(a=>a.fullyBuffered$)).pipe(hp(()=>this.bufferManagers.every(a=>a.fullyBuffered$.getValue()))),t=Ja(...this.bufferManagers.map(a=>a.onLastSegment$)).pipe(hp(()=>this.bufferManagers.some(a=>a.onLastSegment$.getValue()))),i=j0({allBuffersFull:e,someBufferEnded:t}).pipe(z0(),hp(({allBuffersFull:a,someBufferEnded:n})=>a&&n),pp(a=>a)),r=()=>{try{this.source?.endOfStream()}catch(a){this.error$.next({id:"EndOfStream",category:H0.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:a})}};this.representationSubscription.add(Ja(this.forceEnded$,i).pipe(pp(a=>Q0(this.source)&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(n=>!n.updating))).subscribe(r))}};var ns=class extends ha{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i,genericErrorListener:r}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$),this.subscription.add(this.player.currentVideoRepresentation$.pipe(G0()).subscribe(a=>{let n=[...this.videoTracksMap.entries()].find(([,{representation:c}])=>c.id===a);if(!n){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[o,{stream:u}]=n,l=this.params.desiredState.videoStream.getTransition();l&&l.to&&l.to.id===u.id&&this.params.desiredState.videoStream.setState(l.to),e.currentVideoTrack$.next(o),e.currentVideoStream$.next(Yo(u));let p=this.player.calculateDurationFromSegments();p&&this.params.output.duration$.next(p/1e3)},r))}getPlayer(){return new mu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{assertNever as v_,assertNonNullable as y_,combine as T_,debounce as I_,ErrorCategory as wE,filter as wp,filterChanged as un,fromEvent as E_,isNonNullable as xE,isNullable as w_,map as ln,merge as cn,observableFrom as Pu,once as kE,Subscription as x_,throttle as k_}from"@vkontakte/videoplayer-shared";var EE=D(Pe(),1),Ip=D(Gi(),1);var Be=(s,e,t=0)=>{for(let i=0;i<s.length;i++)if(s.start(i)*1e3-t<=e&&s.end(i)*1e3+t>e)return!0;return!1};import{abortable as vp,assertNonNullable as ds,combine as ps,ErrorCategory as dt,filter as wu,filterChanged as an,flattenObject as nn,fromEvent as Gt,getTraceSubscriptionMethod as o_,interval as yp,isNonNullable as on,isNullable as yE,map as hs,merge as ir,now as Tp,Subject as Yt,Subscription as TE,SubscriptionRemovable as u_,tap as l_,throttle as c_,ValueSubject as ee}from"@vkontakte/videoplayer-shared";var gu=D(Pe(),1),tr=D(Ge(),1),Su=D(Gi(),1);var bE=D($o(),1);import{assertNever as Y0,ErrorCategory as pE,Subject as hE}from"@vkontakte/videoplayer-shared";var K0=18,fE=!1;try{fE=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=K0}catch(s){console.error(s)}var mp=class{constructor(e,t=!1){this.bufferFull$=new hE;this.error$=new hE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:pE.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};fE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:pE.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:Y0(t)}}},mE=mp;var os=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};import{abortable as vi,assertNonNullable as je,ErrorCategory as Wt,fromEvent as bp,getExponentialDelay as gp,isHigher as X0,isNonNullable as yi,isNullable as he,now as bu,once as J0,Subject as Z0,Subscription as e_,ValueSubject as er}from"@vkontakte/videoplayer-shared";var Za=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new er(0);this.currentLowLatencySegmentLength$=new er(0);this.currentSegmentLength$=new er(0);this.onLastSegment$=new er(!1);this.fullyBuffered$=new er(!1);this.playingRepresentation$=new er(void 0);this.playingRepresentationInit$=new er(void 0);this.error$=new Z0;this.gaps=[];this.subscription=new e_;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new j;this.switchAbortController=new j;this.destroyAbortController=new j;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=vi(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new mE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.subscription.add(bp(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Wt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Wt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(bp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Wt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!V(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,os(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);je(i,"No init buffer for starting representation"),je(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=vi(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(he(a)||he(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),je(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();yi(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=vi(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);je(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(he(a)||he(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),je(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();yi(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=vi(this.destroyAbortController.signal,async function*(e){let t=(0,Su.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!it(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);je(r,`Representation not found by id ${i}`);let a=this.segments.get(i);je(a,"No segments for starting representation");let n=this.initData.get(i);if(je(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new j,vi(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);je(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(he(o)||he(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),je(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!V(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();yi(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(){!he(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(he(e)||he(this.downloadingRepresentationId)||he(this.playingRepresentationId)||he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||yi(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),je(i,`No such representation ${this.playingRepresentationId}`),he(r)||he(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);yi(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=bi(i),f=bi(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&yi(h)&&yi(f)&&X0(h.quality,f.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||S?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let v=[...this.segments.entries()].map(([T,y])=>{let x=y.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;v&&(this.playingRepresentationId=v,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&os(this.sourceBuffer.buffered)>=this.bufferLimit){let d=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=[];if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,gu.default)(p,n))d="high";else{let h=(0,tr.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,tr.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-this.getForwardBufferDuration(e)<u),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;yi(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,Su.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,Su.default)(e.streams[this.kind],i=>i.representations);for(let i of t){if(!i||!it(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,tr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,tr.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!it(r))return;let a=this.segments.get(i.id)??[],n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=tt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&lt&&lt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&lt&&lt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:d,time:{from:h,to:f}},m)=>{let S=h<=i&&f>=i,g=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(Be(this.sourceBuffer.buffered,h)&&Be(this.sourceBuffer.buffered,f)))&&g&&T});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){it(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await vi(o,async function*(){let p=gp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=bu(),!p)return;let c=new DataView(p),d=ct(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),De(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())it(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await vi(n,async function*(){let u=gp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),bp(window,"online").pipe(J0()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=bu(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),De(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,tr.default)(e,0).byte.from,to:(0,tr.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=bu(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Wt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=bu();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Wt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,gu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=ct(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(a.aborted){await n();continue}let p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,f=c<=r;if(!h)continue;let m=ct(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===d?S:m.parseFeedableSegmentChunk(S);g?.byteLength&&(l.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Be(this.sourceBuffer.buffered,e.segment.time.from,100)&&Be(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Wt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",ap(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let r of this.segments.get(i.id)??[])r.status==="fed"&&Math.round(r.time.from)===Math.round(e.segment.time.from)&&Math.round(r.time.to)===Math.round(e.segment.time.to)&&(r.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Lt(()=>(0,bE.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",a=!i&&this.tuning.dash.ignoreNetworkErrorsOnLoadInit,o=(!i&&this.failedDownloads>0?vi(this.destroyAbortController.signal,async function*(){let u=gp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ct(e.mime),{priority:r,ignoreNetworkErrors:a})).then(async u=>{if(!u)return;let{init:l,dataView:p,segments:c}=u,d=p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&it(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,u=>{a||this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Wt.WTF,message:"loadInit threw",thrown:u})});return this.initData.set(e.id,o),o}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||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||he(e))return!1;let r=[],a=0,n=u=>{u.sort((p,c)=>p.from-c.from);let l=[u[0]];for(let p=1;p<u.length;p++){let{from:c,to:d}=u[p],h=l[l.length-1];h.to>=c?h.to=Math.max(h.to,d):l.push(u[p])}return l},o=u=>{if(a>=t)return r;r.push({...u.time}),r=n(r);let l=ap(u)?u.size??0:u.byte.to-u.byte.from;a+=l};for(let u of this.segments.values())for(let l of u){let p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,p=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let d of this.segments.values())for(let h of d)(0,gu.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&c++;if(c===this.segments.size){let d={time:{from:l,to:p},url:"",status:"none"};o(d)}}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 p of l)p.time.from>=e+u&&p.status==="fed"&&o(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!V(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||!V(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||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||he(e)?0:pe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:a}=this.sourceBuffer;for(let n=0;n<a.length;n++){let o=a.start(n)*1e3,u=a.end(n)*1e3;if(!(u<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(a=>{if(r&&a.persistent)return!0;let n=Math.round(a.from),o=Math.round(a.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Lt(()=>{try{this.detectGaps(e,t)}catch(a){this.error$.next({id:"GapDetection",category:Wt.WTF,message:"detectGaps threw",thrown:a})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(he(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||he(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),a=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(p=>p.from-t<=n&&p.to+t>=o),l=e.filter(p=>n>=p.from&&n<p.to-t||o>p.from+t&&o<=p.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Wt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};import{abortable as en,assertNever as gE,fromEvent as SE,merge as t_,now as tn,Subject as us,ValueSubject as Sp,flattenObject as ls,ErrorCategory as rn,SubscriptionRemovable as i_}from"@vkontakte/videoplayer-shared";var yu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new us;this.firstBytesManifest$=new us;this.firstBytesRequested$=new us;this.firstBytesReceived$=new us;this.lastConnectionType$=new Sp(void 0);this.lastConnectionReused$=new Sp(void 0);this.lastRequestFirstBytes$=new Sp(void 0);this.recoverableError$=new us;this.error$=new us;this.abortAllController=new j;this.subscription=new i_;this.fetchManifest=en(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=It(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(vu);return r?(t.log("success",ls({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",ls({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=en(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1,ignoreNetworkErrors:p=!1}={}){let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let I=new URL(c,location.href);I.searchParams.append("bytes",`${i.from}-${i.to}`),c=I.toString();break}default:gE(t)}this.requestQuic&&(c=It(c));let f=this.abortAllController.signal,m;if(n){let I=new j;if(m=t_(SE(this.abortAllController.signal,"abort"),SE(n,"abort")).subscribe(()=>{try{I.abort()}catch(N){vu(N)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{I.abort()}catch(N){vu(N)}f=I.signal}let S=0,g=tn();h.log("startRequest",ls({url:c,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:g})),this.firstBytesRequested$.next();let v=yield this.doFetch(c,{priority:a,headers:d,signal:f},{ignoreNetworkErrors:p}),T=tn();if(!v)return h.error("error",{message:"No response in request"}),h.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(T-g),!v.ok||!v.body){this.unsubscribeAbortSubscription(m);let I=`Fetch error ${v.status}: ${v.statusText}`;return h.error("error",{message:I}),h.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!o){this.unsubscribeAbortSubscription(m);let I=tn(),N={requestStartedAt:g,requestEndedAt:I,duration:I-g};return h.log("endRequest",ls(N)),h.end(),v.arrayBuffer()}let y=v.body;if(o){let I;[y,I]=v.body.tee(),this.throughputEstimator?.trackStream(I,u)}let x=y.getReader(),A,R=parseInt(v.headers.get("content-length")??"",10);Number.isFinite(R)&&(A=R),!A&&i&&(A=i.to-i.from+1);let w=A?new Uint8Array(A):new Uint8Array(0),B=!1,k=I=>{this.unsubscribeAbortSubscription(m),B=!0,vu(I)},F=en(f,async function*({done:I,value:N}){if(S===0&&(this.lastRequestFirstBytes$.next(tn()-g),this.firstBytesReceived$.next()),f.aborted){this.unsubscribeAbortSubscription(m);return}if(!I&&N){if(l&&A)w.set(N,S),S+=N.byteLength;else{let L=new Uint8Array(w.length+N.length);L.set(w),L.set(N,w.length),w=L,S+=N.byteLength}r?.(new DataView(w.buffer),S),yield x?.read().then(F,k)}}.bind(this));yield x?.read().then(F,k),this.unsubscribeAbortSubscription(m);let C=tn(),E={failed:B,requestStartedAt:g,requestEndedAt:C,duration:C-g};return B?(h.error("endRequest",ls(E)),h.end(),null):(h.log("endRequest",ls(E)),h.end(),w.buffer)}.bind(this));this.fetchByteRangeRepresentation=en(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},measureThroughput:!1,...i});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=en(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,{measureThroughput:!1,...t});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Wr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:gE(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t,i){let r=await Ke(e,t);if(r.ok)return r;if(i?.ignoreNetworkErrors)return;let a=await r.text(),n=parseInt(a);if(!isNaN(n))switch(n){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:rn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:rn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:rn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:rn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${n})`,category:rn.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},vu=s=>{if(!De(s))throw s};import{isNullable as r_,ValueSubject as vE}from"@vkontakte/videoplayer-shared";var Ti=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new vE(e.initial),this.debounced$=new vE(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Fe(`raw_${t}`),this.smoothedSeries$=new Fe(`smoothed_${t}`),this.reportedSeries$=new Fe(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(r_(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 Tu=class extends Ti{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ut(this.slow,e,this.params.emaAlphaSlow),this.fast=Ut(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Iu=class extends Ti{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Pd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ut(this.emaSmoothed,e,this.params.emaAlpha);let i=Wy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Eu=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?Ut(this.smoothed,t,this.params.emaAlpha):t}};var Qt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Tu({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Iu({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 Eu({initial:e,label:"liveEdgeDelay",...t})}};var cs=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)};import{isNullable as s_,ValueSubject as a_}from"@vkontakte/videoplayer-shared";var sn=class s{constructor(e,t){this.currentRepresentation$=new a_(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!s_(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&it(t.segmentReference))}};var d_=["timeupdate","progress","play","seeked","stalled","waiting"],p_=["timeupdate","progress","loadeddata","playing","seeked"];var xu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new TE;this.subscriptionRemovable=new u_;this.representationSubscription=new TE;this.state$=new O("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Yt;this.manifestRequested$=new Yt;this.firstBytesManifest$=new Yt;this.manifestReceived$=new Yt;this.firstBytesRequested$=new Yt;this.firstBytesReceived$=new Yt;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.isActiveLive$=new ee(!1);this.isLowLatency$=new ee(!1);this.liveDuration$=new ee(0);this.liveSeekableDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(0);this.liveStreamStatus$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.fetcherRecoverableError$=new Yt;this.fetcherError$=new Yt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Yt;this.gapWatchdogActive=!1;this.liveWasInterrupted=!1;this.destroyController=new j;this.initManifest=vp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.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=vp(this.destroyController.signal,async function*(){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=Jr(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=zr(e)??{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,p)=>!!(this.element?.canPlayType?.(l)&&_e()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!0);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";if(c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h),c&&this.liveWasInterrupted){this.liveWasInterrupted=!1,this.stopStallWatchdogSubscription();let f=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(f).catch(m=>{this.error$.next({id:"updateManifest",category:dt.VIDEO_PIPELINE,message:"seekLive after stream restore failed",thrown:m})})}}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=ts(d),c=n[0]),u==="video"&&(a=es(d),this.forceVideoCodec&&(0,EE.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>fi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=Zr(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);$.display.isHDR&&d&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",nn(o)),o}.bind(this));this.initRepresentations=vp(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",nn({initialVideo:e,initialAudio:t,sourceHls:i})),ds(this.manifest),ds(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add(Gt(c,"error").pipe(wu(d=>!!this.element?.played.length)).subscribe(d=>{this.error$.next({id:"VideoSource",category:dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:d})}))};this.source=Er();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),ni())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}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((c,d)=>[...c,...d.representations],[]);if(this.videoBufferManager=new Za("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],on(t)){let c=this.manifest.streams.audio.reduce((d,h)=>[...d,...h.representations],[]);this.audioBufferManager=new Za("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}if(sn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new sn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ir(...p_.map(c=>Gt(this.element,c))).pipe(hs(c=>this.element?pe(this.element.buffered,this.element.currentTime*1e3):0),an(),l_(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&this.stopStallWatchdogSubscription()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ir(Gt(this.element,"ended"),this.forceEnded$).subscribe(()=>{this.stopStallWatchdogSubscription()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(an()).subscribe(d=>this.liveStreamEndTimestamp=Tp())),this.subscription.add(Gt(this.element,"pause").subscribe(()=>{let{liveUpdateInterval:d}=this.tuning.dash;this.livePauseWatchdogSubscription=yp(d).subscribe(h=>{let f=ai(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,f+d,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Gt(this.element,"play").subscribe(d=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(ps({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(hs(({isActiveLive:d,isLowLatency:h})=>d&&h),an()).subscribe(d=>{this.isManualDecreasePlaybackInLive()||cs(this.element,1)})),this.representationSubscription.add(ps({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(wu(({bufferLength:d,isActiveLive:h,isLowLatency:f})=>h&&f&&!!d)).subscribe(({bufferLength:d})=>this.liveBuffer.next(d))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(d=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!d)return;let h=this.liveSeekableDuration$.getValue()-d/1e3;this.liveSeekableDuration$.next(Math.max(h,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+d/1e3)})),this.representationSubscription.add(ps({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(wu(({isLive:d})=>d),an((d,h)=>h.bufferLength<d.bufferLength),hs(({rtt:d,bufferLength:h,segmentServerLatency:f})=>{let m=ai(this.manifestUrlString,2);return(d/2+h+f+m)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ps({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:d,isActiveLive:h,isLowLatency:f})=>{if(!f||!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=d-m;if(this.isManualDecreasePlaybackInLive())return;let T=1;Math.abs(v)>S&&(T=1+Math.sign(v)*g),cs(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(d=>{let h=0;if(d){let f=(this.element?.currentTime??0)*1e3;h=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let c=0;this.representationSubscription.add(ps({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(c_(this.tuning.dash.liveUpdateInterval)).subscribe(async({liveLoadBufferLength:d,bufferLength:h})=>{if(!this.element||this.isUpdatingLive)return;let f=this.element.playbackRate,m=ai(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,g=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),v=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,T=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,y=isFinite(d)?d:h,x=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),A=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(A);let R="none";if(x?R="active_low_latency":this.isLowLatency$.getValue()&&A?(this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),R="active_low_latency"):m!==0&&y<g?R="live_forward_buffering":y<g+T&&(R="live_with_target_offset"),isFinite(d)&&(c=d>c?d:c),R==="live_forward_buffering"||R==="live_with_target_offset"){let w=c-(g+v),B=this.normalizeLiveOffset(Math.trunc(m+w/f)),k=Math.abs(B-m),F=0;!d||k<=this.tuning.dashCmafLive.offsetCalculationError?F=m:B>0&&k>this.tuning.dashCmafLive.offsetCalculationError&&(F=B),this.manifestUrlString=ne(this.manifestUrlString,F,2)}(R==="live_with_target_offset"||R==="live_forward_buffering")&&(c=0,await this.updateLive())},d=>{this.error$.next({id:"updateLive",category:dt.VIDEO_PIPELINE,thrown:d,message:"Failed to update live with subscription"})}))}let u=ir(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(hs(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),l=ir(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(hs(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),p=ps({allBuffersFull:u,someBufferEnded:l}).pipe(an(),hs(({allBuffersFull:c,someBufferEnded:d})=>c&&d),wu(c=>c));if(this.representationSubscription.add(ir(this.forceEnded$,p).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(ir(...this.bufferManagers.map(c=>c.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 c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(d=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){d();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)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),d()},{once:!0})})}if(!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,Ip.default)((0,Ip.default)([...this.manifest.streams.audio,...this.manifest.streams.video],d=>d.representations),d=>{let h=[];return d.duration&&h.push(d.duration),it(d.segmentReference)&&d.segmentReference.totalSegmentsDurationMs&&h.push(d.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&on(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=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=yp(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:dt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new yu({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.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Qt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){ds(this.element),this.updateManifestUrlWithTimeOffset(e),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.updateLiveBuffersFromManifest(this.manifest))}updateManifestUrlWithTimeOffset(e){let t=this.liveStreamStatus$.getValue()!=="active"?Tp()-this.liveStreamEndTimestamp:0,i=this.normalizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,2)}async updateLiveBuffersFromManifest(e){await this.videoBufferManager?.seekLive(e.streams.video),await this.audioBufferManager?.seekLive(e.streams.audio),this.liveTextManager?.seekLive(e.streams.text)}stopStallWatchdogSubscription(){this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)}initBuffer(){ds(this.element),this.state$.setState("running"),this.subscription.add(ir(...d_.map(e=>Gt(this.element,e)),Gt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:dt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Gt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Gt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===2&&!this.element.seeking&&Be(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{let{keepSilentStallWatchdogWhenNotActive:t}=this.tuning.dashCmafLive,{crashOnStallTimeout:i,crashOnStallTWithoutDataTimeout:r,liveStallReinitInterval:a,stallWatchdogInterval:n}=this.tuning.dash,o=this.isLive$.getValue(),l=this.liveStreamStatus$.getValue()==="active";if(!this.element||this.source?.readyState!=="open")return;let p=this.currentStallDuration$.getValue();p+=n,this.currentStallDuration$.next(p);let c={timeInWaiting:p},d=Tp(),h=100,f=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(f);let m=this.audioBufferManager?.lastDataObtainedTimestamp??0,S=this.videoBufferManager?.getForwardBufferDuration()??0,g=this.audioBufferManager?.getForwardBufferDuration()??0,v=S<h&&d-f>r,T=this.audioBufferManager&&g<h&&d-m>r;if((!t||l)&&((v||T)&&p>r||p>=i))throw new Error(`Stall timeout exceeded: ${p} ms`);if(o&&p%a===0){let y=this.normalizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);!l&&t?(this.liveWasInterrupted=!0,this.updateManifestUrlWithTimeOffset(y),this.updateManifest()):this.seekLive(y).catch(x=>{this.error$.next({id:"stallIntervalCallback",category:dt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:x})}),c.liveLastOffset=y}else{let y=this.element.currentTime*1e3;this.videoBufferManager?.maintain(y),this.audioBufferManager?.maintain(y),c.position=y}this.tracer.log("stallIntervalCallback",nn(c))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=yp(this.tuning.dash.stallWatchdogInterval).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:dt.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){ds(this.element),ds(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Be(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(yE(this.element)||yE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",nn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){on(this.element)&&on(this.source)&&on(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=o_(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normalizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=[],o=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(r&&l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n.push(1/0):n.push(l.to));if(n.length){let u=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:n,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",nn(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as h_,map as f_,observeElementSize as m_,Subscription as b_,ValueSubject as Ep,noop as g_}from"@vkontakte/videoplayer-shared";var ku=class{constructor(){this.subscription=new b_;this.pipSize$=new Ep(void 0);this.videoSize$=new Ep(void 0);this.elementSize$=new Ep(void 0);this.pictureInPictureWindowRemoveEventListener=g_}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(m_(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(h_({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(f_(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var rr=class{constructor(e){this.subscription=new x_;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ci;this.stallsManager=new jr;this.elementSizeManager=new ku;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Tt;this.audioTrackSwitchHistory=new Tt;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?.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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(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?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return v_(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new pi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 Qe(e.source.url),this.params=e,this.video=Ae(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(de(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 xu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;w_(this.observableVideo)&&(this.observableVideo=Me(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:wE.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(wp(c=>!!c.length),kE()).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(ln(c=>c.to.state!=="none"),un());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(wp(xE),kE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(ln(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(ot(this.video,t.isLooped,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),hi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:i}),this.subscription.add($e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),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 d=this.player.getStreams(),h=this.player.getCodecs();if(y_(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push(rp(S));let g=[];for(let v of S.representations){let T=za(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(sp(m));let S=[];for(let g of m.representations){let v=bi({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=YI(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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 o=cn(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$,E_(this.video,"progress")).pipe(wp(()=>this.videoTracksMap.size>0)),{abrThrottle:u}=this.params.tuning.dash;u&&(o=o.pipe(k_(u))),this.subscription.add(o.subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[f,m]=h,S=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===f.id);xE(S)&&(this.stallsManager.lastVideoTrackSelected=S);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")await this.player.initRepresentations(f.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",f.id),m){let v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,v)}},r)),this.subscription.add(T_({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:cn(Pu([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(ln(c=>c.to)))}).pipe(ln(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),un()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),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(un()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(sp(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(un()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(rp(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.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(ln(({to:c})=>c==="ready"),un());this.subscription.add(cn(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Pu(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(cn(l,this.player.state$.stateChangeEnded$,Pu(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=cn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Pu(["init"])).pipe(I_(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:Wi,t=this.params.tuning.useNewAutoSelectVideoTrack?Ur:Fr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Nr,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=[...this.videoTracksMap.keys()].find(({id:w})=>w===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=pe(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=[...this.audioStreamsMap.keys()].find(({id:w})=>w===g?.id)??this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current: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 x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{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}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;if(A&&R)return[A,R];if(A&&!R&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:wE.DOM,thrown:e}))}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),Re(this.video),this.tracer.end()}};var dn=class extends rr{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 xp,merge as PE,filter as AE,filterChanged as RE,isNullable as kp,map as $E,ValueSubject as Pp,isNonNullable as P_}from"@vkontakte/videoplayer-shared";var pn=class extends rr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Pp(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(RE()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.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(a.isLowLatency.stateChangeEnded$.pipe($E(u=>u.to)).subscribe(this.player.isLowLatency$)).add(xp({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe($E(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u*1e3+l+t:void 0)).subscribe(i.liveTime$)).add(xp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:PE(r.playbackRateState$,new Pp(1))}).pipe(AE(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||kp(p)||(t=u-p)})).add(xp({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:PE(r.playbackRateState$,new Pp(1))}).pipe(RE((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||kp(u)||kp(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=KI(u);this.params.output.availableTextTracks$.next([l])}})),this.params.tuning.dashCmafLive.externalStopControl||this.subscription.add(this.player.liveStreamStatus$.pipe(AE(u=>P_(u))).subscribe(u=>i.isLiveEnded$.next(u==="unpublished"&&i.position$.getValue()===0)))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};import{assertNever as tO,assertNonNullable as iO,combine as rO,debounce as sO,ErrorCategory as QE,filter as jp,filterChanged as In,fromEvent as aO,isNonNullable as GE,isNullable as nO,map as En,merge as wn,observableFrom as Ou,once as YE,Subscription as oO}from"@vkontakte/videoplayer-shared";var WE=D(Pe(),1),Up=D(Gi(),1);import{abortable as _p,assertNonNullable as bs,combine as gs,ErrorCategory as wt,filter as Cu,filterChanged as vn,flattenObject as yn,fromEvent as Bt,getTraceSubscriptionMethod as H_,interval as Op,isNonNullable as Tn,isNullable as HE,map as Ss,merge as ur,now as Np,Subject as Kt,Subscription as Fp,SubscriptionRemovable as z_,tap as W_,throttle as zE,ValueSubject as te}from"@vkontakte/videoplayer-shared";var Mu=D(Pe(),1),or=D(Ge(),1),Lu=D(Gi(),1);var FE=D($o(),1);import{assertNever as A_,ErrorCategory as ME,Subject as LE}from"@vkontakte/videoplayer-shared";var R_=18,DE=!1;try{DE=$.browser.isSafari&&!!$.browser.safariVersion&&$.browser.safariVersion<=R_}catch(s){console.error(s)}var Ap=class{constructor(e,t=!1){this.bufferFull$=new LE;this.error$=new LE;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.isAbortFixEnabled=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null,this.isAbortFixEnabled&&this.queue.shift()}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:ME.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.isAbortFixEnabled=t,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i,r=a=>{this.abortRequested=!1,t(a)};DE&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:a}of this.queue)a(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.isAbortFixEnabled?this.queue[0]:this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(r){r instanceof DOMException&&r.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):r instanceof DOMException&&r.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:ME.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:r}),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:A_(t)}}},BE=Ap;import{abortable as Ii,assertNonNullable as He,ErrorCategory as ar,fromEvent as Dp,getExponentialDelay as Bp,isHigher as B_,isNonNullable as Ei,isNullable as fe,now as $u,once as C_,Subject as V_,Subscription as __,ValueSubject as nr}from"@vkontakte/videoplayer-shared";var Rp=D(Ge(),1);import{videoSizeToQuality as $_,throttleFn as M_}from"@vkontakte/videoplayer-shared";var hn=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a,streamId:n})=>{let o=(a?Mt(a):void 0)??$_({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},CE=({id:s,bitrate:e})=>({id:s,bitrate:e}),VE=({language:s,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),_E=({language:s,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:s,label:e}),$p=({id:s,language:e,label:t,codecs:i,isDefault:r})=>({id:s,language:e,label:t,codec:(0,Rp.default)(i.split("."),0),isDefault:r}),Mp=({id:s,language:e,label:t,hdr:i,codecs:r})=>({id:s,language:e,hdr:i,label:t,codec:(0,Rp.default)(r.split("."),0)}),Lp=s=>"url"in s,rt=s=>s.type==="template";var OE=s=>{s.sort((t,i)=>t.from-i.from);let e=[s[0]];for(let t=1;t<s.length;t++){let{from:i,to:r}=s[t],a=e[e.length-1];a.to>=i?a.to=Math.max(a.to,r):e.push(s[t])}return e},sr=(s,e)=>{for(let t of s)if(e(t))return t;return null},NE=s=>{let e=!1,t=M_(()=>{e=!0},s);return()=>{try{return t(),e}finally{e=!1}}};import{fromEvent as L_,Subscription as D_}from"@vkontakte/videoplayer-shared";var Au=s=>{let e=[];for(let t=0;t<s.length;t++){let i=Math.floor(s.start(t)*1e3),r=Math.ceil(s.end(t)*1e3);e.push(i,r)}return e};var Ru=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new D_;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add(L_(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!V(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Au(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],a=e[i+1],n=t[i],o=t[i+1];if(n>r||o<a)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var fn=class{constructor(e,t,i,{fetcher:r,tuning:a,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new nr(0);this.currentLowLatencySegmentLength$=new nr(0);this.currentSegmentLength$=new nr(0);this.onLastSegment$=new nr(!1);this.fullyBuffered$=new nr(!1);this.playingRepresentation$=new nr(void 0);this.playingRepresentationInit$=new nr(void 0);this.error$=new V_;this.gaps=[];this.subscription=new __;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new j;this.switchAbortController=new j;this.destroyAbortController=new j;this.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=Ii(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);He(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new BE(this.sourceBuffer,this.tuning.dash.useAbortMSEFix),this.sourceBufferBufferedDiff=new Ru(this.mediaSource,this.sourceBuffer),this.subscription.add(Dp(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add(Dp(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:ar.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!V(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,os(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=pe(this.sourceBuffer.buffered,o),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<p).catch(c=>{this.handleAsyncError(c,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);He(i,"No init buffer for starting representation"),He(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=Ii(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(fe(a)||fe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),He(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();Ei(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Ii(this.destroyAbortController.signal,async function*(e,t=!1){if(!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);He(i,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(fe(a)||fe(r)?yield this.loadInit(i,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),He(r,"No segments for starting representation"),a=this.initData.get(e),!(!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Ei(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Ii(this.destroyAbortController.signal,async function*(e){let t=(0,Lu.default)(e,u=>u.representations);if(!this.downloadingRepresentationId||!t.length)return;this.isSeekingLive=!0;for(let u of this.representations.keys()){let l=t.find(d=>d.id===u);l&&this.representations.set(u,l);let p=this.representations.get(u);if(!p||!rt(p.segmentReference)){this.isSeekingLive=!1;return}let c=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,c)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);He(r,`Representation not found by id ${i}`);let a=this.segments.get(i);He(a,"No segments for starting representation");let n=this.initData.get(i);if(He(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer)){this.isSeekingLive=!1;return}let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=a,this.compatibilityMode=u,this.forwardBufferTarget=a.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!V(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new j,Ii(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let a=this.representations.get(i);He(a,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(fe(o)||fe(n)?yield this.loadInit(a,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),He(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Ei(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!fe(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new j,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(fe(e)||fe(this.downloadingRepresentationId)||fe(this.playingRepresentationId)||fe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||Ei(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),a=this.segments.get(this.playingRepresentationId);if(He(t,`No such representation ${this.downloadingRepresentationId}`),He(i,`No such representation ${this.playingRepresentationId}`),fe(r)||fe(a))return;let n=r.find(d=>e>=d.time.from&&e<d.time.to);Ei(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let o=e,u=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=this.getForwardBufferDuration(e),h=hn(i),f=hn(t),m=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&Ei(h)&&Ei(f)&&B_(h.quality,f.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(m||S?o+=Math.min(d,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=n.time.to-e+u&&(o=n?n.time.to+u:-1/0),this.tuning.dash.useNewRepresentationSwitch){let v=[...this.segments.entries()].map(([T,y])=>{let x=y.find(A=>e>=A.time.from&&e<A.time.to);return{representationId:T,status:x?.status}}).find(T=>T.status==="fed")?.representationId;v&&(this.playingRepresentationId=v,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)))}}if(isFinite(this.bufferLimit)&&os(this.sourceBuffer.buffered)>=this.bufferLimit){let d=pe(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h).catch(f=>{this.handleAsyncError(f,"pruneBuffer")});return}let p=null;if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,o),p?.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,Mu.default)(p,n))d="high";else{let h=(0,or.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(p,t,d).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p?.length&&pe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let c=(0,or.default)(r,-1);!this.isLive&&c&&(this.fullyBuffered$.next(c.time.to-e-pe(this.sourceBuffer.buffered,e)<u),this.onLastSegment$.next(e-c.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r,persistent:!0}),i=a.time.to;Ei(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind];if(!t)return;let i=(0,Lu.default)(t,a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!i)return;let r=this.segments.get(i.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){if(!e||[...this.segments.values()].every(i=>!i.length))return;let t=(0,Lu.default)(e.streams[this.kind],i=>i.representations)??[];for(let i of t){if(!i||!rt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),a=100,n=this.segments.get(i.id)??[],o=(0,or.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+a&&o<=l.time.to+a);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(u+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;He(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!rt(r))return;let a=this.segments.get(i.id);if(!a)continue;let n=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=tt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);return i?i.find(a=>a.time.from<=e&&a.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.sourceBufferBufferedDiff?.destroy(),this.gapDetectionIdleCallback&&lt&&lt(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&lt&&lt(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.checkEjectedSegments(),this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){if(this.playingRepresentationId!==this.downloadingRepresentationId){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);this.liveUpdateSegmentIndex=i}return this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):null}selectForwardBufferSegmentsRecord(e,t,i){let r=this.getForwardBufferDuration(i),a=e.findIndex(({status:d,time:{from:h,to:f}},m)=>{let S=h<=i&&f>=i,g=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+v||r<v&&f-h>=v||f<=i+v;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&V(this.mediaSource,this.sourceBuffer)&&!(Be(this.sourceBuffer.buffered,h)&&Be(this.sourceBuffer.buffered,f)))&&g&&T});if(a===-1)return null;if(t!=="byteRange")return e.slice(a,a+1);let n=e,o=0,u=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<n.length&&(o<=p||u<=c);d++){let h=n[d];if(o+=h.byte.to+1-h.byte.from,u+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")l.push(h);else break}return l}async loadSegments(e,t,i="auto"){rt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Ii(o,async function*(){let p=Bp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,p))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let p=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=$u(),!p)return;let c=new DataView(p),d=ct(t.mime);if(!isFinite(r.segment.time.to)){let m=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(c,m)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=d.getServerLatencyTimestamps(c);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),De(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())rt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Ii(n,async function*(){let u=Bp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Dp(window,"online").pipe(C_()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=$u(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),De(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(rt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,or.default)(e,0).byte.from,to:(0,or.default)(e,-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:async(o,u)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=$u(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:ar.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!rt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!a.aborted)try{this.lastDataObtainedTimestampMs=$u();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:ar.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Mu.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),p=ct(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(u.status="partially_fed",o.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),o.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!V(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(a.aborted){await n();continue}let{segment:l}=u,p=l.byte.from-i,c=l.byte.to-i,d=c-p+1,h=p<r,f=c<=r;if(h){if(l.status==="downloading"&&f){l.status="downloaded";let m=new DataView(e.buffer,e.byteOffset+p,d);await this.sourceBufferTaskQueue.append(m,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(d,r-p),u.loadedBytes>u.feedingBytes)){let m=new DataView(e.buffer,e.byteOffset+p+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===d?m:ct(o.mime).parseFeedableSegmentChunk(m);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,a)&&!a.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===d&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!(fe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer))){!this.isLive&&$.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Be(this.sourceBuffer.buffered,e.segment.time.from,100)&&Be(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:ar.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",Lp(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let a of r)a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let n=a instanceof Promise;t||=n,a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Lt(()=>(0,FE.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=Bp(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ct(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:p}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let d=p;this.isLive&&rt(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),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:ar.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||!V(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||fe(e))return!1;this.checkEjectedSegments();let r=[],a=0,n=o=>{if(a>=t)return;r.push({...o.time});let u=Lp(o)?o.size??0:o.byte.to-o.byte.from;a+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&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,p=0;for(let c of this.segments.values())for(let d of c)(0,Mu.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(u)&&Math.round(d.time.to)>=Math.round(l)&&p++;if(p===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=OE(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||!V(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||!V(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||!V(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||!V(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||fe(e)?0:pe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let a=0;a<i.length;a++){let n=i.start(a)*1e3,o=i.end(a)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!V(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let a=Math.round(r.from),n=Math.round(r.to);for(let o=0;o<i.length;o++)if(a>=Math.round(i.start(o)*1e3)&&n<=Math.round(i.end(o)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=Lt(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:ar.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if(fe(this.sourceBuffer)||!V(this.mediaSource,this.sourceBuffer)||fe(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Au(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let p=0;p<e.length;p+=2){let c=e[p],d=e[p+1];u||(u=c-t<=n&&d+t>=o),(n>=c&&n<d-t||o>c+t&&o<=d)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:ar.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,or.default)(e,-1)?.time.to:0)||0}};import{abortable as mn,assertNever as UE,fromEvent as qE,merge as O_,now as bn,Subject as fs,ValueSubject as Cp,flattenObject as ms,ErrorCategory as gn,SubscriptionRemovable as N_}from"@vkontakte/videoplayer-shared";var Bu=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:a=!1}){this.manifestRequested$=new fs;this.firstBytesManifest$=new fs;this.firstBytesRequested$=new fs;this.firstBytesReceived$=new fs;this.lastConnectionType$=new Cp(void 0);this.lastConnectionReused$=new Cp(void 0);this.lastRequestFirstBytes$=new Cp(void 0);this.recoverableError$=new fs;this.error$=new fs;this.abortAllController=new j;this.subscription=new N_;this.fetchManifest=mn(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=It(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Qr(i)),this.manifestRequested$.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Du);return r?(t.log("success",ms({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),this.firstBytesManifest$.next(),r.text()):(t.error("error",ms({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=mn(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1,bufferOptimisation:l=!1}={}){let p=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(p,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),p=E.toString();break}default:UE(t)}this.requestQuic&&(p=It(p));let h=this.abortAllController.signal,f;if(n){let E=new j;if(f=O_(qE(this.abortAllController.signal,"abort"),qE(n,"abort")).subscribe(()=>{try{E.abort()}catch(I){Du(I)}}),this.subscription.add(f),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(I){Du(I)}h=E.signal}let m=0,S=bn();d.log("startRequest",ms({url:p,priority:a,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:S})),this.firstBytesRequested$.next();let g=yield this.doFetch(p,{priority:a,headers:c,signal:h}),v=bn();if(!g)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(f),null;if(this.throughputEstimator?.addRawRtt(v-S),!g.ok||!g.body){this.unsubscribeAbortSubscription(f);let E=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:E}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){this.unsubscribeAbortSubscription(f);let E=bn(),I={requestStartedAt:S,requestEndedAt:E,duration:E-S};return d.log("endRequest",ms(I)),d.end(),g.arrayBuffer()}let T=g.body;if(o){let E;[T,E]=g.body.tee(),this.throughputEstimator?.trackStream(E,u)}let y=T.getReader(),x,A=parseInt(g.headers.get("content-length")??"",10);Number.isFinite(A)&&(x=A),!x&&i&&(x=i.to-i.from+1);let R=x?new Uint8Array(x):new Uint8Array(0),w=!1,B=E=>{this.unsubscribeAbortSubscription(f),w=!0,Du(E)},k=mn(h,async function*({done:E,value:I}){if(m===0&&(this.lastRequestFirstBytes$.next(bn()-S),this.firstBytesReceived$.next()),h.aborted){this.unsubscribeAbortSubscription(f);return}if(!E&&I){if(l&&x)R.set(I,m),m+=I.byteLength;else{let N=new Uint8Array(R.length+I.length);N.set(R),N.set(I,R.length),R=N,m+=I.byteLength}r?.(new DataView(R.buffer),m),yield y?.read().then(k,B)}}.bind(this));yield y?.read().then(k,B),this.unsubscribeAbortSubscription(f);let F=bn(),C={failed:w,requestStartedAt:S,requestEndedAt:F,duration:F-S};return w?(d.error("endRequest",ms(C)),d.end(),null):(d.log("endRequest",ms(C)),d.end(),R.buffer)}.bind(this));this.fetchByteRangeRepresentation=mn(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,n=r,o=a,u=!1,l,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,u=a+1===l,u&&(n=Math.min(l,r),o=Math.max(p,a))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!c)return null;let d=new DataView(c,r-n,a-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let m;if(u)m=new DataView(c,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:i,measureThroughput:!1});if(!g)return null;m=new DataView(g)}let S=t.parseSegments(m,h,f);return{init:h,dataView:new DataView(c),segments:S}}.bind(this));this.fetchTemplateRepresentation=mn(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=a}onHeadersReceived(e){let{type:t,reused:i}=Wr(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:r}=e;switch(r){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:UE(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await Ke(e,t);if(i.ok)return i;let r=await i.text(),a=parseInt(r);if(!isNaN(a))switch(a){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:gn.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:gn.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:gn.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:gn.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${a})`,category:gn.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Du=s=>{if(!De(s))throw s};import{isNullable as F_,ValueSubject as U_}from"@vkontakte/videoplayer-shared";var Sn=class s{constructor(e,t){this.currentRepresentation$=new U_(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e?.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){if(!F_(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,a=r.segments.length,n=r.segments[0].time.from,o=r.segments[a-1].time.to;if(e<n||e>o)continue;let u=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=s.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>s.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&rt(t.segmentReference))}};var Q_=["progress","play","seeked","stalled","waiting"],G_=["timeupdate","progress","loadeddata","playing","seeked"];var Vu=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new Fp;this.subscriptionRemovable=new z_;this.representationSubscription=new Fp;this.state$=new O("none");this.currentVideoRepresentation$=new te(void 0);this.currentVideoRepresentationInit$=new te(void 0);this.currentAudioRepresentation$=new te(void 0);this.currentVideoSegmentLength$=new te(0);this.currentAudioSegmentLength$=new te(0);this.error$=new Kt;this.manifestRequested$=new Kt;this.firstBytesManifest$=new Kt;this.manifestReceived$=new Kt;this.firstBytesRequested$=new Kt;this.firstBytesReceived$=new Kt;this.lastConnectionType$=new te(void 0);this.lastConnectionReused$=new te(void 0);this.lastRequestFirstBytes$=new te(void 0);this.currentLiveTextRepresentation$=new te(null);this.isLive$=new te(!1);this.isActiveLive$=new te(!1);this.isLowLatency$=new te(!1);this.liveDuration$=new te(0);this.liveSeekableDuration$=new te(0);this.liveAvailabilityStartTime$=new te(0);this.liveStreamStatus$=new te(void 0);this.bufferLength$=new te(0);this.liveLatency$=new te(void 0);this.liveLoadBufferLength$=new te(0);this.livePositionFromPlayer$=new te(0);this.currentStallDuration$=new te(0);this.videoLastDataObtainedTimestamp$=new te(0);this.fetcherRecoverableError$=new Kt;this.fetcherError$=new Kt;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Kt;this.gapWatchdogActive=!1;this.destroyController=new j;this.initManifest=_p(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ne(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:wt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=_p(this.destroyController.signal,async function*(){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:wt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Jr(e??"",this.manifestUrlString),this.manifestReceived$.next()}catch(u){let l=zr(e)??{id:"ManifestParsing",category:wt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,p)=>!!(this.element?.canPlayType?.(l)&&_e()?.isTypeSupported?.(`${l}; codecs="${p}"`)||u==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:c}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";c||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},a,n;for(let u of["video","audio"]){let p=t.streams[u].filter(({mime:d,codecs:h})=>i(u,d,h));r[u]=p;let c;if(this.tuning.dash.codecsPrioritizeEnabled){let d=p.map(({codecs:h})=>h);u==="audio"&&(n=ts(d),c=n[0]),u==="video"&&(a=es(d),this.forceVideoCodec&&(0,WE.default)(a,this.forceVideoCodec)?c=this.forceVideoCodec:c=a[0]),c&&(r[u]=p.filter(({codecs:h})=>fi(h)===c))}else{let d=new Set(p.map(({codecs:h})=>h));c=Zr(d),c&&(r[u]=p.filter(({codecs:h})=>h.startsWith(c)))}if(u==="video"){let d=this.tuning.preferHDR,h=r.video.some(m=>m.hdr),f=r.video.some(m=>!m.hdr);$.display.isHDR&&d&&h?r.video=r.video.filter(m=>m.hdr):f&&(r.video=r.video.filter(m=>!m.hdr))}}let o={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(o.codecs={video:a,audio:n}),this.tracer.log("updateManifestEnd",yn(o)),o}.bind(this));this.initRepresentations=_p(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",yn({initialVideo:e,initialAudio:t,sourceHls:i})),bs(this.manifest),bs(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new Fp,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add(Bt(d,"error").pipe(Cu(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:wt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Er();let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),ni())if(i){let d=document.createElement("source");r(d),d.type="application/x-mpegurl",d.src=i.url,this.element.appendChild(d)}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((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new fn("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Tn(t)){let d=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new fn("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}Sn.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Sn(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ur(...G_.map(d=>Bt(this.element,d))).pipe(Ss(d=>this.element?pe(this.element.buffered,this.element.currentTime*1e3):0),vn(),W_(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ur(Bt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(vn()).subscribe(h=>this.liveStreamEndTimestamp=Np())),this.subscription.add(Bt(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=Op(1e3).subscribe(h=>{let f=ai(this.manifestUrlString,2);this.manifestUrlString=ne(this.manifestUrlString,f+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(Bt(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add(gs({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Ss(({isActiveLive:h,isLowLatency:f})=>h&&f),vn()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||cs(this.element,1)})),this.representationSubscription.add(gs({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Cu(({bufferLength:h,isActiveLive:f,isLowLatency:m})=>f&&m&&!!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 f=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(f,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add(gs({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Cu(({isLive:h})=>h),vn((h,f)=>f.bufferLength<h.bufferLength),Ss(({rtt:h,bufferLength:f,segmentServerLatency:m})=>{let S=ai(this.manifestUrlString,2);return(h/2+f+m+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(gs({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:f,isLowLatency:m})=>{if(!m||!f)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-S;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(T)>g&&(y=1+Math.sign(T)*v),cs(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let m=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??m))-m}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let d=0;this.representationSubscription.add(gs({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(zE(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(!this.element||this.isUpdatingLive)return;let m=this.element.playbackRate,S=ai(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*m),T=this.tuning.dashCmafLive.normalizedActualBufferOffset*m,y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*m,x=isFinite(h)?h:f,A=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),R=g<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(R);let w="none";if(A?w="active_low_latency":this.isLowLatency$.getValue()&&R?(this.bufferManagers.forEach(B=>B.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&x<v?w="live_forward_buffering":x<v+y&&(w="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),w==="live_forward_buffering"||w==="live_with_target_offset"){let B=d-(v+T),k=this.normolizeLiveOffset(Math.trunc(S+B/m)),F=Math.abs(k-S),C=0;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?C=S:k>0&&F>this.tuning.dashCmafLive.offsetCalculationError&&(C=k),this.manifestUrlString=ne(this.manifestUrlString,C,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:wt.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=ur(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe(Ss(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),p=ur(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe(Ss(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),c=gs({allBuffersFull:l,someBufferEnded:p}).pipe(vn(),Ss(({allBuffersFull:d,someBufferEnded:h})=>d&&h),Cu(d=>d));if(this.representationSubscription.add(ur(this.forceEnded$,c).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{this.source?.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:wt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(ur(...this.bufferManagers.map(d=>d.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 d=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{d&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:wt.VIDEO_PIPELINE,message:"Failed to open MediaSource",thrown:new Error("Timeout reject when wait sourceopen event"),traceAsLog:!0})},this.tuning.dash.sourceOpenTimeout)),this.source?.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),h()},{once:!0})})}if(!this.isLive$.getValue()){let d=[this.manifest.duration??0,...(0,Up.default)((0,Up.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),rt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&Tn(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=()=>{if(!this.element||!this.videoBufferManager||this.source?.readyState!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Op(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:wt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Bu({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.subscription.add(this.fetcher.manifestRequested$.subscribe(this.manifestRequested$)),this.subscription.add(this.fetcher.firstBytesManifest$.subscribe(this.firstBytesManifest$)),this.subscription.add(this.fetcher.firstBytesRequested$.subscribe(this.firstBytesRequested$)),this.subscription.add(this.fetcher.firstBytesReceived$.subscribe(this.firstBytesReceived$)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.liveBuffer=Qt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){bs(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?Np()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ne(this.manifestUrlString,i,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){bs(this.element),this.state$.setState("running");let e=Bt(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe(zE(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add(ur(...Q_.map(t=>Bt(this.element,t)),Bt(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:wt.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add(Bt(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(Bt(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&Be(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let t=()=>{if(!this.element||this.source?.readyState!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},a=Np(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,c=l<n&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&p<n&&a-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&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 h=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(h).catch(f=>{this.error$.next({id:"stallIntervalCallback",category:wt.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:f})}),r.liveLastOffset=h}else{let h=this.element.currentTime*1e3;this.videoBufferManager?.maintain(h),this.audioBufferManager?.maintain(h),r.position=h}this.tracer.log("stallIntervalCallback",yn(r))};this.stallWatchdogSubscription&&(this.stallWatchdogSubscription.unsubscribe(),this.subscriptionRemovable.remove(this.stallWatchdogSubscription)),this.stallWatchdogSubscription=Op(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:wt.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscriptionRemovable.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){bs(this.element),bs(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(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),this.warmUpMediaSourceIfNeeded(i),Be(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!(HE(this.element)||HE(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",yn({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){Tn(this.element)&&Tn(this.source)&&Tn(e)&&this.source?.readyState==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(t=>t.warmUpMediaSource())}get isStreamEnded(){return this.source?.readyState==="ended"}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}getCodecs(){return this.manifest?.codecs}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.subscriptionRemovable.unsubscribe(),this.representationSubscription.unsubscribe(),this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=H_(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(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getBufferedTo();if(e===null)return;let t=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i=this.isJumpGapAfterSeekLive,r=this.element.currentTime;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let a=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=a&&l.to+o>a&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",yn({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};import{combine as Y_,map as K_,observeElementSize as X_,Subscription as J_,ValueSubject as qp,noop as Z_}from"@vkontakte/videoplayer-shared";var _u=class{constructor(){this.subscription=new J_;this.pipSize$=new qp(void 0);this.videoSize$=new qp(void 0);this.elementSize$=new qp(void 0);this.pictureInPictureWindowRemoveEventListener=Z_}connect({observableVideo:e,video:t}){let i=r=>{let a=r.target;this.pipSize$.next({width:a.width,height:a.height})};this.subscription.add(X_(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(Y_({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(K_(({videoSize:r,inPip:a,pipSize:n})=>a?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var lr=class{constructor(e){this.subscription=new oO;this.videoState=new O("stopped");this.observableVideo=null;this.droppedFramesManager=new ci;this.stallsManager=new jr;this.elementSizeManager=new _u;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Tt;this.audioTrackSwitchHistory=new Tt;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?.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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&P(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?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return tO(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new pi(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.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 Qe(e.source.url),this.params=e,this.video=Ae(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(de(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 Vu({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;nO(this.observableVideo)&&(this.observableVideo=Me(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:QE.WTF,message:`${i} internal logic error`,thrown:n})},a=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:a}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(jp(c=>!!c.length),YE()).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(En(c=>c.to.state!=="none"),In());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$,duration:this.video.duration}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.currentBuffer$,e.currentNativeBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(i.loadedMetadata$,e.loadedMetadataEvent$),a(this.player.error$,e.error$),a(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),a(this.player.fetcherError$,e.fetcherError$),a(this.player.manifestRequested$,e.manifestRequested$),a(this.player.firstBytesManifest$,e.firstBytesManifest$),a(this.player.manifestReceived$,e.manifestReceived$),a(this.player.firstBytesRequested$,e.firstBytesRequested$),a(this.player.firstBytesReceived$,e.firstBytesReceived$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(jp(GE),YE()),e.firstBytesEvent$),a(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),a(this.videoState.stateChangeEnded$.pipe(En(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(ot(this.video,t.isLooped,r)),this.subscription.add($e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(We(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),a(Ye(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},r)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),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 d=this.player.getStreams(),h=this.player.getCodecs();if(iO(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let S of d.audio){m.push($p(S));let g=[];for(let v of S.representations){let T=CE(v);g.push(T),this.audioTracksMap.set(T,{stream:S,representation:v})}this.audioStreamsMap.set(S,g)}this.params.output.availableAudioStreams$.next(m)}let f=[];for(let m of d.video){f.push(Mp(m));let S=[];for(let g of m.representations){let v=hn({...g,streamId:m.id});v&&(S.push(v),this.videoTracksMap.set(v,{stream:m,representation:g}))}this.videoStreamsMap.set(m,S)}this.params.output.availableVideoStreams$.next(f);for(let m of d.text)for(let S of m.representations){let g=VE(m,S);this.textTracksMap.set(g,{stream:m,representation:S})}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),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),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&&NE(o)||null;this.subscription.add(wn(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$,aO(this.video,"progress")).pipe(jp(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(c!=="manifest_ready"&&c!=="running"||d||c==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:f}=this.selectedRepresentations;if(!h)return;let m=sr(this.videoTracksMap.keys(),g=>this.videoTracksMap.get(g)?.representation.id===h.id);GE(m)&&(this.stallsManager.lastVideoTrackSelected=m);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),c==="manifest_ready")await this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),f){let g=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",f.id,g)}},r)),this.subscription.add(rO({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:wn(Ou([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe(En(c=>c.to)))}).pipe(En(({videoState:c,autoVideoTrackState:d})=>c.to!=="stopped"&&d),In()).subscribe(c=>this.player.setSmartRepresentationSwitch(c))),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(In()).subscribe(c=>{let d=sr(this.videoTracksMap.entries(),([,{representation:g}])=>g.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Mp(f));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(In()).subscribe(c=>{let d=sr(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:f}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===f.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next($p(f))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.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(En(({to:c})=>c==="ready"),In());this.subscription.add(wn(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,Ou(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(wn(l,this.player.state$.stateChangeEnded$,Ou(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=wn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ou(["init"])).pipe(sO(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?Qi:Wi,t=this.params.tuning.useNewAutoSelectVideoTrack?Ur:Fr,i=this.params.tuning.useNewAutoSelectVideoTrack?ut:Nr,{desiredState:r,output:a}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=sr(this.videoTracksMap.keys(),w=>w.id===o),l=a.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let c=sr(this.videoStreamsMap.keys(),w=>w.id===p.id),d=c&&this.videoStreamsMap.get(c);if(!d)return;let h=pe(this.video.buffered,this.video.currentTime*1e3),f;this.player.isActiveLive$.getValue()?f=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?f=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:f=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(f,m||1/0),1),g=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),v=g?.id&&sr(this.audioStreamsMap.keys(),w=>w.id===g.id)||this.audioStreamsMap.keys().next().value,T=0;if(v){if(u&&!n){let w=e(u,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}if(l){let w=e(l,d,this.audioStreamsMap.get(v)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);T=Math.max(T,w?.bitrate??-1/0)}}let y=u;(n||!y)&&(y=i(d,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:T,forwardBufferHealth:S,current: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 x=v&&t(y,d,this.audioStreamsMap.get(v)??[],{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}),A=this.videoTracksMap.get(y)?.representation,R=x&&this.audioTracksMap.get(x)?.representation;A&&R?(this.selectedRepresentations.video=A,this.selectedRepresentations.audio=R):A&&!R&&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(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:QE.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),Re(this.video),this.tracer.end()}};var xn=class extends lr{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Hp,merge as KE,filter as XE,filterChanged as JE,isNullable as zp,map as ZE,ValueSubject as Wp,isNonNullable as uO}from"@vkontakte/videoplayer-shared";var kn=class extends lr{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:a,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let o=new Wp(1);n(r.playbackRateState$,o),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe(JE()).subscribe(u=>{let l=i.position$.getValue(),p=i.volume$.getValue(),c=!p.volume||p.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(a.isLowLatency.stateChangeEnded$.pipe(ZE(u=>u.to)).subscribe(this.player.isLowLatency$)).add(Hp({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ZE(({liveBufferTime:u,liveAvailabilityStartTime:l})=>u&&l?u+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe(XE(u=>uO(u))).subscribe(u=>i.isLiveEnded$.next(u!=="active"&&i.position$.getValue()===0))).add(Hp({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:KE(r.playbackRateState$,new Wp(1))}).pipe(XE(({liveStreamStatus:u,liveDuration:l})=>u==="active"&&!!l)).subscribe(({liveDuration:u,playbackRate:l})=>{let p=i.liveBufferTime$.getValue(),c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||l<1-d||this.video.paused||zp(p)||(t=u-p)})).add(Hp({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:KE(r.playbackRateState$,new Wp(1))}).pipe(JE((u,l)=>this.player.liveStreamStatus$.getValue()==="active"?u.liveDuration===l.liveDuration:u.time===l.time)).subscribe(({time:u,liveDuration:l,playbackRate:p})=>{let c=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&p>=1-d||zp(u)||zp(l))return;let h=-1*(l-u-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(u=>{if(u){let l=_E(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 ew="X-Playback-Duration",Qp=async s=>{let e=await Ke(s),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(ew)?parseInt(e.headers.get(ew),10):void 0};import{assertNever as vO,combine as yO,debounce as TO,ErrorCategory as Uu,filter as IO,filterChanged as EO,isNonNullable as rw,isNullable as qu,map as sw,merge as wO,observableFrom as xO,Subscription as kO,ValueSubject as Kp,VideoQuality as PO}from"@vkontakte/videoplayer-shared";var Yp=D(vc(),1);import{videoSizeToQuality as lO,getExponentialDelay as cO}from"@vkontakte/videoplayer-shared";var dO=s=>{let e=null;if(s.QUALITY&&(e=Mt(s.QUALITY)),!e&&s.RESOLUTION){let[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=lO({width:t,height:i})}return e??null},pO=(s,e)=>{let t=s.split(`
179
+ `),i=[],r=[];for(let a=0;a<t.length;a++){let n=t[a],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,Yp.default)(o[1].split(",").map(S=>S.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,c=dO(l),d;l.BANDWIDTH&&(d=parseInt(l.BANDWIDTH,10)/1e3||void 0),!d&&l["AVERAGE-BANDWIDTH"]&&(d=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[S,g]=l.RESOLUTION.split("x").map(v=>parseInt(v,10));S&&g&&(f={width:S,height:g})}let m=new URL(t[++a],e).toString();c&&i.push({id:p,quality:c,url:m,bandwidth:d,size:f,fps:h})}if(u){let l=(0,Yp.default)(u[1].split(",").map(h=>{let f=h.indexOf("=");return[h.substring(0,f),h.substring(f+1)]}).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,d=l.NAME;p&&c&&r.push({type:"internal",id:c,label:d,language:c,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},hO=s=>new Promise(e=>{setTimeout(()=>{e()},s)}),Gp=0,tw=async(s,e=s,t,i)=>{let a=await(await Ke(s,i)).text();Gp+=1;try{let{qualityManifests:n,textTracks:o}=pO(a,e);return{qualityManifests:n,textTracks:o}}catch{if(Gp<=t.manifestRetryMaxCount)return await hO(cO(Gp-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),tw(s,e,t)}return{qualityManifests:[],textTracks:[]}},Nu=tw;import{isNonNullable as fO,Subscription as mO,throttle as bO,ValueSubject as iw,Subject as gO,ErrorCategory as SO}from"@vkontakte/videoplayer-shared";var Fu=class{constructor(e,t,i,r,a){this.subscription=new mO;this.abortControllers={destroy:new j,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new iw(null);this.getCurrentTime$=new iw(null);this.error$=new gO;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:a},this.subscription.add(e.pipe(bO(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 Ke(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
180
+ `),a=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),p=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:a,to:a+p},url:l}),a=a+p,!i.segmentStartTime){let c=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),a=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(fO(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new j;let{textTracks:e}=await this.fetchManifestData(),t=await this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}}async fetchManifestData(){let e=this.prepareUrl??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:SO.WTF,thrown:t,message:e})}};var Pn=class{constructor(e){this.subscription=new kO;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Kp([]);this.liveOffset=new ji;this.manifestStartTime$=new Kp(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),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?.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"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(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?.to==="playing"&&P(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 p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return vO(t)}};this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:PO.INVARIANT,url:this.params.source.url};let t=(i,r)=>Nu(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},r);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Fu(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Qe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Uu.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(r,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Uu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),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(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Kp(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:Uu.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Me(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add($e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(We(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ye(this.video),e.elementVisible$),this.liveTextManager?(a(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),a(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.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(EO(),sw(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(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&rw(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===c);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(de(d.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.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(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(yO({startTime:this.manifestStartTime$.pipe(IO(rw)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(sw(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let n=wO(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,xO(["init"])).pipe(TO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){let e=this.selectManifest();if(qu(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}=t?.to??i??{};for(let[l,p]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,c)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ne(r.toString(),this.liveOffset.getTotalOffset(),a);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Qp(n).then(o=>{if(!qu(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(qu(u)||!isFinite(u))&&Ke(n).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let c=new URL(p,n).toString();Qp(c).then(d=>{qu(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ne(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as AO,debounce as RO,ErrorCategory as Xp,fromEvent as Jp,isNonNullable as $O,isNullable as MO,map as aw,merge as nw,observableFrom as ow,Subscription as LO,ValueSubject as uw,VideoQuality as DO}from"@vkontakte/videoplayer-shared";var An=class{constructor(e){this.subscription=new LO;this.videoState=new O("stopped");this.manifests$=new uw([]);this.unmuteAfterBrowserResetsHappened=new uw(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||n||o){let p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);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?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?P(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),P(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?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return AO(t)}};this.textTracksManager=new Qe(e.source.url),this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:DO.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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Nu(ne(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.params.output.firstBytesManifest$.next(),this.manifests$.next([this.masterManifest,...t]),this.params.output.manifestReceived$.next(),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Xp.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":a;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Xp.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Me(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(aw(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(We(this.video,t.playbackRate,r.playbackRateState$,i)),hi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add($e(this.video,t.volume,r.volumeState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&$O(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(de(f.url)))}let c=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe(aw(o=>o.map(({id:u,quality:l,size:p,bandwidth:c,fps:d})=>({id:u,quality:l,size:p,fps:d,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!$.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(nw(Jp(o,"addtrack"),Jp(o,"removetrack"),Jp(o,"change"),ow(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=nw(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ow(["init"])).pipe(RO(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Re(this.video)}prepare(){let e=this.selectManifest();if(MO(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:a,min:n}=t?.to??i??{};for(let[o,u]of[[a,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&r.searchParams.set(u,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xp.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var dw=D(oi(),1),Zp=D(Bi(),1),pw=D(Ge(),1);import{assertNever as BO,assertNonNullable as lw,debounce as CO,ErrorCategory as cw,isHigherOrEqual as VO,isLowerOrEqual as _O,isNonNullable as OO,merge as NO,observableFrom as FO,Subscription as UO,map as qO}from"@vkontakte/videoplayer-shared";var Rn=class{constructor(e){this.subscription=new UO;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new Qe;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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!n){this.handleQualityLimitTransition(a.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(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?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return BO(e)}};this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),(0,dw.default)(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Zp.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:cw.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Me(this.video);this.subscription.add(()=>r.destroy());let a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentNativeBuffer$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.loadedMetadata$,e.loadedMetadataEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(qO(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),hi({subscription:this.subscription,desiredState:t,videoElement$:this.params.output.element$,observableVideo:r}),this.subscription.add($e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(We(this.video,t.playbackRate,r.playbackRateState$,i)),a(Ye(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&OO(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(u),p.playbackRate=u)}}this.videoState.getState()==="playing"&&!this.video.ended&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")})),this.textTracksManager.connect(this.video,t,e);let n=NO(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,FO(["init"])).pipe(CO(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),Re(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;lw(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];lw(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=It(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(de(t))}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cw.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=l=>{this.params.output.currentVideoTrack$.next(l),this.params.desiredState.videoTrack.startTransitionTo(l)},i=l=>{let p=ut(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=this.params.output.currentVideoTrack$.getValue()?.quality,a=!!(e.max||e.min),n=(0,Zp.default)(this.trackUrls).map(l=>l.track);if(!r||!a||Vr(e,n[0].quality,(0,pw.default)(n,-1)?.quality)){i();return}let o=e.max?_O(r,e.max):!0,u=e.min?VO(r,e.min):!0;o&&u||i(e)}};import{assertNever as fw,debounce as WO,merge as mw,observableFrom as QO,Subscription as GO,map as bw,ValueSubject as YO,ErrorCategory as th,VideoQuality as KO}from"@vkontakte/videoplayer-shared";import{ErrorCategory as jO}from"@vkontakte/videoplayer-shared";var hw=["stun:videostun.mycdn.me:80"],HO=1e3,zO=3,eh=()=>null,ju=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=eh;this.externalStopCallback=eh;this.externalErrorCallback=eh;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:hw}]};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:jO.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{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),HO)}normalizeOptions(e={}){let t={stunServerList:hw,maxRetryNumber:zO,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var $n=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new YO(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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),P(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?.to==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return fw(e)}};this.subscription=new GO,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ae(e.container,e.tuning),this.liveStreamClient=new ju(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),Re(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:th.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(mw(this.videoState.stateChangeStarted$.pipe(bw(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(bw(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=Me(this.video);this.subscription.add(()=>r.destroy());let a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.currentBuffer$,e.currentNativeBuffer$),a(Ye(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(()=>{this.videoState.getTransition()?.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($e(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 fw(n.to)}},i)).add(mw(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,QO(["init"])).pipe(WO(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(de(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:KO.INVARIANT}),this.video.srcObject=e,P(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.currentNativeBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:th.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Le(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:th.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var vs=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};import{assertNever as Mn,assertNonNullable as Xt,ErrorCategory as Hu,filter as Iw,isNonNullable as Ew,isNullable as rN,map as sN,merge as aN,once as nN,Subject as ie,Subscription as ww,ValueSubject as U,flattenObject as ih,devNull as oN,getWindow as uN}from"@vkontakte/videoplayer-shared";import{Observable as XO,map as gw,Subscription as JO,Subject as ZO}from"@vkontakte/videoplayer-shared";var Sw=s=>new XO(e=>{let t=new JO,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(gw(({from:l,to:p})=>`${l}-${p}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(gw(({type:l})=>l!==void 0)),n=new ZO,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),s.maxTransitionInterval),_({m:"hangup.set",l,id:o})})),t.add(r.subscribe(()=>{_({m:"hangup.cl",id:o}),window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(l=>{o&&(_({m:"hangup.rs.0",id:o}),window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval),_({m:"hangup.rs.1",id:o})))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as eN,Subscription as tN,combine as iN,filter as yw,once as Tw}from"@vkontakte/videoplayer-shared";function vw(){return new(window.AudioContext||window.webkitAudioContext)}var ys=class s{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new j;this.subscriptions=new tN;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(yw(a=>!!a.type),Tw()).subscribe(({type:a})=>this.subscribe(a)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){$.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(iN({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(yw(({playbackState:t,video:i,volume:{muted:r,volume:a}})=>t==="playing"&&!!i&&!r&&!!a),Tw()).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=vw();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let a=i.createMediaElementSource(e);return this.mediaElementSource=a,a.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:s.errorId,category:eN.VIDEO_PIPELINE,message:e?.message??`${s.errorId} exception`,thrown:e})}};var lN={chunkDuration:5e3,maxParallelRequests:5},Ln=class{constructor(e){this.current$=new U({type:void 0});this.providerError$=new ie;this.noAvailableProvidersError$=new ie;this.volumeMultiplierError$=new ie;this.providerOutput={position$:new U(0),duration$:new U(1/0),volume$:new U({muted:!1,volume:1}),availableVideoStreams$:new U([]),currentVideoStream$:new U(void 0),availableVideoTracks$:new U([]),currentVideoTrack$:new U(void 0),availableVideoCodecs$:new U([]),availableAudioStreams$:new U([]),currentAudioStream$:new U(void 0),availableAudioTracks$:new U([]),availableAudioCodecs$:new U([]),currentVideoSegmentLength$:new U(0),currentAudioSegmentLength$:new U(0),isAudioAvailable$:new U(!0),autoVideoTrackLimitingAvailable$:new U(!1),autoVideoTrackLimits$:new U(void 0),currentBuffer$:new U(void 0),currentNativeBuffer$:new U(void 0),isBuffering$:new U(!0),error$:new ie,fetcherError$:new ie,fetcherRecoverableError$:new ie,warning$:new ie,willSeekEvent$:new ie,soundProhibitedEvent$:new ie,seekedEvent$:new ie,loopedEvent$:new ie,endedEvent$:new ie,manifestRequested$:new ie,firstBytesManifest$:new ie,manifestReceived$:new ie,firstBytesRequested$:new ie,firstBytesReceived$:new ie,firstBytesEvent$:new ie,loadedMetadataEvent$:new ie,firstFrameEvent$:new ie,canplay$:new ie,isLive$:new U(void 0),isLiveEnded$:new U(null),canPlayLiveTailBuffer$:new U(!1),isLowLatency$:new U(!1),canChangePlaybackSpeed$:new U(!0),liveTime$:new U(void 0),liveBufferTime$:new U(void 0),liveLatency$:new U(void 0),severeStallOccurred$:new ie,availableTextTracks$:new U([]),currentTextTrack$:new U(void 0),hostname$:new U(void 0),httpConnectionType$:new U(void 0),httpConnectionReused$:new U(void 0),inPiP$:new U(!1),inFullscreen$:new U(!1),element$:new U(void 0),elementVisible$:new U(!0),availableSources$:new U(void 0),is3DVideo$:new U(!1),playbackState$:new U(""),getCurrentTime$:new U(null)};this.subscription=new ww;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=Hl([...OI(this.params.tuning),..._I(this.params.tuning)]).filter(l=>Ew(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(l=>!(0,rh.default)(r,l)),...t.filter(l=>(0,rh.default)(r,l))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.tracer.log("Selected formats",ih(a)),this.screenFormatsIterator=new vs(a);let n=[...ep(!0),...ep(!1)];this.chromecastFormatsIterator=new vs(n.filter(l=>Ew(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ys.isSupported()&&(this.volumeMultiplierManager=new ys(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){_.reset(),this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new vs(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(rN(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:Hu.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Mn(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:a};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Xt(u),this.params.tuning.useNewDashProvider?new xn({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtual&&!$.device.isMobile?new ns({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):this.params.tuning.useDashProviderVirtualMobile&&$.device.isMobile?new ns({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new dn({...o,source:u,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Xt(u),this.params.tuning.useNewDashProvider?new kn({...o,source:u}):new pn({...o,source:u})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let u=this.applyFailoverHost(t[e]);return Xt(u),new An({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Xt(u),new Pn({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Xt(u),new Rn({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Xt(u),new Fy({...o,source:u,config:{...lN,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Xt(u),new $n({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 Mn(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o={meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};if(this.params.tuning.chromecastPresentationApi&&this.params.dependencies.chromecastInitializer instanceof Ot){let{chromecastConnector:l}=this.params.dependencies.chromecastInitializer;return Xt(l),new Ns({...o,chromecastConnector:l})}let u=this.params.dependencies.chromecastInitializer.connection$.getValue();return Xt(u),new ta({...o,connection:u})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Mn(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Mn(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 Mn(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,xw.default)((0,sh.default)(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new ww,t=!1,i=0;e.add(aN(this.providerOutput.error$.pipe(Iw(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),Sw({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(sN(a=>({id:`ProviderHangup:${a}`,category:Hu.WTF,message:`A ${a} 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 a=this.params.desiredState.playbackState.transitionEnded$.pipe(Iw(({to:n})=>n==="playing"),nN()).subscribe(()=>t=!0);e.add(a)}));let r=()=>{let a=_.drain(),{logDashLiveDebug:n,sendDashLiveDebug:o}=this.params.tuning;if(n&&uN().console.log(`===== DASH_LIVE DEBUG START ====
181
181
  `,a.map(({time:u,data:l,stack:p})=>`${u}: ${JSON.stringify(l)}${p?`
182
182
  `+p:""}`).join(`
183
183
  `),`
184
- ===== DASH_LIVE DEBUG END ====`),o){let u=a.reduce((l,{time:p,data:c,stack:d})=>{let h=(0,ih.default)(c).map(([f,m])=>`${f}:${m}`).join(",");return l+=`${p}: ${h}${d?`: ${d}`:""};`,l},"");oN.push("core",{key:"vp_dash_live_debug",strings:[u]})}};return e.add(this.providerError$.subscribe(a=>{a.id.startsWith("ProviderHangup")&&(_({m:"final.0",e:a.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{_({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(a=>{let n=this.current$.getValue().destination,o={error:a,currentDestination:n};if(n==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=a.category===Hu.NETWORK,l=a.category===Hu.FATAL,p=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!l,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=p&&!l&&(u&&t||!c);o={...o,isNetworkError:u,isFatalError:l,haveFailoverHost:p,tryFailover:h,canReinitProvider:c},c?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(n??"SCREEN"))}a.traceAsLog?this.tracer.log("providerInfo",eh(o)):this.tracer.error("providerError",eh(o))})),e}};import{fromEvent as Wu,once as cN,combine as dN,Subscription as ww,ValueSubject as rh,map as xw,filter as pN,isNonNullable as zu,now as st,safeStorage as sh,getWindow as hN}from"@vkontakte/videoplayer-shared";var fN=5e3,Pw="one_video_throughput",kw="one_video_rtt",nh=()=>{let{navigator:s}=hN();if(s)return s.connection},Aw=()=>{let s=nh()?.downlink;if(zu(s)&&s!==10)return s*1e3},Rw=()=>{let s=nh()?.rtt;if(zu(s)&&s!==3e3)return s},$w=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},ah=class s{constructor(e){this.subscription=new ww;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=s.load(Pw)||(e.useBrowserEstimation?Aw():void 0)||fN,i=s.load(kw)??(e.useBrowserEstimation?Rw():void 0)??0;if(this.throughput$=new rh(t),this.rtt$=new rh(i),this.rttAdjustedThroughput$=new rh($w(t,i,e.rttPenaltyRequestSize)),this.throughput=Qt.getSmoothedValue(t,-1,e),this.rtt=Qt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let o=Aw();o&&this.throughput.next(o);let u=Rw();zu(u)&&this.rtt.next(u)},a=nh();a&&"onchange"in a&&this.subscription.add(Wu(a,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{sh.set(Pw,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{sh.set(kw,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(xw(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(dN({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(xw(({throughput:r,rtt:a})=>$w(r,a,e.rttPenaltyRequestSize)),pN(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=st(),r=new ww;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Wu(e,"progress").pipe(cN()).subscribe(a=>{t=a.loaded,i=st()}));break;case 1:case 0:r.add(Wu(e,"loadstart").subscribe(()=>{t=0,i=st()}));break}r.add(Wu(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=st(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=st(),n=0,o=st(),u=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:c})=>{if(p)!t&&this.addRawSpeed(r,st()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let d=st();if(d-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=st()}else n+=c.byteLength;o=st()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&st()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,st()-o,this.concurrentDownloads.size),n=0,o=st());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=sh.get(e);if(zu(t))return parseInt(t,10)??void 0}},Mw=ah;import{fillWithDefault as mN,VideoQuality as Qu}from"@vkontakte/videoplayer-shared";var Lw={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:Qu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Qu.Q_720P,trafficSavingLimit:Qu.Q_480P},stallsManager:{enabled:!1,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Qu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},Dw=s=>({...mN(s,Lw),configName:[...s.configName??[],...Lw.configName]});import{assertNonNullable as lh,combine as Jt,ErrorCategory as Gu,filter as me,filterChanged as Y,fromEvent as ch,isNonNullable as Nw,isNullable as PN,Logger as kN,map as G,mapTo as Fw,merge as wi,now as Yu,once as Te,Subject as z,Subscription as Uw,tap as dh,ValueSubject as M,isHigher as AN,isInvariantQuality as qw,flattenObject as xi,throttle as ph,getTraceSubscriptionMethod as jw,TracerFactory as RN,InternalsExposure as $N,getPlayerId as MN,devNull as Ku}from"@vkontakte/videoplayer-shared";import{merge as bN,map as gN,filter as Bw,isNonNullable as SN}from"@vkontakte/videoplayer-shared";var oh=({seekState:s,position$:e})=>bN(s.stateChangeEnded$.pipe(gN(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Bw(SN)),e.pipe(Bw(()=>s.getState().state==="none")));import{assertNonNullable as vN}from"@vkontakte/videoplayer-shared";var Cw=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return vN(e,`Wrong container or containerId {${s.container}}`),e};import{filter as yN,once as TN}from"@vkontakte/videoplayer-shared";var Vw=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(yN(r=>r.length>0),TN()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t?.getValue().find(i))&&e.startTransitionTo(s)};var _w=D(oi(),1);import{devNull as IN,getWindow as uh}from"@vkontakte/videoplayer-shared";var Ow=()=>{let s="mediaCapabilities"in uh().navigator?EN:wN,e=Lt(async()=>{let t=await Promise.all((0,_w.default)(xN).map(async([r,a])=>({codec:r,supported:await s(a)}))),i=[$.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return IN.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>lt(e)},EN=async s=>{if(!s)return Promise.resolve({supported:!1});let e={["channels"in s?"audio":"video"]:s};return await uh().navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},wN=s=>{if(!s)return Promise.resolve({supported:!1});let e=uh().document,t="channels"in s?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType(s?.contentType??"")==="probably"})},xN={H264:{contentType:'video/mp4; codecs="avc1.4D400C"',width:720,height:720,bitrate:2886,framerate:30},H265:{contentType:'video/mp4; codecs="hvc1.1.6.L123.B0"',width:720,height:720,bitrate:2886,framerate:30},VP8:{contentType:'video/webm; codecs="vp8"',width:720,height:720,bitrate:2886,framerate:30},VP9:{contentType:'video/webm; codecs="vp09.00.10.08"',width:720,height:720,bitrate:2886,framerate:30},AV1:{contentType:'video/mp4; codecs="av01.0.01M.08"',width:720,height:720,bitrate:2886,framerate:30},OPUS:{contentType:'audio/ogg; codecs="opus"',channels:"2",bitrate:128e3},AAC_LC:{contentType:'audio/mp4; codecs="mp4a.40.2"',channels:"2",bitrate:128e3},AC3:{contentType:'audio/mp4; codecs="ac-3"',channels:"6",bitrate:128e3},EAC3:{contentType:'audio/mp4; codecs="ec-3"',channels:"6",bitrate:128e3},AAC_HE_V1:{contentType:'audio/mp4; codecs="mp4a.40.5"',channels:"2",bitrate:128e3},AAC_HE_V2:{contentType:'audio/mp4; codecs="mp4a.40.29"',channels:"2",bitrate:128e3},AAC_xHE:{contentType:'audio/mp4; codecs="mp4a.40.42"',channels:"2",bitrate:128e3}};var Xu=class{constructor(e={configName:[]},t=RN.createRootTracer(!1),i){this.subscription=new Uw;this.logger=new kN;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new M(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new M(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new M(void 0),position$:new M(0),duration$:new M(1/0),muted$:new M(!1),volume$:new M(1),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableQualities$:new M([]),availableQualitiesFps$:new M({}),currentQuality$:new M(void 0),isAutoQualityEnabled$:new M(!0),autoQualityLimitingAvailable$:new M(!1),autoQualityLimits$:new M({}),predefinedQualityLimitType$:new M("unknown"),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),isAudioAvailable$:new M(!0),currentPlaybackRate$:new M(1),currentBuffer$:new M({start:0,end:0}),currentNativeBuffer$:new M({start:0,end:0}),isBuffering$:new M(!0),isStalled$:new M(!1),isEnded$:new M(!1),isLooped$:new M(!1),isLive$:new M(void 0),isLiveEnded$:new M(null),canPlayLiveTailBuffer$:new M(!1),canChangePlaybackSpeed$:new M(void 0),atLiveEdge$:new M(void 0),atLiveDurationEdge$:new M(void 0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),currentFormat$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),throughputEstimation$:new M(void 0),rttEstimation$:new M(void 0),videoBitrate$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),surface$:new M("none"),chromecastState$:new M("NOT_AVAILABLE"),chromecastDeviceName$:new M(void 0),intrinsicVideoSize$:new M(void 0),availableSources$:new M(void 0),is3DVideo$:new M(!1),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0)};this.events={inited$:new z,ready$:new z,started$:new z,playing$:new z,paused$:new z,stopped$:new z,willReady$:new z,willStart$:new z,willResume$:new z,willPause$:new z,willStop$:new z,willDestruct$:new z,watchCoverageRecord$:new z,watchCoverageLive$:new z,managedError$:new z,fatalError$:new z,fetcherRecoverableError$:new z,ended$:new z,looped$:new z,seeked$:new z,willSeek$:new z,autoplaySoundProhibited$:new z,manifestRequested$:new z,firstBytesManifest$:new z,manifestReceived$:new z,firstBytesRequested$:new z,firstBytesReceived$:new z,firstBytes$:new z,loadedMetadata$:new z,firstFrame$:new z,canplay$:new z,log$:new z,fetcherError$:new z,severeStallOccured$:new z};this.experimental={element$:new M(void 0),tuningConfigName$:new M([]),enableDebugTelemetry$:new M(!1),dumpTelemetry:oy,getCurrentTime$:new M(null)};this.initLogs(),this.tuning=Dw(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,hh.default)(this.info).forEach(a=>a.setSuppressErrors(!0)),(0,hh.default)(this.events).forEach(a=>a.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName);let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new Ot(r):new Kn(r),this.throughputEstimator=new Mw(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new $N("core",MN(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i?.onDevNullLog,Ku.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(a,n,o)=>{let u=Reflect.get(a,n,o);return typeof u!="function"?u:(...l)=>{try{return u.apply(a,l)}catch(p){let c=l.map(f=>JSON.stringify(f,(m,S)=>{let g=typeof S;return(0,Hw.default)(["number","string","boolean"],g)?S:S===null?null:`<${g}>`})),d=`Player.${String(n)}`,h=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Gu.WTF,message:h,thrown:p}),p}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:a,...n}=e;this.tracer.log("initVideo",xi(n)),this.domContainer=Cw(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ln({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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),this.devNullLog&&this.tuning.devNullLogEnabled?(Ku.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=Ow())):Ku.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?$.isInited$.pipe(me(a=>!!a),Te()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),ch(document,"visibilitychange").pipe(Te()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy(),Ku.destroy("core"),this.collectDecodingInfoDestroyCb?.()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(me(t=>!!t),Te()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{let i=this.desiredState.volume,a=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||a);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof Ot)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof Ot)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{lh(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(me(i=>i.length>0),Te()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",xi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",xi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Vw(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(PN(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Nw(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.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(wi(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(ly(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(me(({from:e})=>e==="stopped"),Te()).subscribe(()=>{this.initedAt=Yu(),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",xi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Gu.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Te()).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",xi(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),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Jt({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)=>qw(u)?1:qw(l)?-1:AN(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(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(me(n=>Nw(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).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??{})})).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.currentNativeBuffer$.pipe(G(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(dh(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.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(Jt({hasLiveOffsetByPaused:wi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),Y(),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(Jt({atLiveEdge:Jt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:oh({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}),Y(),dh(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Jt({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),Y(),dh(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),Y()).subscribe(this.info.volume$)).add(oh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(wi(e.providerOutput.endedEvent$.pipe(Fw(!0)),e.providerOutput.seekedEvent$.pipe(Fw(!1))).pipe(Y()).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:Gu.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(Te()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(Te()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(Te()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(Te()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(Te()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(Te(),G(n=>n??Yu()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Te(),G(()=>Yu()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Te(),G(()=>Yu()-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 M(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new M(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(me(({to:n})=>n==="playing"),Te()).subscribe(()=>i.next(!1)));let r=0,a=wi(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),Y());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(wi(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(wi(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(),p=this.chromecastInitializer.castState$.getValue(),c;p==="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(G(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Uw;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(me(i=>i.length>0),Te()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=ut(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(wi(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(){let e=this.providerContainer?.providerOutput;lh(this.providerContainer),lh(e),ny(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>ay(t)),this.providerContainer.current$.subscribe(({type:t})=>aa("provider",t)),e.duration$.subscribe(t=>aa("duration",t)),e.availableVideoTracks$.pipe(me(t=>!!t.length),Te()).subscribe(t=>aa("tracks",t)),this.events.fatalError$.subscribe(new Fe("fatalError")),this.events.managedError$.subscribe(new Fe("managedError")),e.position$.subscribe(new Fe("position")),e.currentVideoTrack$.pipe(G(t=>t?.quality)).subscribe(new Fe("quality")),this.info.currentBuffer$.subscribe(new Fe("buffer")),e.isBuffering$.subscribe(new Fe("isBuffering"))].forEach(t=>this.subscription.add(t)),aa("codecs",$.video.supportedCodecs)}initTracerSubscription(){let e=jw(this.tracer.log.bind(this.tracer)),t=jw(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(Y()).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(Jt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(me(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(me(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(me(i=>i>0),Y()).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(Jt({currentBuffer:this.info.currentBuffer$.pipe(me(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(ph(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(Jt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(me(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),ph(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),me(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),me(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),me(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Jt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(me(({throughputEstimation:i,rtt:r})=>!!i&&!!r),ph(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),me(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?.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:Gu.DOM,message:String(r)})})};this.subscription.add(wi(ch(document,"visibilitychange"),ch(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",xi({quality:t,availableTracks:xi(e),track:xi(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!ca()}};import{Subscription as nae,Observable as oae,Subject as uae,ValueSubject as lae,VideoQuality as cae}from"@vkontakte/videoplayer-shared";var dae=`@vkontakte/videoplayer-core@${bh}`;export{xs as ChromecastState,el as HttpConnectionType,oae as Observable,xe as PlaybackState,Xu as Player,Un as PredefinedQualityLimits,dae as SDK_VERSION,uae as Subject,nae as Subscription,tl as Surface,bh as VERSION,lae as ValueSubject,Vt as VideoFormat,cae as VideoQuality,TA as areValidLiveRecordSources,$ as clientChecker,Vi as isMobile};
184
+ ===== DASH_LIVE DEBUG END ====`),o){let u=a.reduce((l,{time:p,data:c,stack:d})=>{let h=(0,sh.default)(c).map(([f,m])=>`${f}:${m}`).join(",");return l+=`${p}: ${h}${d?`: ${d}`:""};`,l},"");oN.push("core",{key:"vp_dash_live_debug",strings:[u]})}};return e.add(this.providerError$.subscribe(a=>{a.id.startsWith("ProviderHangup")&&(_({m:"final.0",e:a.id}),r())})).add(this.noAvailableProvidersError$.subscribe(()=>{_({m:"final.1"}),r()})),e.add(this.providerError$.subscribe(a=>{let n=this.current$.getValue().destination,o={error:a,currentDestination:n};if(n==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("CHROMECAST"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=a.category===Hu.NETWORK,l=a.category===Hu.FATAL,p=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!l,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,h=p&&!l&&(u&&t||!c);o={...o,isNetworkError:u,isFatalError:l,haveFailoverHost:p,tryFailover:h,canReinitProvider:c},c?(i++,this.reinitProvider()):h?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(i=0,this.switchToNextProvider(n??"SCREEN"))}a.traceAsLog?this.tracer.log("providerInfo",ih(o)):this.tracer.error("providerError",ih(o))})),e}};import{fromEvent as zu,once as cN,combine as dN,Subscription as kw,ValueSubject as ah,map as Pw,filter as pN,isNonNullable as Wu,now as st,safeStorage as nh,getWindow as hN}from"@vkontakte/videoplayer-shared";var fN=5e3,Aw="one_video_throughput",Rw="one_video_rtt",uh=()=>{let{navigator:s}=hN();if(s)return s.connection},$w=()=>{let s=uh()?.downlink;if(Wu(s)&&s!==10)return s*1e3},Mw=()=>{let s=uh()?.rtt;if(Wu(s)&&s!==3e3)return s},Lw=(s,e,t)=>{let i=t*8,r=i/s;return i/(r+e)},oh=class s{constructor(e){this.subscription=new kw;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=s.load(Aw)||(e.useBrowserEstimation?$w():void 0)||fN,i=s.load(Rw)??(e.useBrowserEstimation?Mw():void 0)??0;if(this.throughput$=new ah(t),this.rtt$=new ah(i),this.rttAdjustedThroughput$=new ah(Lw(t,i,e.rttPenaltyRequestSize)),this.throughput=Qt.getSmoothedValue(t,-1,e),this.rtt=Qt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let o=$w();o&&this.throughput.next(o);let u=Mw();Wu(u)&&this.rtt.next(u)},a=uh();a&&"onchange"in a&&this.subscription.add(zu(a,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{nh.set(Aw,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{nh.set(Rw,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.pipe(Pw(r=>Math.round(r))).subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(dN({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Pw(({throughput:r,rtt:a})=>Lw(r,a,e.rttPenaltyRequestSize)),pN(r=>{let a=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-a)/a>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=st(),r=new kw;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(zu(e,"progress").pipe(cN()).subscribe(a=>{t=a.loaded,i=st()}));break;case 1:case 0:r.add(zu(e,"loadstart").subscribe(()=>{t=0,i=st()}));break}r.add(zu(e,"loadend").subscribe(a=>{if(e.status===200){let n=a.loaded,o=st(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=st(),n=0,o=st(),u=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:c})=>{if(p)!t&&this.addRawSpeed(r,st()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let d=st();if(d-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=st()}else n+=c.byteLength;o=st()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&st()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,st()-o,this.concurrentDownloads.size),n=0,o=st());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(s.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=nh.get(e);if(Wu(t))return parseInt(t,10)??void 0}},Dw=oh;import{fillWithDefault as mN,VideoQuality as Qu}from"@vkontakte/videoplayer-shared";var Bw={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:Qu.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Qu.Q_720P,trafficSavingLimit:Qu.Q_480P},stallsManager:{enabled:!1,ignoreDynamicAbrForShortVideo:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:20,maxPossibleStallDuration:3e4,minTvtToBeCounted:120,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Qu.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,maxVirtualBufferSize:250*1024*1024,virtualBufferPruneSize:100*1024*1024,representationSwitchForwardBufferGap:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,useAbortMSEFix:!1,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!0,stallWatchdogInterval:100,liveUpdateInterval:1e3,liveStallReinitInterval:3e3,ignoreNetworkErrorsOnLoadInit:!1,bufferTolerance:100,actionTimeShiftFromSegment:500},dashCmafLive:{externalStopControl:!1,keepSilentStallWatchdogWhenNotActive:!1,maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",chromecastPresentationApi:!1,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useDashProviderVirtual:!1,useDashProviderVirtualMobile:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0,devNullLogEnabled:!1,collectingDecodingInfoEnabled:!1,sendDashLiveDebug:!1,logDashLiveDebug:!1},Cw=s=>({...mN(s,Bw),configName:[...s.configName??[],...Bw.configName]});import{assertNonNullable as dh,combine as Jt,ErrorCategory as Gu,filter as me,filterChanged as Y,fromEvent as ph,isNonNullable as Uw,isNullable as kN,Logger as PN,map as G,mapTo as qw,merge as wi,now as Yu,once as Te,Subject as W,Subscription as jw,tap as hh,ValueSubject as M,isHigher as AN,isInvariantQuality as Hw,flattenObject as xi,throttle as fh,getTraceSubscriptionMethod as zw,TracerFactory as RN,InternalsExposure as $N,getPlayerId as MN,devNull as Ku}from"@vkontakte/videoplayer-shared";import{merge as bN,map as gN,filter as Vw,isNonNullable as SN}from"@vkontakte/videoplayer-shared";var lh=({seekState:s,position$:e})=>bN(s.stateChangeEnded$.pipe(gN(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Vw(SN)),e.pipe(Vw(()=>s.getState().state==="none")));import{assertNonNullable as vN}from"@vkontakte/videoplayer-shared";var _w=s=>{let e=typeof s.container=="string"?document.getElementById(s.container):s.container;return vN(e,`Wrong container or containerId {${s.container}}`),e};import{filter as yN,once as TN}from"@vkontakte/videoplayer-shared";var Ow=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(yN(r=>r.length>0),TN()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t?.getValue().find(i))&&e.startTransitionTo(s)};var Nw=D(oi(),1);import{devNull as IN,getWindow as ch}from"@vkontakte/videoplayer-shared";var Fw=()=>{let s="mediaCapabilities"in ch().navigator?EN:wN,e=Lt(async()=>{let t=await Promise.all((0,Nw.default)(xN).map(async([r,a])=>({codec:r,supported:await s(a)}))),i=[$.browser.current,...t.map(r=>JSON.stringify(r))].slice(0,16);return IN.push("core",{key:"videoplayer_decoding_info",strings:i}),t});return()=>lt(e)},EN=async s=>{if(!s)return Promise.resolve({supported:!1});let e={["channels"in s?"audio":"video"]:s};return await ch().navigator.mediaCapabilities.decodingInfo({type:"media-source",...e})},wN=s=>{if(!s)return Promise.resolve({supported:!1});let e=ch().document,t="channels"in s?e.createElement("audio"):e.createElement("video");return Promise.resolve({supported:t.canPlayType(s?.contentType??"")==="probably"})},xN={H264:{contentType:'video/mp4; codecs="avc1.4D400C"',width:720,height:720,bitrate:2886,framerate:30},H265:{contentType:'video/mp4; codecs="hvc1.1.6.L123.B0"',width:720,height:720,bitrate:2886,framerate:30},VP8:{contentType:'video/webm; codecs="vp8"',width:720,height:720,bitrate:2886,framerate:30},VP9:{contentType:'video/webm; codecs="vp09.00.10.08"',width:720,height:720,bitrate:2886,framerate:30},AV1:{contentType:'video/mp4; codecs="av01.0.01M.08"',width:720,height:720,bitrate:2886,framerate:30},OPUS:{contentType:'audio/ogg; codecs="opus"',channels:"2",bitrate:128e3},AAC_LC:{contentType:'audio/mp4; codecs="mp4a.40.2"',channels:"2",bitrate:128e3},AC3:{contentType:'audio/mp4; codecs="ac-3"',channels:"6",bitrate:128e3},EAC3:{contentType:'audio/mp4; codecs="ec-3"',channels:"6",bitrate:128e3},AAC_HE_V1:{contentType:'audio/mp4; codecs="mp4a.40.5"',channels:"2",bitrate:128e3},AAC_HE_V2:{contentType:'audio/mp4; codecs="mp4a.40.29"',channels:"2",bitrate:128e3},AAC_xHE:{contentType:'audio/mp4; codecs="mp4a.40.42"',channels:"2",bitrate:128e3}};var Xu=class{constructor(e={configName:[]},t=RN.createRootTracer(!1),i){this.subscription=new jw;this.logger=new PN;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new M(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new M(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new M(void 0),position$:new M(0),duration$:new M(1/0),muted$:new M(!1),volume$:new M(1),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableQualities$:new M([]),availableQualitiesFps$:new M({}),currentQuality$:new M(void 0),isAutoQualityEnabled$:new M(!0),autoQualityLimitingAvailable$:new M(!1),autoQualityLimits$:new M({}),predefinedQualityLimitType$:new M("unknown"),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),isAudioAvailable$:new M(!0),currentPlaybackRate$:new M(1),currentBuffer$:new M({start:0,end:0}),currentNativeBuffer$:new M({start:0,end:0}),isBuffering$:new M(!0),isStalled$:new M(!1),isEnded$:new M(!1),isLooped$:new M(!1),isLive$:new M(void 0),isLiveEnded$:new M(null),canPlayLiveTailBuffer$:new M(!1),canChangePlaybackSpeed$:new M(void 0),atLiveEdge$:new M(void 0),atLiveDurationEdge$:new M(void 0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),currentFormat$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),throughputEstimation$:new M(void 0),rttEstimation$:new M(void 0),videoBitrate$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),surface$:new M("none"),chromecastState$:new M("NOT_AVAILABLE"),chromecastDeviceName$:new M(void 0),intrinsicVideoSize$:new M(void 0),availableSources$:new M(void 0),is3DVideo$:new M(!1),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0)};this.events={inited$:new W,ready$:new W,started$:new W,playing$:new W,paused$:new W,stopped$:new W,willReady$:new W,willStart$:new W,willResume$:new W,willPause$:new W,willStop$:new W,willDestruct$:new W,watchCoverageRecord$:new W,watchCoverageLive$:new W,managedError$:new W,fatalError$:new W,fetcherRecoverableError$:new W,ended$:new W,looped$:new W,seeked$:new W,willSeek$:new W,autoplaySoundProhibited$:new W,manifestRequested$:new W,firstBytesManifest$:new W,manifestReceived$:new W,firstBytesRequested$:new W,firstBytesReceived$:new W,firstBytes$:new W,loadedMetadata$:new W,firstFrame$:new W,canplay$:new W,log$:new W,fetcherError$:new W,severeStallOccured$:new W};this.experimental={element$:new M(void 0),tuningConfigName$:new M([]),enableDebugTelemetry$:new M(!1),dumpTelemetry:ly,getCurrentTime$:new M(null)};this.initLogs(),this.tuning=Cw(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,mh.default)(this.info).forEach(a=>a.setSuppressErrors(!0)),(0,mh.default)(this.events).forEach(a=>a.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName);let r={receiverApplicationId:this.tuning.chromecastReceiverId,isDisabled:this.tuning.disableChromecast,dependencies:{logger:this.logger}};if(this.chromecastInitializer=this.tuning.chromecastPresentationApi?new Ot(r):new Kn(r),this.throughputEstimator=new Dw(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new $N("core",MN(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),this.devNullLog=i?.onDevNullLog,Ku.create("core"),Proxy&&Reflect)return new Proxy(this,{get:(a,n,o)=>{let u=Reflect.get(a,n,o);return typeof u!="function"?u:(...l)=>{try{return u.apply(a,l)}catch(p){let c=l.map(f=>JSON.stringify(f,(m,S)=>{let g=typeof S;return(0,Ww.default)(["number","string","boolean"],g)?S:S===null?null:`<${g}>`})),d=`Player.${String(n)}`,h=`Exception calling ${d} (${c.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Gu.WTF,message:h,thrown:p}),p}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:a,...n}=e;this.tracer.log("initVideo",xi(n)),this.domContainer=_w(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ln({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],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),this.devNullLog&&this.tuning.devNullLogEnabled?(Ku.subscribe("core",this.devNullLog),this.tuning.collectingDecodingInfoEnabled&&(this.collectDecodingInfoDestroyCb=Fw())):Ku.destroy("core")},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?$.isInited$.pipe(me(a=>!!a),Te()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),ph(document,"visibilitychange").pipe(Te()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy(),Ku.destroy("core"),this.collectDecodingInfoDestroyCb?.()}waitInit(e){this.playerInited.getValue()?e():this.subscription.add(this.playerInited.pipe(me(t=>!!t),Te()).subscribe(e))}prepare(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")}),this}play(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")}),this}pause(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")}),this}stop(){return this.waitInit(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")}),this}seekTime(e,t=!0){return this.waitInit(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),a=e;e>=i&&!r&&(a=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:a,forcePrecise:t}),Number.isFinite(a)&&(this.events.willSeek$.next({from:this.getExactTime(),to:a}),this.desiredState.seekState.setState({state:"requested",position:a*1e3,forcePrecise:t}))}),this}seekPercent(e){return this.waitInit(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)}),this}setVolume(e,t){return this.waitInit(()=>{let i=this.desiredState.volume,a=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||a);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof Ot)?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})}),this}setMuted(e,t=!1){return this.waitInit(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"&&!(this.chromecastInitializer instanceof Ot)?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})}),this}setVideoStream(e){return this.waitInit(()=>{this.desiredState.videoStream.startTransitionTo(e)}),this}setAudioStream(e){return this.waitInit(()=>{this.desiredState.audioStream.startTransitionTo(e)}),this}setQuality(e){return this.waitInit(()=>{dh(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(me(i=>i.length>0),Te()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)}),this}setAutoQuality(e){return this.waitInit(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)}),this}setAutoQualityLimits(e){return this.waitInit(()=>{this.tracer.log("setAutoQualityLimits",xi(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)}),this}setPredefinedQualityLimits(e){return this.waitInit(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)}),this}setPlaybackRate(e){return this.waitInit(()=>{this.tracer.log("setPlaybackRate",{playbackRate:e}),this.desiredState.playbackRate.startTransitionTo(e)}),this}setExternalTextTracks(e){return this.waitInit(()=>{e.length&&this.tracer.log("setExternalTextTracks",xi(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))}),this}selectTextTrack(e){return this.waitInit(()=>{Ow(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})}),this}setTextTrackCueSettings(e){return this.waitInit(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)}),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.waitInit(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)}),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.waitInit(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)}),this}stopCameraManualRotation(e=!1){return this.waitInit(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)}),this}moveCameraFocusPX(e,t){return this.waitInit(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}}),this}holdCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.holdCamera()}),this}releaseCamera(){return this.waitInit(()=>{let e=this.getScene3D();e&&e.releaseCamera()}),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(kN(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Uw(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.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(wi(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(dy(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(me(({from:e})=>e==="stopped"),Te()).subscribe(()=>{this.initedAt=Yu(),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",xi(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Gu.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Te()).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",xi(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),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Jt({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)=>Hw(u)?1:Hw(l)?-1:AN(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(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(me(n=>Uw(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).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??{})})).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.currentNativeBuffer$.pipe(G(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentNativeBuffer$)).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(hh(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(Jt({hasLiveOffsetByPaused:wi(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),Y(),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(Jt({atLiveEdge:Jt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:lh({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}),Y(),hh(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Jt({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),Y(),hh(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),Y()).subscribe(this.info.volume$)).add(lh({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.info.isEnded$.getValue()&&this.tuning.changePlaybackStateToPausedWhenEnded&&this.play()})).add(wi(e.providerOutput.endedEvent$.pipe(qw(!0)),e.providerOutput.seekedEvent$.pipe(qw(!1))).pipe(Y()).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:Gu.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.manifestRequested$.pipe(Te()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.firstBytesManifest$.pipe(Te()).subscribe(this.events.firstBytesManifest$)).add(e.providerOutput.manifestReceived$.pipe(Te()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe(Te()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe(Te()).subscribe(this.events.firstBytesReceived$)).add(e.providerOutput.firstBytesEvent$.pipe(Te(),G(n=>n??Yu()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Te(),G(()=>Yu()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Te(),G(()=>Yu()-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 M(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new M(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(me(({to:n})=>n==="playing"),Te()).subscribe(()=>i.next(!1)));let r=0,a=wi(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),Y());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(wi(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(wi(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(),p=this.chromecastInitializer.castState$.getValue(),c;p==="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(G(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new jw;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(me(i=>i.length>0),Te()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=ut(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(wi(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(){let e=this.providerContainer?.providerOutput;dh(this.providerContainer),dh(e),uy(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>oy(t)),this.providerContainer.current$.subscribe(({type:t})=>aa("provider",t)),e.duration$.subscribe(t=>aa("duration",t)),e.availableVideoTracks$.pipe(me(t=>!!t.length),Te()).subscribe(t=>aa("tracks",t)),this.events.fatalError$.subscribe(new Fe("fatalError")),this.events.managedError$.subscribe(new Fe("managedError")),e.position$.subscribe(new Fe("position")),e.currentVideoTrack$.pipe(G(t=>t?.quality)).subscribe(new Fe("quality")),this.info.currentBuffer$.subscribe(new Fe("buffer")),e.isBuffering$.subscribe(new Fe("isBuffering"))].forEach(t=>this.subscription.add(t)),aa("codecs",$.video.supportedCodecs)}initTracerSubscription(){let e=zw(this.tracer.log.bind(this.tracer)),t=zw(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(Y()).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(Jt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(me(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(me(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(me(i=>i>0),Y()).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(Jt({currentBuffer:this.info.currentBuffer$.pipe(me(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(fh(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(Jt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(me(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),fh(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),me(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),me(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),me(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Jt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(me(({throughputEstimation:i,rtt:r})=>!!i&&!!r),fh(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),me(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?.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:Gu.DOM,message:String(r)})})};this.subscription.add(wi(ph(document,"visibilitychange"),ph(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",xi({quality:t,availableTracks:xi(e),track:xi(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!ca()}};import{Subscription as nae,Observable as oae,Subject as uae,ValueSubject as lae,VideoQuality as cae}from"@vkontakte/videoplayer-shared";var dae=`@vkontakte/videoplayer-core@${Sh}`;export{xs as ChromecastState,el as HttpConnectionType,oae as Observable,xe as PlaybackState,Xu as Player,Un as PredefinedQualityLimits,dae as SDK_VERSION,uae as Subject,nae as Subscription,tl as Surface,Sh as VERSION,lae as ValueSubject,Vt as VideoFormat,cae as VideoQuality,TA as areValidLiveRecordSources,$ as clientChecker,Vi as isMobile};