@vkontakte/videoplayer-core 2.0.150-dev.31e6196f.0 → 2.0.150-dev.c564bb3a.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs +15 -15
- package/es2015.esm.js +20 -20
- package/es2018.cjs +11 -11
- package/es2018.esm.js +18 -18
- package/es2024.cjs +4 -4
- package/es2024.esm.js +6 -6
- package/esnext.cjs +4 -4
- package/esnext.esm.js +6 -6
- package/evergreen.esm.js +3 -3
- package/package.json +2 -2
package/es2024.esm.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.150-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.150-dev.c564bb3a.0
|
|
3
|
+
* Wed, 14 Jan 2026 08:56:21 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-150/doc/
|
|
5
5
|
*/
|
|
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/es2024";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/es2024";import{assertNever as sA,assertNonNullable as Ci,ErrorCategory as aA,getHighestQuality as nA,isNonNullable as qm}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as Um}from"@vkontakte/videoplayer-shared/es2024";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/es2024";import{isBrowserWindow as vA,ValueSubject as yA}from"@vkontakte/videoplayer-shared/es2024";var Hm=D(Pe(),1);import{getWindow as lA}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";import{clearVideoElement as PD}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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/es2024";import{isNonNullable as ld,isNullable as LD,Subscription as DD}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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:`
|
|
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((G2,Zy)=>{"use strict";var sC=Ri();Zy.exports=Array.isArray||function(e){return sC(e)==="Array"}});var tT=b((Y2,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((K2,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((X2,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((J2,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((rQ,hT)=>{"use strict";dT();pT();var EC=si();hT.exports=EC("Array","flatMap")});var bT=b((sQ,mT)=>{"use strict";var wC=fT();mT.exports=wC});var Gi=b((aQ,gT)=>{"use strict";var xC=bT();gT.exports=xC});var ma=b((IQ,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((EQ,IT)=>{"use strict";IT.exports=`
|
|
7
|
+
\v\f\r \u2028\u2029\uFEFF`});var xT=b((wQ,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((xQ,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((kQ,$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((MQ,CT)=>{"use strict";BT();var FC=si();CT.exports=FC("String","trimLeft")});var OT=b((LQ,_T)=>{"use strict";var UC=VT();_T.exports=UC});var FT=b((DQ,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.c564bb3a.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/es2024";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/es2024";import{assertNever as sA,assertNonNullable as Ci,ErrorCategory as aA,getHighestQuality as nA,isNonNullable as qm}from"@vkontakte/videoplayer-shared/es2024";import{assertNever as Um}from"@vkontakte/videoplayer-shared/es2024";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/es2024";import{isBrowserWindow as vA,ValueSubject as yA}from"@vkontakte/videoplayer-shared/es2024";var Hm=D(Pe(),1);import{getWindow as lA}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";import{clearVideoElement as PD}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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/es2024";import{isNonNullable as ld,isNullable as LD,Subscription as DD}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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
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]
|
|
@@ -168,14 +168,14 @@ 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(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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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>${`
|
|
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/es2024";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/es2024";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/es2024";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:nQ,NativeAbortController:oQ}=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,vQ=fa?yT.Request:le.Request,j=fa?Yi:le.AbortController,yQ=fa?Hr:le.AbortSignal;var dE=D(Pe(),1);var UT=D(FT(),1);import{ErrorCategory as ba}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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/es2024";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/es2024";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 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/es2024";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/es2024";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/es2024";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/es2024";import{assertNever as d0}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";import{assertNever as M0,ErrorCategory as sE,Subject as aE}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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&<&<(this.gapDetectionIdleCallback),this.initLoadIdleCallback&<&<(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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";var Rp=D(Ge(),1);import{videoSizeToQuality as $_,throttleFn as M_}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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&<&<(this.gapDetectionIdleCallback),this.initLoadIdleCallback&<&<(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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";var Yp=D(vc(),1);import{videoSizeToQuality as lO,getExponentialDelay as cO}from"@vkontakte/videoplayer-shared/es2024";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(`
|
|
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/es2024";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/es2024";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/es2024";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/es2024";import{assertNever as d0}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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_18l2bgfm3anm4)for(let t of this.idleCallbacks.values())e.__polyfill_cancelIdleCallback_18l2bgfm3anm4(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/es2024";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/es2024";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/es2024";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/es2024";import{assertNever as M0,ErrorCategory as sE,Subject as aE}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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&<&<(this.gapDetectionIdleCallback),this.initLoadIdleCallback&<&<(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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";var Rp=D(Ge(),1);import{videoSizeToQuality as $_,throttleFn as M_}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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&<&<(this.gapDetectionIdleCallback),this.initLoadIdleCallback&<&<(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/es2024";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/es2024";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/es2024";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/es2024";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/es2024";var Yp=D(vc(),1);import{videoSizeToQuality as lO,getExponentialDelay as cO}from"@vkontakte/videoplayer-shared/es2024";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
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/es2024";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
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/es2024";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/es2024";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/es2024";import{ErrorCategory as jO}from"@vkontakte/videoplayer-shared/es2024";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/es2024";import{Observable as XO,map as gw,Subscription as JO,Subject as ZO}from"@vkontakte/videoplayer-shared/es2024";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/es2024";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?`
|