@vkontakte/videoplayer-core 2.0.136-dev.b3347749.0 → 2.0.136-dev.b7a1035a.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.js +36 -36
- package/es2015.esm.js +36 -36
- package/es2018.cjs.js +44 -44
- package/es2018.esm.js +44 -44
- package/es2024.cjs.js +43 -43
- package/es2024.esm.js +45 -45
- package/esnext.cjs.js +43 -43
- package/esnext.esm.js +45 -45
- package/evergreen.esm.js +44 -44
- package/package.json +2 -2
- package/types/index.d.ts +1 -0
- package/types/player/Player.d.ts +1 -0
- package/types/player/types.d.ts +4 -0
- package/types/providers/DashProvider/lib/buffer.d.ts +1 -0
- package/types/providers/DashProvider/lib/fetcher.d.ts +1 -0
- package/types/providers/DashProvider/lib/player.d.ts +4 -0
- package/types/providers/DashProviderNew/lib/buffer.d.ts +1 -0
- package/types/providers/DashProviderNew/lib/fetcher.d.ts +1 -0
- package/types/providers/DashProviderNew/lib/player.d.ts +4 -0
- package/types/providers/ProviderContainer/utils/formatsSupport.d.ts +0 -2
- package/types/providers/types.d.ts +1 -0
- package/types/providers/utils/parsers/mpeg/BoxModel.d.ts +4 -4
- package/types/providers/utils/parsers/mpeg/box.d.ts +7 -7
- package/types/providers/utils/parsers/mpeg/boxes/index.d.ts +25 -25
- package/types/providers/utils/parsers/mpeg/boxes/uuid.d.ts +13 -6
- package/types/utils/tuningConfig.d.ts +2 -0
- package/types/utils/videoFormat.d.ts +6 -1
package/esnext.cjs.js
CHANGED
|
@@ -1,91 +1,91 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.136-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.136-dev.b7a1035a.0
|
|
3
|
+
* Mon, 28 Jul 2025 10:52:47 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-136/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var vv=Object.create;var us=Object.defineProperty;var yv=Object.getOwnPropertyDescriptor;var Tv=Object.getOwnPropertyNames;var Iv=Object.getPrototypeOf,Ev=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),xv=(a,e)=>{for(var t in e)us(a,t,{get:e[t],enumerable:!0})},Gl=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Tv(e))!Ev.call(a,r)&&r!==t&&us(a,r,{get:()=>e[r],enumerable:!(i=yv(e,r))||i.enumerable});return a};var K=(a,e,t)=>(t=a!=null?vv(Iv(a)):{},Gl(e||!a||!a.__esModule?us(t,"default",{value:a,enumerable:!0}):t,a)),wv=a=>Gl(us({},"__esModule",{value:!0}),a);var Se=b((Xn,Wl)=>{"use strict";var Ar=function(a){return a&&a.Math===Math&&a};Wl.exports=Ar(typeof globalThis=="object"&&globalThis)||Ar(typeof window=="object"&&window)||Ar(typeof self=="object"&&self)||Ar(typeof global=="object"&&global)||Ar(typeof Xn=="object"&&Xn)||function(){return this}()||Function("return this")()});var we=b((hL,zl)=>{"use strict";zl.exports=function(a){try{return!!a()}catch{return!0}}});var kr=b((fL,Yl)=>{"use strict";var Av=we();Yl.exports=!Av(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Jn=b((mL,Zl)=>{"use strict";var kv=kr(),Jl=Function.prototype,Kl=Jl.apply,Xl=Jl.call;Zl.exports=typeof Reflect=="object"&&Reflect.apply||(kv?Xl.bind(Kl):function(){return Xl.apply(Kl,arguments)})});var Ae=b((bL,ic)=>{"use strict";var ec=kr(),tc=Function.prototype,Zn=tc.call,Pv=ec&&tc.bind.bind(Zn,Zn);ic.exports=ec?Pv:function(a){return function(){return Zn.apply(a,arguments)}}});var pi=b((gL,ac)=>{"use strict";var rc=Ae(),Rv=rc({}.toString),Lv=rc("".slice);ac.exports=function(a){return Lv(Rv(a),8,-1)}});var eo=b((SL,sc)=>{"use strict";var $v=pi(),Mv=Ae();sc.exports=function(a){if($v(a)==="Function")return Mv(a)}});var ve=b((vL,nc)=>{"use strict";var to=typeof document=="object"&&document.all;nc.exports=typeof to>"u"&&to!==void 0?function(a){return typeof a=="function"||a===to}:function(a){return typeof a=="function"}});var Ye=b((yL,oc)=>{"use strict";var Dv=we();oc.exports=!Dv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ke=b((TL,uc)=>{"use strict";var Cv=kr(),ds=Function.prototype.call;uc.exports=Cv?ds.bind(ds):function(){return ds.apply(ds,arguments)}});var io=b(dc=>{"use strict";var lc={}.propertyIsEnumerable,cc=Object.getOwnPropertyDescriptor,Bv=cc&&!lc.call({1:2},1);dc.f=Bv?function(e){var t=cc(this,e);return!!t&&t.enumerable}:lc});var Pr=b((EL,pc)=>{"use strict";pc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var fc=b((xL,hc)=>{"use strict";var Vv=Ae(),_v=we(),Ov=pi(),ro=Object,Fv=Vv("".split);hc.exports=_v(function(){return!ro("z").propertyIsEnumerable(0)})?function(a){return Ov(a)==="String"?Fv(a,""):ro(a)}:ro});var Rr=b((wL,mc)=>{"use strict";mc.exports=function(a){return a==null}});var Xt=b((AL,bc)=>{"use strict";var Nv=Rr(),Uv=TypeError;bc.exports=function(a){if(Nv(a))throw new Uv("Can't call method on "+a);return a}});var hi=b((kL,gc)=>{"use strict";var qv=fc(),Hv=Xt();gc.exports=function(a){return qv(Hv(a))}});var Ne=b((PL,Sc)=>{"use strict";var jv=ve();Sc.exports=function(a){return typeof a=="object"?a!==null:jv(a)}});var fi=b((RL,vc)=>{"use strict";vc.exports={}});var Vt=b((LL,Tc)=>{"use strict";var ao=fi(),so=Se(),Qv=ve(),yc=function(a){return Qv(a)?a:void 0};Tc.exports=function(a,e){return arguments.length<2?yc(ao[a])||yc(so[a]):ao[a]&&ao[a][e]||so[a]&&so[a][e]}});var Lr=b(($L,Ic)=>{"use strict";var Gv=Ae();Ic.exports=Gv({}.isPrototypeOf)});var mi=b((ML,wc)=>{"use strict";var Wv=Se(),Ec=Wv.navigator,xc=Ec&&Ec.userAgent;wc.exports=xc?String(xc):""});var oo=b((DL,$c)=>{"use strict";var Lc=Se(),no=mi(),Ac=Lc.process,kc=Lc.Deno,Pc=Ac&&Ac.versions||kc&&kc.version,Rc=Pc&&Pc.v8,ht,ps;Rc&&(ht=Rc.split("."),ps=ht[0]>0&&ht[0]<4?1:+(ht[0]+ht[1]));!ps&&no&&(ht=no.match(/Edge\/(\d+)/),(!ht||ht[1]>=74)&&(ht=no.match(/Chrome\/(\d+)/),ht&&(ps=+ht[1])));$c.exports=ps});var uo=b((CL,Dc)=>{"use strict";var Mc=oo(),zv=we(),Yv=Se(),Kv=Yv.String;Dc.exports=!!Object.getOwnPropertySymbols&&!zv(function(){var a=Symbol("symbol detection");return!Kv(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Mc&&Mc<41})});var lo=b((BL,Cc)=>{"use strict";var Xv=uo();Cc.exports=Xv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var co=b((VL,Bc)=>{"use strict";var Jv=Vt(),Zv=ve(),ey=Lr(),ty=lo(),iy=Object;Bc.exports=ty?function(a){return typeof a=="symbol"}:function(a){var e=Jv("Symbol");return Zv(e)&&ey(e.prototype,iy(a))}});var $r=b((_L,Vc)=>{"use strict";var ry=String;Vc.exports=function(a){try{return ry(a)}catch{return"Object"}}});var xt=b((OL,_c)=>{"use strict";var ay=ve(),sy=$r(),ny=TypeError;_c.exports=function(a){if(ay(a))return a;throw new ny(sy(a)+" is not a function")}});var Mr=b((FL,Oc)=>{"use strict";var oy=xt(),uy=Rr();Oc.exports=function(a,e){var t=a[e];return uy(t)?void 0:oy(t)}});var Nc=b((NL,Fc)=>{"use strict";var po=Ke(),ho=ve(),fo=Ne(),ly=TypeError;Fc.exports=function(a,e){var t,i;if(e==="string"&&ho(t=a.toString)&&!fo(i=po(t,a))||ho(t=a.valueOf)&&!fo(i=po(t,a))||e!=="string"&&ho(t=a.toString)&&!fo(i=po(t,a)))return i;throw new ly("Can't convert object to primitive value")}});var ft=b((UL,Uc)=>{"use strict";Uc.exports=!0});var jc=b((qL,Hc)=>{"use strict";var qc=Se(),cy=Object.defineProperty;Hc.exports=function(a,e){try{cy(qc,a,{value:e,configurable:!0,writable:!0})}catch{qc[a]=e}return e}});var Dr=b((HL,Wc)=>{"use strict";var dy=ft(),py=Se(),hy=jc(),Qc="__core-js_shared__",Gc=Wc.exports=py[Qc]||hy(Qc,{});(Gc.versions||(Gc.versions=[])).push({version:"3.43.0",mode:dy?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var mo=b((jL,Yc)=>{"use strict";var zc=Dr();Yc.exports=function(a,e){return zc[a]||(zc[a]=e||{})}});var _i=b((QL,Kc)=>{"use strict";var fy=Xt(),my=Object;Kc.exports=function(a){return my(fy(a))}});var mt=b((GL,Xc)=>{"use strict";var by=Ae(),gy=_i(),Sy=by({}.hasOwnProperty);Xc.exports=Object.hasOwn||function(e,t){return Sy(gy(e),t)}});var bo=b((WL,Jc)=>{"use strict";var vy=Ae(),yy=0,Ty=Math.random(),Iy=vy(1.1.toString);Jc.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Iy(++yy+Ty,36)}});var $e=b((zL,ed)=>{"use strict";var Ey=Se(),xy=mo(),Zc=mt(),wy=bo(),Ay=uo(),ky=lo(),Oi=Ey.Symbol,go=xy("wks"),Py=ky?Oi.for||Oi:Oi&&Oi.withoutSetter||wy;ed.exports=function(a){return Zc(go,a)||(go[a]=Ay&&Zc(Oi,a)?Oi[a]:Py("Symbol."+a)),go[a]}});var ad=b((YL,rd)=>{"use strict";var Ry=Ke(),td=Ne(),id=co(),Ly=Mr(),$y=Nc(),My=$e(),Dy=TypeError,Cy=My("toPrimitive");rd.exports=function(a,e){if(!td(a)||id(a))return a;var t=Ly(a,Cy),i;if(t){if(e===void 0&&(e="default"),i=Ry(t,a,e),!td(i)||id(i))return i;throw new Dy("Can't convert object to primitive value")}return e===void 0&&(e="number"),$y(a,e)}});var So=b((KL,sd)=>{"use strict";var By=ad(),Vy=co();sd.exports=function(a){var e=By(a,"string");return Vy(e)?e:e+""}});var hs=b((XL,od)=>{"use strict";var _y=Se(),nd=Ne(),vo=_y.document,Oy=nd(vo)&&nd(vo.createElement);od.exports=function(a){return Oy?vo.createElement(a):{}}});var yo=b((JL,ud)=>{"use strict";var Fy=Ye(),Ny=we(),Uy=hs();ud.exports=!Fy&&!Ny(function(){return Object.defineProperty(Uy("div"),"a",{get:function(){return 7}}).a!==7})});var dd=b(cd=>{"use strict";var qy=Ye(),Hy=Ke(),jy=io(),Qy=Pr(),Gy=hi(),Wy=So(),zy=mt(),Yy=yo(),ld=Object.getOwnPropertyDescriptor;cd.f=qy?ld:function(e,t){if(e=Gy(e),t=Wy(t),Yy)try{return ld(e,t)}catch{}if(zy(e,t))return Qy(!Hy(jy.f,e,t),e[t])}});var To=b((e$,pd)=>{"use strict";var Ky=we(),Xy=ve(),Jy=/#|\.prototype\./,Cr=function(a,e){var t=eT[Zy(a)];return t===iT?!0:t===tT?!1:Xy(e)?Ky(e):!!e},Zy=Cr.normalize=function(a){return String(a).replace(Jy,".").toLowerCase()},eT=Cr.data={},tT=Cr.NATIVE="N",iT=Cr.POLYFILL="P";pd.exports=Cr});var Fi=b((t$,fd)=>{"use strict";var hd=eo(),rT=xt(),aT=kr(),sT=hd(hd.bind);fd.exports=function(a,e){return rT(a),e===void 0?a:aT?sT(a,e):function(){return a.apply(e,arguments)}}});var Io=b((i$,md)=>{"use strict";var nT=Ye(),oT=we();md.exports=nT&&oT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var wt=b((r$,bd)=>{"use strict";var uT=Ne(),lT=String,cT=TypeError;bd.exports=function(a){if(uT(a))return a;throw new cT(lT(a)+" is not an object")}});var bi=b(Sd=>{"use strict";var dT=Ye(),pT=yo(),hT=Io(),fs=wt(),gd=So(),fT=TypeError,Eo=Object.defineProperty,mT=Object.getOwnPropertyDescriptor,xo="enumerable",wo="configurable",Ao="writable";Sd.f=dT?hT?function(e,t,i){if(fs(e),t=gd(t),fs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Ao in i&&!i[Ao]){var r=mT(e,t);r&&r[Ao]&&(e[t]=i.value,i={configurable:wo in i?i[wo]:r[wo],enumerable:xo in i?i[xo]:r[xo],writable:!1})}return Eo(e,t,i)}:Eo:function(e,t,i){if(fs(e),t=gd(t),fs(i),pT)try{return Eo(e,t,i)}catch{}if("get"in i||"set"in i)throw new fT("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ni=b((s$,vd)=>{"use strict";var bT=Ye(),gT=bi(),ST=Pr();vd.exports=bT?function(a,e,t){return gT.f(a,e,ST(1,t))}:function(a,e,t){return a[e]=t,a}});var Te=b((n$,Td)=>{"use strict";var Br=Se(),vT=Jn(),yT=eo(),TT=ve(),IT=dd().f,ET=To(),Ui=fi(),xT=Fi(),qi=Ni(),yd=mt();Dr();var wT=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return vT(a,this,arguments)};return e.prototype=a.prototype,e};Td.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Br:r?Br[t]:Br[t]&&Br[t].prototype,o=i?Ui:Ui[t]||qi(Ui,t,{})[t],u=o.prototype,l,c,d,p,h,m,g,y,T;for(p in e)l=ET(i?p:t+(r?".":"#")+p,a.forced),c=!l&&n&&yd(n,p),m=o[p],c&&(a.dontCallGetSet?(T=IT(n,p),g=T&&T.value):g=n[p]),h=c&&g?g:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?y=xT(h,Br):a.wrap&&c?y=wT(h):s&&TT(h)?y=yT(h):y=h,(a.sham||h&&h.sham||m&&m.sham)&&qi(y,"sham",!0),qi(o,p,y),s&&(d=t+"Prototype",yd(Ui,d)||qi(Ui,d,{}),qi(Ui[d],p,h),a.real&&u&&(l||!u[p])&&qi(u,p,h)))}});var Ed=b((o$,Id)=>{"use strict";var AT=Math.ceil,kT=Math.floor;Id.exports=Math.trunc||function(e){var t=+e;return(t>0?kT:AT)(t)}});var Vr=b((u$,xd)=>{"use strict";var PT=Ed();xd.exports=function(a){var e=+a;return e!==e||e===0?0:PT(e)}});var Ad=b((l$,wd)=>{"use strict";var RT=Vr(),LT=Math.max,$T=Math.min;wd.exports=function(a,e){var t=RT(a);return t<0?LT(t+e,0):$T(t,e)}});var ko=b((c$,kd)=>{"use strict";var MT=Vr(),DT=Math.min;kd.exports=function(a){var e=MT(a);return e>0?DT(e,9007199254740991):0}});var Hi=b((d$,Pd)=>{"use strict";var CT=ko();Pd.exports=function(a){return CT(a.length)}});var Po=b((p$,Ld)=>{"use strict";var BT=hi(),VT=Ad(),_T=Hi(),Rd=function(a){return function(e,t,i){var r=BT(e),s=_T(r);if(s===0)return!a&&-1;var n=VT(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Ld.exports={includes:Rd(!0),indexOf:Rd(!1)}});var _r=b((h$,$d)=>{"use strict";$d.exports=function(){}});var Md=b(()=>{"use strict";var OT=Te(),FT=Po().includes,NT=we(),UT=_r(),qT=NT(function(){return!Array(1).includes()});OT({target:"Array",proto:!0,forced:qT},{includes:function(e){return FT(this,e,arguments.length>1?arguments[1]:void 0)}});UT("includes")});var Jt=b((b$,Dd)=>{"use strict";var HT=Vt();Dd.exports=HT});var Bd=b((g$,Cd)=>{"use strict";Md();var jT=Jt();Cd.exports=jT("Array","includes")});var _d=b((S$,Vd)=>{"use strict";var QT=Bd();Vd.exports=QT});var st=b((v$,Od)=>{"use strict";var GT=_d();Od.exports=GT});var bs=b((L$,Ud)=>{"use strict";var zT=mo(),YT=bo(),Nd=zT("keys");Ud.exports=function(a){return Nd[a]||(Nd[a]=YT(a))}});var Hd=b(($$,qd)=>{"use strict";var KT=we();qd.exports=!KT(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var gs=b((M$,Qd)=>{"use strict";var XT=mt(),JT=ve(),ZT=_i(),eI=bs(),tI=Hd(),jd=eI("IE_PROTO"),Ro=Object,iI=Ro.prototype;Qd.exports=tI?Ro.getPrototypeOf:function(a){var e=ZT(a);if(XT(e,jd))return e[jd];var t=e.constructor;return JT(t)&&e instanceof t?t.prototype:e instanceof Ro?iI:null}});var Ss=b((D$,Gd)=>{"use strict";Gd.exports={}});var Yd=b((C$,zd)=>{"use strict";var rI=Ae(),Lo=mt(),aI=hi(),sI=Po().indexOf,nI=Ss(),Wd=rI([].push);zd.exports=function(a,e){var t=aI(a),i=0,r=[],s;for(s in t)!Lo(nI,s)&&Lo(t,s)&&Wd(r,s);for(;e.length>i;)Lo(t,s=e[i++])&&(~sI(r,s)||Wd(r,s));return r}});var $o=b((B$,Kd)=>{"use strict";Kd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Mo=b((V$,Xd)=>{"use strict";var oI=Yd(),uI=$o();Xd.exports=Object.keys||function(e){return oI(e,uI)}});var Do=b((_$,ip)=>{"use strict";var Zd=Ye(),lI=we(),ep=Ae(),cI=gs(),dI=Mo(),pI=hi(),hI=io().f,tp=ep(hI),fI=ep([].push),mI=Zd&&lI(function(){var a=Object.create(null);return a[2]=2,!tp(a,2)}),Jd=function(a){return function(e){for(var t=pI(e),i=dI(t),r=mI&&cI(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Zd||(r?u in t:tp(t,u)))&&fI(o,a?[u,t[u]]:t[u]);return o}};ip.exports={entries:Jd(!0),values:Jd(!1)}});var rp=b(()=>{"use strict";var bI=Te(),gI=Do().entries;bI({target:"Object",stat:!0},{entries:function(e){return gI(e)}})});var sp=b((N$,ap)=>{"use strict";rp();var SI=fi();ap.exports=SI.Object.entries});var op=b((U$,np)=>{"use strict";var vI=sp();np.exports=vI});var ji=b((q$,up)=>{"use strict";var yI=op();up.exports=yI});var gi=b((H$,lp)=>{"use strict";lp.exports={}});var pp=b((j$,dp)=>{"use strict";var TI=Se(),II=ve(),cp=TI.WeakMap;dp.exports=II(cp)&&/native code/.test(String(cp))});var _o=b((Q$,mp)=>{"use strict";var EI=pp(),fp=Se(),xI=Ne(),wI=Ni(),Co=mt(),Bo=Dr(),AI=bs(),kI=Ss(),hp="Object already initialized",Vo=fp.TypeError,PI=fp.WeakMap,vs,Or,ys,RI=function(a){return ys(a)?Or(a):vs(a,{})},LI=function(a){return function(e){var t;if(!xI(e)||(t=Or(e)).type!==a)throw new Vo("Incompatible receiver, "+a+" required");return t}};EI||Bo.state?(bt=Bo.state||(Bo.state=new PI),bt.get=bt.get,bt.has=bt.has,bt.set=bt.set,vs=function(a,e){if(bt.has(a))throw new Vo(hp);return e.facade=a,bt.set(a,e),e},Or=function(a){return bt.get(a)||{}},ys=function(a){return bt.has(a)}):(Si=AI("state"),kI[Si]=!0,vs=function(a,e){if(Co(a,Si))throw new Vo(hp);return e.facade=a,wI(a,Si,e),e},Or=function(a){return Co(a,Si)?a[Si]:{}},ys=function(a){return Co(a,Si)});var bt,Si;mp.exports={set:vs,get:Or,has:ys,enforce:RI,getterFor:LI}});var No=b((G$,gp)=>{"use strict";var Oo=Ye(),$I=mt(),bp=Function.prototype,MI=Oo&&Object.getOwnPropertyDescriptor,Fo=$I(bp,"name"),DI=Fo&&function(){}.name==="something",CI=Fo&&(!Oo||Oo&&MI(bp,"name").configurable);gp.exports={EXISTS:Fo,PROPER:DI,CONFIGURABLE:CI}});var vp=b(Sp=>{"use strict";var BI=Ye(),VI=Io(),_I=bi(),OI=wt(),FI=hi(),NI=Mo();Sp.f=BI&&!VI?Object.defineProperties:function(e,t){OI(e);for(var i=FI(t),r=NI(t),s=r.length,n=0,o;s>n;)_I.f(e,o=r[n++],i[o]);return e}});var Uo=b((z$,yp)=>{"use strict";var UI=Vt();yp.exports=UI("document","documentElement")});var Qo=b((Y$,kp)=>{"use strict";var qI=wt(),HI=vp(),Tp=$o(),jI=Ss(),QI=Uo(),GI=hs(),WI=bs(),Ip=">",Ep="<",Ho="prototype",jo="script",wp=WI("IE_PROTO"),qo=function(){},Ap=function(a){return Ep+jo+Ip+a+Ep+"/"+jo+Ip},xp=function(a){a.write(Ap("")),a.close();var e=a.parentWindow.Object;return a=null,e},zI=function(){var a=GI("iframe"),e="java"+jo+":",t;return a.style.display="none",QI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Ap("document.F=Object")),t.close(),t.F},Ts,Is=function(){try{Ts=new ActiveXObject("htmlfile")}catch{}Is=typeof document<"u"?document.domain&&Ts?xp(Ts):zI():xp(Ts);for(var a=Tp.length;a--;)delete Is[Ho][Tp[a]];return Is()};jI[wp]=!0;kp.exports=Object.create||function(e,t){var i;return e!==null?(qo[Ho]=qI(e),i=new qo,qo[Ho]=null,i[wp]=e):i=Is(),t===void 0?i:HI.f(i,t)}});var Qi=b((K$,Pp)=>{"use strict";var YI=Ni();Pp.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:YI(a,e,t),a}});var Yo=b((X$,$p)=>{"use strict";var KI=we(),XI=ve(),JI=Ne(),ZI=Qo(),Rp=gs(),eE=Qi(),tE=$e(),iE=ft(),zo=tE("iterator"),Lp=!1,_t,Go,Wo;[].keys&&(Wo=[].keys(),"next"in Wo?(Go=Rp(Rp(Wo)),Go!==Object.prototype&&(_t=Go)):Lp=!0);var rE=!JI(_t)||KI(function(){var a={};return _t[zo].call(a)!==a});rE?_t={}:iE&&(_t=ZI(_t));XI(_t[zo])||eE(_t,zo,function(){return this});$p.exports={IteratorPrototype:_t,BUGGY_SAFARI_ITERATORS:Lp}});var Es=b((J$,Dp)=>{"use strict";var aE=$e(),sE=aE("toStringTag"),Mp={};Mp[sE]="z";Dp.exports=String(Mp)==="[object z]"});var Fr=b((Z$,Cp)=>{"use strict";var nE=Es(),oE=ve(),xs=pi(),uE=$e(),lE=uE("toStringTag"),cE=Object,dE=xs(function(){return arguments}())==="Arguments",pE=function(a,e){try{return a[e]}catch{}};Cp.exports=nE?xs:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=pE(e=cE(a),lE))=="string"?t:dE?xs(e):(i=xs(e))==="Object"&&oE(e.callee)?"Arguments":i}});var Vp=b((eM,Bp)=>{"use strict";var hE=Es(),fE=Fr();Bp.exports=hE?{}.toString:function(){return"[object "+fE(this)+"]"}});var Nr=b((tM,Op)=>{"use strict";var mE=Es(),bE=bi().f,gE=Ni(),SE=mt(),vE=Vp(),yE=$e(),_p=yE("toStringTag");Op.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(SE(r,_p)||bE(r,_p,{configurable:!0,value:e}),i&&!mE&&gE(r,"toString",vE))}});var Np=b((iM,Fp)=>{"use strict";var TE=Yo().IteratorPrototype,IE=Qo(),EE=Pr(),xE=Nr(),wE=gi(),AE=function(){return this};Fp.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=IE(TE,{next:EE(+!i,t)}),xE(a,r,!1,!0),wE[r]=AE,a}});var qp=b((rM,Up)=>{"use strict";var kE=Ae(),PE=xt();Up.exports=function(a,e,t){try{return kE(PE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var jp=b((aM,Hp)=>{"use strict";var RE=Ne();Hp.exports=function(a){return RE(a)||a===null}});var Gp=b((sM,Qp)=>{"use strict";var LE=jp(),$E=String,ME=TypeError;Qp.exports=function(a){if(LE(a))return a;throw new ME("Can't set "+$E(a)+" as a prototype")}});var Ko=b((nM,Wp)=>{"use strict";var DE=qp(),CE=Ne(),BE=Xt(),VE=Gp();Wp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=DE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return BE(r),VE(s),CE(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var ah=b((oM,rh)=>{"use strict";var _E=Te(),OE=Ke(),ws=ft(),th=No(),FE=ve(),NE=Np(),zp=gs(),Yp=Ko(),UE=Nr(),qE=Ni(),Xo=Qi(),HE=$e(),Kp=gi(),ih=Yo(),jE=th.PROPER,QE=th.CONFIGURABLE,Xp=ih.IteratorPrototype,As=ih.BUGGY_SAFARI_ITERATORS,Ur=HE("iterator"),Jp="keys",qr="values",Zp="entries",eh=function(){return this};rh.exports=function(a,e,t,i,r,s,n){NE(t,e,i);var o=function(T){if(T===r&&p)return p;if(!As&&T&&T in c)return c[T];switch(T){case Jp:return function(){return new t(this,T)};case qr:return function(){return new t(this,T)};case Zp:return function(){return new t(this,T)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Ur]||c["@@iterator"]||r&&c[r],p=!As&&d||o(r),h=e==="Array"&&c.entries||d,m,g,y;if(h&&(m=zp(h.call(new a)),m!==Object.prototype&&m.next&&(!ws&&zp(m)!==Xp&&(Yp?Yp(m,Xp):FE(m[Ur])||Xo(m,Ur,eh)),UE(m,u,!0,!0),ws&&(Kp[u]=eh))),jE&&r===qr&&d&&d.name!==qr&&(!ws&&QE?qE(c,"name",qr):(l=!0,p=function(){return OE(d,this)})),r)if(g={values:o(qr),keys:s?p:o(Jp),entries:o(Zp)},n)for(y in g)(As||l||!(y in c))&&Xo(c,y,g[y]);else _E({target:e,proto:!0,forced:As||l},g);return(!ws||n)&&c[Ur]!==p&&Xo(c,Ur,p,{name:r}),Kp[e]=p,g}});var nh=b((uM,sh)=>{"use strict";sh.exports=function(a,e){return{value:a,done:e}}});var Zo=b((lM,dh)=>{"use strict";var GE=hi(),Jo=_r(),oh=gi(),lh=_o(),WE=bi().f,zE=ah(),ks=nh(),YE=ft(),KE=Ye(),ch="Array Iterator",XE=lh.set,JE=lh.getterFor(ch);dh.exports=zE(Array,"Array",function(a,e){XE(this,{type:ch,target:GE(a),index:0,kind:e})},function(){var a=JE(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,ks(void 0,!0);switch(a.kind){case"keys":return ks(t,!1);case"values":return ks(e[t],!1)}return ks([t,e[t]],!1)},"values");var uh=oh.Arguments=oh.Array;Jo("keys");Jo("values");Jo("entries");if(!YE&&KE&&uh.name!=="values")try{WE(uh,"name",{value:"values"})}catch{}});var hh=b((cM,ph)=>{"use strict";var ZE=$e(),ex=gi(),tx=ZE("iterator"),ix=Array.prototype;ph.exports=function(a){return a!==void 0&&(ex.Array===a||ix[tx]===a)}});var eu=b((dM,mh)=>{"use strict";var rx=Fr(),fh=Mr(),ax=Rr(),sx=gi(),nx=$e(),ox=nx("iterator");mh.exports=function(a){if(!ax(a))return fh(a,ox)||fh(a,"@@iterator")||sx[rx(a)]}});var gh=b((pM,bh)=>{"use strict";var ux=Ke(),lx=xt(),cx=wt(),dx=$r(),px=eu(),hx=TypeError;bh.exports=function(a,e){var t=arguments.length<2?px(a):e;if(lx(t))return cx(ux(t,a));throw new hx(dx(a)+" is not iterable")}});var yh=b((hM,vh)=>{"use strict";var fx=Ke(),Sh=wt(),mx=Mr();vh.exports=function(a,e,t){var i,r;Sh(a);try{if(i=mx(a,"return"),!i){if(e==="throw")throw t;return t}i=fx(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Sh(i),t}});var Rs=b((fM,xh)=>{"use strict";var bx=Fi(),gx=Ke(),Sx=wt(),vx=$r(),yx=hh(),Tx=Hi(),Th=Lr(),Ix=gh(),Ex=eu(),Ih=yh(),xx=TypeError,Ps=function(a,e){this.stopped=a,this.result=e},Eh=Ps.prototype;xh.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=bx(e,i),l,c,d,p,h,m,g,y=function(k){return l&&Ih(l,"normal"),new Ps(!0,k)},T=function(k){return r?(Sx(k),o?u(k[0],k[1],y):u(k[0],k[1])):o?u(k,y):u(k)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Ex(a),!c)throw new xx(vx(a)+" is not iterable");if(yx(c)){for(d=0,p=Tx(a);p>d;d++)if(h=T(a[d]),h&&Th(Eh,h))return h;return new Ps(!1)}l=Ix(a,c)}for(m=s?a.next:l.next;!(g=gx(m,l)).done;){try{h=T(g.value)}catch(k){Ih(l,"throw",k)}if(typeof h=="object"&&h&&Th(Eh,h))return h}return new Ps(!1)}});var Ah=b((mM,wh)=>{"use strict";var wx=Ye(),Ax=bi(),kx=Pr();wh.exports=function(a,e,t){wx?Ax.f(a,e,kx(0,t)):a[e]=t}});var kh=b(()=>{"use strict";var Px=Te(),Rx=Rs(),Lx=Ah();Px({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Rx(e,function(i,r){Lx(t,i,r)},{AS_ENTRIES:!0}),t}})});var Rh=b((SM,Ph)=>{"use strict";Zo();kh();var $x=fi();Ph.exports=$x.Object.fromEntries});var $h=b((vM,Lh)=>{"use strict";Lh.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 Dh=b(()=>{"use strict";Zo();var Mx=$h(),Dx=Se(),Cx=Nr(),Mh=gi();for(Ls in Mx)Cx(Dx[Ls],Ls),Mh[Ls]=Mh.Array;var Ls});var Bh=b((IM,Ch)=>{"use strict";var Bx=Rh();Dh();Ch.exports=Bx});var tu=b((EM,Vh)=>{"use strict";var Vx=Bh();Vh.exports=Vx});var _h=b(()=>{"use strict"});var iu=b((AM,Oh)=>{"use strict";var Hr=Se(),_x=mi(),Ox=pi(),$s=function(a){return _x.slice(0,a.length)===a};Oh.exports=function(){return $s("Bun/")?"BUN":$s("Cloudflare-Workers")?"CLOUDFLARE":$s("Deno/")?"DENO":$s("Node.js/")?"NODE":Hr.Bun&&typeof Bun.version=="string"?"BUN":Hr.Deno&&typeof Deno.version=="object"?"DENO":Ox(Hr.process)==="process"?"NODE":Hr.window&&Hr.document?"BROWSER":"REST"}()});var Ms=b((kM,Fh)=>{"use strict";var Fx=iu();Fh.exports=Fx==="NODE"});var Uh=b((PM,Nh)=>{"use strict";var Nx=bi();Nh.exports=function(a,e,t){return Nx.f(a,e,t)}});var jh=b((RM,Hh)=>{"use strict";var Ux=Vt(),qx=Uh(),Hx=$e(),jx=Ye(),qh=Hx("species");Hh.exports=function(a){var e=Ux(a);jx&&e&&!e[qh]&&qx(e,qh,{configurable:!0,get:function(){return this}})}});var Gh=b((LM,Qh)=>{"use strict";var Qx=Lr(),Gx=TypeError;Qh.exports=function(a,e){if(Qx(e,a))return a;throw new Gx("Incorrect invocation")}});var au=b(($M,Wh)=>{"use strict";var Wx=Ae(),zx=ve(),ru=Dr(),Yx=Wx(Function.toString);zx(ru.inspectSource)||(ru.inspectSource=function(a){return Yx(a)});Wh.exports=ru.inspectSource});var nu=b((MM,Jh)=>{"use strict";var Kx=Ae(),Xx=we(),zh=ve(),Jx=Fr(),Zx=Vt(),ew=au(),Yh=function(){},Kh=Zx("Reflect","construct"),su=/^\s*(?:class|function)\b/,tw=Kx(su.exec),iw=!su.test(Yh),jr=function(e){if(!zh(e))return!1;try{return Kh(Yh,[],e),!0}catch{return!1}},Xh=function(e){if(!zh(e))return!1;switch(Jx(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return iw||!!tw(su,ew(e))}catch{return!0}};Xh.sham=!0;Jh.exports=!Kh||Xx(function(){var a;return jr(jr.call)||!jr(Object)||!jr(function(){a=!0})||a})?Xh:jr});var ef=b((DM,Zh)=>{"use strict";var rw=nu(),aw=$r(),sw=TypeError;Zh.exports=function(a){if(rw(a))return a;throw new sw(aw(a)+" is not a constructor")}});var ou=b((CM,rf)=>{"use strict";var tf=wt(),nw=ef(),ow=Rr(),uw=$e(),lw=uw("species");rf.exports=function(a,e){var t=tf(a).constructor,i;return t===void 0||ow(i=tf(t)[lw])?e:nw(i)}});var sf=b((BM,af)=>{"use strict";var cw=Ae();af.exports=cw([].slice)});var of=b((VM,nf)=>{"use strict";var dw=TypeError;nf.exports=function(a,e){if(a<e)throw new dw("Not enough arguments");return a}});var uu=b((_M,uf)=>{"use strict";var pw=mi();uf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(pw)});var gu=b((OM,gf)=>{"use strict";var Xe=Se(),hw=Jn(),fw=Fi(),lf=ve(),mw=mt(),bf=we(),cf=Uo(),bw=sf(),df=hs(),gw=of(),Sw=uu(),vw=Ms(),fu=Xe.setImmediate,mu=Xe.clearImmediate,yw=Xe.process,lu=Xe.Dispatch,Tw=Xe.Function,pf=Xe.MessageChannel,Iw=Xe.String,cu=0,Qr={},hf="onreadystatechange",Gr,vi,du,pu;bf(function(){Gr=Xe.location});var bu=function(a){if(mw(Qr,a)){var e=Qr[a];delete Qr[a],e()}},hu=function(a){return function(){bu(a)}},ff=function(a){bu(a.data)},mf=function(a){Xe.postMessage(Iw(a),Gr.protocol+"//"+Gr.host)};(!fu||!mu)&&(fu=function(e){gw(arguments.length,1);var t=lf(e)?e:Tw(e),i=bw(arguments,1);return Qr[++cu]=function(){hw(t,void 0,i)},vi(cu),cu},mu=function(e){delete Qr[e]},vw?vi=function(a){yw.nextTick(hu(a))}:lu&&lu.now?vi=function(a){lu.now(hu(a))}:pf&&!Sw?(du=new pf,pu=du.port2,du.port1.onmessage=ff,vi=fw(pu.postMessage,pu)):Xe.addEventListener&&lf(Xe.postMessage)&&!Xe.importScripts&&Gr&&Gr.protocol!=="file:"&&!bf(mf)?(vi=mf,Xe.addEventListener("message",ff,!1)):hf in df("script")?vi=function(a){cf.appendChild(df("script"))[hf]=function(){cf.removeChild(this),bu(a)}}:vi=function(a){setTimeout(hu(a),0)});gf.exports={set:fu,clear:mu}});var yf=b((FM,vf)=>{"use strict";var Sf=Se(),Ew=Ye(),xw=Object.getOwnPropertyDescriptor;vf.exports=function(a){if(!Ew)return Sf[a];var e=xw(Sf,a);return e&&e.value}});var Su=b((NM,If)=>{"use strict";var Tf=function(){this.head=null,this.tail=null};Tf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};If.exports=Tf});var xf=b((UM,Ef)=>{"use strict";var ww=mi();Ef.exports=/ipad|iphone|ipod/i.test(ww)&&typeof Pebble<"u"});var Af=b((qM,wf)=>{"use strict";var Aw=mi();wf.exports=/web0s(?!.*chrome)/i.test(Aw)});var Df=b((HM,Mf)=>{"use strict";var Wi=Se(),kw=yf(),kf=Fi(),vu=gu().set,Pw=Su(),Rw=uu(),Lw=xf(),$w=Af(),yu=Ms(),Pf=Wi.MutationObserver||Wi.WebKitMutationObserver,Rf=Wi.document,Lf=Wi.process,Ds=Wi.Promise,Eu=kw("queueMicrotask"),Gi,Tu,Iu,Cs,$f;Eu||(Wr=new Pw,zr=function(){var a,e;for(yu&&(a=Lf.domain)&&a.exit();e=Wr.get();)try{e()}catch(t){throw Wr.head&&Gi(),t}a&&a.enter()},!Rw&&!yu&&!$w&&Pf&&Rf?(Tu=!0,Iu=Rf.createTextNode(""),new Pf(zr).observe(Iu,{characterData:!0}),Gi=function(){Iu.data=Tu=!Tu}):!Lw&&Ds&&Ds.resolve?(Cs=Ds.resolve(void 0),Cs.constructor=Ds,$f=kf(Cs.then,Cs),Gi=function(){$f(zr)}):yu?Gi=function(){Lf.nextTick(zr)}:(vu=kf(vu,Wi),Gi=function(){vu(zr)}),Eu=function(a){Wr.head||Gi(),Wr.add(a)});var Wr,zr;Mf.exports=Eu});var Bf=b((jM,Cf)=>{"use strict";Cf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var Bs=b((QM,Vf)=>{"use strict";Vf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var yi=b((GM,_f)=>{"use strict";var Mw=Se();_f.exports=Mw.Promise});var zi=b((WM,Uf)=>{"use strict";var Dw=Se(),Yr=yi(),Cw=ve(),Bw=To(),Vw=au(),_w=$e(),Of=iu(),Ow=ft(),xu=oo(),Ff=Yr&&Yr.prototype,Fw=_w("species"),wu=!1,Nf=Cw(Dw.PromiseRejectionEvent),Nw=Bw("Promise",function(){var a=Vw(Yr),e=a!==String(Yr);if(!e&&xu===66||Ow&&!(Ff.catch&&Ff.finally))return!0;if(!xu||xu<51||!/native code/.test(a)){var t=new Yr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[Fw]=i,wu=t.then(function(){})instanceof i,!wu)return!0}return!e&&(Of==="BROWSER"||Of==="DENO")&&!Nf});Uf.exports={CONSTRUCTOR:Nw,REJECTION_EVENT:Nf,SUBCLASSING:wu}});var Yi=b((zM,Hf)=>{"use strict";var qf=xt(),Uw=TypeError,qw=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new Uw("Bad Promise constructor");e=i,t=r}),this.resolve=qf(e),this.reject=qf(t)};Hf.exports.f=function(a){return new qw(a)}});var lm=b(()=>{"use strict";var Hw=Te(),jw=ft(),Fs=Ms(),Zt=Se(),Qw=fi(),Zi=Ke(),jf=Qi(),Qf=Ko(),Gw=Nr(),Ww=jh(),zw=xt(),Os=ve(),Yw=Ne(),Kw=Gh(),Xw=ou(),Kf=gu().set,Lu=Df(),Jw=Bf(),Zw=Bs(),eA=Su(),Xf=_o(),Ns=yi(),$u=zi(),Jf=Yi(),Us="Promise",Zf=$u.CONSTRUCTOR,tA=$u.REJECTION_EVENT,iA=$u.SUBCLASSING,Au=Xf.getterFor(Us),rA=Xf.set,Ki=Ns&&Ns.prototype,Ti=Ns,Vs=Ki,em=Zt.TypeError,ku=Zt.document,Mu=Zt.process,Pu=Jf.f,aA=Pu,sA=!!(ku&&ku.createEvent&&Zt.dispatchEvent),tm="unhandledrejection",nA="rejectionhandled",Gf=0,im=1,oA=2,Du=1,rm=2,_s,Wf,am,zf,sm=function(a){var e;return Yw(a)&&Os(e=a.then)?e:!1},nm=function(a,e){var t=e.value,i=e.state===im,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===rm&&lA(e),e.rejection=Du),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new em("Promise-chain cycle")):(l=sm(u))?Zi(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},om=function(a,e){a.notified||(a.notified=!0,Lu(function(){for(var t=a.reactions,i;i=t.get();)nm(i,a);a.notified=!1,e&&!a.rejection&&uA(a)}))},um=function(a,e,t){var i,r;sA?(i=ku.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Zt.dispatchEvent(i)):i={promise:e,reason:t},!tA&&(r=Zt["on"+a])?r(i):a===tm&&Jw("Unhandled promise rejection",t)},uA=function(a){Zi(Kf,Zt,function(){var e=a.facade,t=a.value,i=Yf(a),r;if(i&&(r=Zw(function(){Fs?Mu.emit("unhandledRejection",t,e):um(tm,e,t)}),a.rejection=Fs||Yf(a)?rm:Du,r.error))throw r.value})},Yf=function(a){return a.rejection!==Du&&!a.parent},lA=function(a){Zi(Kf,Zt,function(){var e=a.facade;Fs?Mu.emit("rejectionHandled",e):um(nA,e,a.value)})},Xi=function(a,e,t){return function(i){a(e,i,t)}},Ji=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=oA,om(a,!0))},Ru=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new em("Promise can't be resolved itself");var i=sm(e);i?Lu(function(){var r={done:!1};try{Zi(i,e,Xi(Ru,r,a),Xi(Ji,r,a))}catch(s){Ji(r,s,a)}}):(a.value=e,a.state=im,om(a,!1))}catch(r){Ji({done:!1},r,a)}}};if(Zf&&(Ti=function(e){Kw(this,Vs),zw(e),Zi(_s,this);var t=Au(this);try{e(Xi(Ru,t),Xi(Ji,t))}catch(i){Ji(t,i)}},Vs=Ti.prototype,_s=function(e){rA(this,{type:Us,done:!1,notified:!1,parent:!1,reactions:new eA,rejection:!1,state:Gf,value:null})},_s.prototype=jf(Vs,"then",function(e,t){var i=Au(this),r=Pu(Xw(this,Ti));return i.parent=!0,r.ok=Os(e)?e:!0,r.fail=Os(t)&&t,r.domain=Fs?Mu.domain:void 0,i.state===Gf?i.reactions.add(r):Lu(function(){nm(r,i)}),r.promise}),Wf=function(){var a=new _s,e=Au(a);this.promise=a,this.resolve=Xi(Ru,e),this.reject=Xi(Ji,e)},Jf.f=Pu=function(a){return a===Ti||a===am?new Wf(a):aA(a)},!jw&&Os(Ns)&&Ki!==Object.prototype)){zf=Ki.then,iA||jf(Ki,"then",function(e,t){var i=this;return new Ti(function(r,s){Zi(zf,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Ki.constructor}catch{}Qf&&Qf(Ki,Vs)}Hw({global:!0,constructor:!0,wrap:!0,forced:Zf},{Promise:Ti});am=Qw.Promise;Gw(Ti,Us,!1,!0);Ww(Us)});var fm=b((XM,hm)=>{"use strict";var cA=$e(),dm=cA("iterator"),pm=!1;try{cm=0,Cu={next:function(){return{done:!!cm++}},return:function(){pm=!0}},Cu[dm]=function(){return this},Array.from(Cu,function(){throw 2})}catch{}var cm,Cu;hm.exports=function(a,e){try{if(!e&&!pm)return!1}catch{return!1}var t=!1;try{var i={};i[dm]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Bu=b((JM,mm)=>{"use strict";var dA=yi(),pA=fm(),hA=zi().CONSTRUCTOR;mm.exports=hA||!pA(function(a){dA.all(a).then(void 0,function(){})})});var bm=b(()=>{"use strict";var fA=Te(),mA=Ke(),bA=xt(),gA=Yi(),SA=Bs(),vA=Rs(),yA=Bu();fA({target:"Promise",stat:!0,forced:yA},{all:function(e){var t=this,i=gA.f(t),r=i.resolve,s=i.reject,n=SA(function(){var o=bA(t.resolve),u=[],l=0,c=1;vA(e,function(d){var p=l++,h=!1;c++,mA(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var Sm=b(()=>{"use strict";var TA=Te(),IA=ft(),EA=zi().CONSTRUCTOR,_u=yi(),xA=Vt(),wA=ve(),AA=Qi(),gm=_u&&_u.prototype;TA({target:"Promise",proto:!0,forced:EA,real:!0},{catch:function(a){return this.then(void 0,a)}});!IA&&wA(_u)&&(Vu=xA("Promise").prototype.catch,gm.catch!==Vu&&AA(gm,"catch",Vu,{unsafe:!0}));var Vu});var vm=b(()=>{"use strict";var kA=Te(),PA=Ke(),RA=xt(),LA=Yi(),$A=Bs(),MA=Rs(),DA=Bu();kA({target:"Promise",stat:!0,forced:DA},{race:function(e){var t=this,i=LA.f(t),r=i.reject,s=$A(function(){var n=RA(t.resolve);MA(e,function(o){PA(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var ym=b(()=>{"use strict";var CA=Te(),BA=Yi(),VA=zi().CONSTRUCTOR;CA({target:"Promise",stat:!0,forced:VA},{reject:function(e){var t=BA.f(this),i=t.reject;return i(e),t.promise}})});var Ou=b((oD,Tm)=>{"use strict";var _A=wt(),OA=Ne(),FA=Yi();Tm.exports=function(a,e){if(_A(a),OA(e)&&e.constructor===a)return e;var t=FA.f(a),i=t.resolve;return i(e),t.promise}});var xm=b(()=>{"use strict";var NA=Te(),UA=Vt(),Im=ft(),qA=yi(),Em=zi().CONSTRUCTOR,HA=Ou(),jA=UA("Promise"),QA=Im&&!Em;NA({target:"Promise",stat:!0,forced:Im||Em},{resolve:function(e){return HA(QA&&this===jA?qA:this,e)}})});var wm=b(()=>{"use strict";lm();bm();Sm();vm();ym();xm()});var Rm=b(()=>{"use strict";var GA=Te(),WA=ft(),qs=yi(),zA=we(),km=Vt(),Pm=ve(),YA=ou(),Am=Ou(),KA=Qi(),Nu=qs&&qs.prototype,XA=!!qs&&zA(function(){Nu.finally.call({then:function(){}},function(){})});GA({target:"Promise",proto:!0,real:!0,forced:XA},{finally:function(a){var e=YA(this,km("Promise")),t=Pm(a);return this.then(t?function(i){return Am(e,a()).then(function(){return i})}:a,t?function(i){return Am(e,a()).then(function(){throw i})}:a)}});!WA&&Pm(qs)&&(Fu=km("Promise").prototype.finally,Nu.finally!==Fu&&KA(Nu,"finally",Fu,{unsafe:!0}));var Fu});var $m=b((fD,Lm)=>{"use strict";_h();wm();Rm();var JA=Jt();Lm.exports=JA("Promise","finally")});var Dm=b((mD,Mm)=>{"use strict";var ZA=$m();Mm.exports=ZA});var Hs=b((bD,Cm)=>{"use strict";var ek=Dm();Cm.exports=ek});var Um=b(()=>{"use strict";var sk=Te(),nk=Do().values;sk({target:"Object",stat:!0},{values:function(e){return nk(e)}})});var Hm=b((WD,qm)=>{"use strict";Um();var ok=fi();qm.exports=ok.Object.values});var Qm=b((zD,jm)=>{"use strict";var uk=Hm();jm.exports=uk});var er=b((YD,Gm)=>{"use strict";var lk=Qm();Gm.exports=lk});var rb=b(()=>{"use strict";var vk=Te(),yk=_i(),Tk=Hi(),Ik=Vr(),Ek=_r();vk({target:"Array",proto:!0},{at:function(e){var t=yk(this),i=Tk(t),r=Ik(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});Ek("at")});var sb=b((ZC,ab)=>{"use strict";rb();var xk=Jt();ab.exports=xk("Array","at")});var ob=b((eB,nb)=>{"use strict";var wk=sb();nb.exports=wk});var Pt=b((tB,ub)=>{"use strict";var Ak=ob();ub.exports=Ak});var sl=b((B0,Mb)=>{"use strict";var _k=pi();Mb.exports=Array.isArray||function(e){return _k(e)==="Array"}});var Cb=b((V0,Db)=>{"use strict";var Ok=TypeError,Fk=9007199254740991;Db.exports=function(a){if(a>Fk)throw Ok("Maximum allowed index exceeded");return a}});var _b=b((_0,Vb)=>{"use strict";var Nk=sl(),Uk=Hi(),qk=Cb(),Hk=Fi(),Bb=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?Hk(n,o):!1,d,p;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&Nk(d)?(p=Uk(d),u=Bb(a,e,d,p,u,s-1)-1):(qk(u+1),a[u]=d),u++),l++;return u};Vb.exports=Bb});var Ub=b((O0,Nb)=>{"use strict";var Ob=sl(),jk=nu(),Qk=Ne(),Gk=$e(),Wk=Gk("species"),Fb=Array;Nb.exports=function(a){var e;return Ob(a)&&(e=a.constructor,jk(e)&&(e===Fb||Ob(e.prototype))?e=void 0:Qk(e)&&(e=e[Wk],e===null&&(e=void 0))),e===void 0?Fb:e}});var Hb=b((F0,qb)=>{"use strict";var zk=Ub();qb.exports=function(a,e){return new(zk(a))(e===0?0:e)}});var jb=b(()=>{"use strict";var Yk=Te(),Kk=_b(),Xk=xt(),Jk=_i(),Zk=Hi(),eP=Hb();Yk({target:"Array",proto:!0},{flatMap:function(e){var t=Jk(this),i=Zk(t),r;return Xk(e),r=eP(t,0),r.length=Kk(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Qb=b(()=>{"use strict";var tP=_r();tP("flatMap")});var Wb=b((j0,Gb)=>{"use strict";jb();Qb();var iP=Jt();Gb.exports=iP("Array","flatMap")});var Yb=b((Q0,zb)=>{"use strict";var rP=Wb();zb.exports=rP});var oa=b((G0,Kb)=>{"use strict";var aP=Yb();Kb.exports=aP});var ua=b((W0,Xb)=>{"use strict";var sP=Fr(),nP=String;Xb.exports=function(a){if(sP(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return nP(a)}});var nl=b((z0,Jb)=>{"use strict";Jb.exports=`
|
|
7
|
-
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var tg=b((Y0,eg)=>{"use strict";var oP=Ae(),uP=Xt(),lP=ua(),ul=nl(),Zb=oP("".replace),cP=RegExp("^["+ul+"]+"),dP=RegExp("(^|[^"+ul+"])["+ul+"]+$"),ol=function(a){return function(e){var t=lP(uP(e));return a&1&&(t=Zb(t,cP,"")),a&2&&(t=Zb(t,dP,"$1")),t}};eg.exports={start:ol(1),end:ol(2),trim:ol(3)}});var sg=b((K0,ag)=>{"use strict";var pP=No().PROPER,hP=we(),ig=nl(),rg="\u200B\x85\u180E";ag.exports=function(a){return hP(function(){return!!ig[a]()||rg[a]()!==rg||pP&&ig[a].name!==a})}});var ll=b((X0,ng)=>{"use strict";var fP=tg().start,mP=sg();ng.exports=mP("trimStart")?function(){return fP(this)}:"".trimStart});var ug=b(()=>{"use strict";var bP=Te(),og=ll();bP({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==og},{trimLeft:og})});var cg=b(()=>{"use strict";ug();var gP=Te(),lg=ll();gP({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==lg},{trimStart:lg})});var pg=b((iV,dg)=>{"use strict";cg();var SP=Jt();dg.exports=SP("String","trimLeft")});var fg=b((rV,hg)=>{"use strict";var vP=pg();hg.exports=vP});var bg=b((aV,mg)=>{"use strict";var yP=fg();mg.exports=yP});var Rg=b(()=>{"use strict"});var Lg=b(()=>{"use strict"});var Mg=b((BO,$g)=>{"use strict";var NP=Ne(),UP=pi(),qP=$e(),HP=qP("match");$g.exports=function(a){var e;return NP(a)&&((e=a[HP])!==void 0?!!e:UP(a)==="RegExp")}});var Bg=b((VO,Cg)=>{"use strict";var jP=Se(),QP=we(),Dg=jP.RegExp,GP=!QP(function(){var a=!0;try{Dg(".","d")}catch{a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(u,l){Object.defineProperty(e,u,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var o=Object.getOwnPropertyDescriptor(Dg.prototype,"flags").get.call(e);return o!==i||t!==i});Cg.exports={correct:GP}});var _g=b((_O,Vg)=>{"use strict";var WP=wt();Vg.exports=function(){var a=WP(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var Ng=b((OO,Fg)=>{"use strict";var zP=Ke(),YP=mt(),KP=Lr(),Og=Bg(),XP=_g(),JP=RegExp.prototype;Fg.exports=Og.correct?function(a){return a.flags}:function(a){return!Og.correct&&KP(JP,a)&&!YP(a,"flags")?zP(XP,a):a.flags}});var qg=b((FO,Ug)=>{"use strict";var hl=Ae(),ZP=_i(),eR=Math.floor,dl=hl("".charAt),tR=hl("".replace),pl=hl("".slice),iR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,rR=/\$([$&'`]|\d{1,2})/g;Ug.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=rR;return r!==void 0&&(r=ZP(r),u=iR),tR(s,u,function(l,c){var d;switch(dl(c,0)){case"$":return"$";case"&":return a;case"`":return pl(e,0,t);case"'":return pl(e,n);case"<":d=r[pl(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=eR(p/10);return h===0?l:h<=o?i[h-1]===void 0?dl(c,1):i[h-1]+dl(c,1):l}d=i[p-1]}return d===void 0?"":d})}});var Qg=b(()=>{"use strict";var aR=Te(),sR=Ke(),ml=Ae(),Hg=Xt(),nR=ve(),oR=Ne(),uR=Mg(),pr=ua(),lR=Mr(),cR=Ng(),dR=qg(),pR=$e(),hR=ft(),fR=pR("replace"),mR=TypeError,fl=ml("".indexOf),bR=ml("".replace),jg=ml("".slice),gR=Math.max;aR({target:"String",proto:!0},{replaceAll:function(e,t){var i=Hg(this),r,s,n,o,u,l,c,d,p,h,m=0,g="";if(oR(e)){if(r=uR(e),r&&(s=pr(Hg(cR(e))),!~fl(s,"g")))throw new mR("`.replaceAll` does not allow non-global regexes");if(n=lR(e,fR),n)return sR(n,e,i,t);if(hR&&r)return bR(pr(i),e,t)}for(o=pr(i),u=pr(e),l=nR(t),l||(t=pr(t)),c=u.length,d=gR(1,c),p=fl(o,u);p!==-1;)h=l?pr(t(u,p,o)):dR(u,o,p,[],void 0,t),g+=jg(o,m,p)+h,m=p+c,p=p+d>o.length?-1:fl(o,u,p+d);return m<o.length&&(g+=jg(o,m)),g}})});var Wg=b((qO,Gg)=>{"use strict";Rg();Lg();Qg();var SR=Jt();Gg.exports=SR("String","replaceAll")});var Yg=b((HO,zg)=>{"use strict";var vR=Wg();zg.exports=vR});var Xg=b((jO,Kg)=>{"use strict";var yR=Yg();Kg.exports=yR});var Zg=b((QO,Jg)=>{"use strict";var TR=Vr(),IR=ua(),ER=Xt(),xR=RangeError;Jg.exports=function(e){var t=IR(ER(this)),i="",r=TR(e);if(r<0||r===1/0)throw new xR("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var aS=b((GO,rS)=>{"use strict";var iS=Ae(),wR=ko(),eS=ua(),AR=Zg(),kR=Xt(),PR=iS(AR),RR=iS("".slice),LR=Math.ceil,tS=function(a){return function(e,t,i){var r=eS(kR(e)),s=wR(t),n=r.length,o=i===void 0?" ":eS(i),u,l;return s<=n||o===""?r:(u=s-n,l=PR(o,LR(u/o.length)),l.length>u&&(l=RR(l,0,u)),a?r+l:l+r)}};rS.exports={start:tS(!1),end:tS(!0)}});var nS=b((WO,sS)=>{"use strict";var $R=mi();sS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test($R)});var oS=b(()=>{"use strict";var MR=Te(),DR=aS().start,CR=nS();MR({target:"String",proto:!0,forced:CR},{padStart:function(e){return DR(this,e,arguments.length>1?arguments[1]:void 0)}})});var lS=b((KO,uS)=>{"use strict";oS();var BR=Jt();uS.exports=BR("String","padStart")});var dS=b((XO,cS)=>{"use strict";var VR=lS();cS.exports=VR});var hS=b((JO,pS)=>{"use strict";var _R=dS();pS.exports=_R});var lL={};xv(lL,{ChromecastState:()=>xr,HttpConnectionType:()=>ls,Observable:()=>Ct.Observable,PlaybackState:()=>Ve,Player:()=>Za,PredefinedQualityLimits:()=>wr,SDK_VERSION:()=>uL,Subject:()=>Ct.Subject,Subscription:()=>Ct.Subscription,Surface:()=>cs,VERSION:()=>Kn,ValueSubject:()=>Ct.ValueSubject,VideoFormat:()=>Et,VideoQuality:()=>Ct.VideoQuality,clientChecker:()=>j,isMobile:()=>tr});module.exports=wv(lL);var Kn="2.0.136-dev.b3347749.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ve||{}),Et=(I=>(I.MPEG="MPEG",I.DASH="DASH",I.DASH_SEP="DASH_SEP",I.DASH_SEP_VK="DASH_SEP",I.DASH_WEBM="DASH_WEBM",I.DASH_WEBM_AV1="DASH_WEBM_AV1",I.DASH_STREAMS="DASH_STREAMS",I.DASH_WEBM_VK="DASH_WEBM",I.DASH_ONDEMAND="DASH_ONDEMAND",I.DASH_ONDEMAND_VK="DASH_ONDEMAND",I.DASH_LIVE="DASH_LIVE",I.DASH_LIVE_CMAF="DASH_LIVE_CMAF",I.DASH_LIVE_WEBM="DASH_LIVE_WEBM",I.HLS="HLS",I.HLS_ONDEMAND="HLS_ONDEMAND",I.HLS_JS="HLS",I.HLS_LIVE="HLS_LIVE",I.HLS_LIVE_CMAF="HLS_LIVE_CMAF",I.WEB_RTC_LIVE="WEB_RTC_LIVE",I))(Et||{});var xr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(xr||{}),ls=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ls||{});var cs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(cs||{}),wr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(wr||{});var fv=K(st(),1);var Z=require("@vkontakte/videoplayer-shared");var Fd=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var ms=class{constructor(e){this.connection$=new Z.ValueSubject(void 0);this.castState$=new Z.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new Z.Subject;this.realCastState$=new Z.ValueSubject("NOT_AVAILABLE");this.subscription=new Z.Subscription;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=(0,Z.isNonNullable)(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Fd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Z.ErrorCategory.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(){(0,Z.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,Z.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,Z.isNullable)(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((0,Z.fromEvent)(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(0,Z.assertNever)(r.sessionState)}})).add((0,Z.merge)((0,Z.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,Z.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,Z.map)(r=>r.castState)),(0,Z.observableFrom)([i.getCastState()])).pipe((0,Z.filterChanged)(),(0,Z.map)(WT),(0,Z.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=(0,Z.isNonNullable)(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();(0,Z.assertNonNullable)(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;((0,Z.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,Z.isNonNullable)(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:Z.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},WT=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,Z.assertNever)(a)}};var ql=K(st(),1),tv=K(ji(),1),iv=K(tu(),1);var Om=K(Hs(),1);var Uu=require("@vkontakte/videoplayer-shared");var ye=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,Uu.assertNever)(t)}return a},ei=(a,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:(0,Uu.assertNever)(e)}};var V=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var At=require("@vkontakte/videoplayer-shared"),ee=class{constructor(e){this.transitionStarted$=new At.Subject;this.transitionEnded$=new At.Subject;this.transitionUpdated$=new At.Subject;this.forceChanged$=new At.Subject;this.stateChangeStarted$=(0,At.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,At.merge)(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||(0,At.isNonNullable)(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}};var Bm=require("@vkontakte/videoplayer-shared"),Vm=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Bm.assertNever)(a)}};var U=require("@vkontakte/videoplayer-shared");var tk=5,ik=5,rk=500,_m=7e3,Kr=class{constructor(e){this.subscription=new U.Subscription;this.loadMediaTimeoutSubscription=new U.Subscription;this.videoState=new ee("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,U.assertNever)(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:(0,U.assertNever)(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:(0,U.assertNever)(e)}break}default:(0,U.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Vm(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 U.Subscription;this.subscription.add(e),this.subscription.add((0,U.merge)(this.videoState.stateChangeStarted$.pipe((0,U.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,U.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new U.Subject;e.add(r.pipe((0,U.debounce)(rk)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>tk)&&r.next(o),s=o})),e.add((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<ik&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),V(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:(0,U.assertNever)(n)}}),t((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,U.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(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"),V(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),V(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),V(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&V(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()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];(0,U.assertNonNullable)(l);let c=(0,U.getHighestQuality)(Object.keys(l));(0,U.assertNonNullable)(c);let d=l[c];(0,U.assertNonNullable)(d),i=d,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,U.assertNonNullable)(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];(0,U.assertNonNullable)(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,U.assertNonNullable)(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,U.assertNonNullable)(l),i=ye(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:U.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,U.assertNever)(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return(0,U.isNonNullable)(o)&&(n.metadata.title=o),(0,U.isNonNullable)(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,U.timeout)(_m).subscribe(()=>s(`timeout(${_m})`)))});(0,Om.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:U.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var rl=K(st(),1);var Qu=require("@vkontakte/videoplayer-shared");var Fm=require("@vkontakte/videoplayer-shared"),Nm=a=>{try{a.pause(),a.playbackRate=0,(0,Fm.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var js=require("@vkontakte/videoplayer-shared"),qu=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)}},Hu=window.WeakMap?new WeakMap:new qu,ju=window.WeakMap?new WeakMap:new Map,ak=(a,e=20)=>{let t=0;return(0,js.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ue=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,Qu.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),Hu.set(i,r);let s=new js.Subscription;return s.add(ak(i,e)),ju.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},qe=a=>{ju.get(a)?.unsubscribe(),ju.delete(a);let t=Hu.get(a);Hu.delete(a),t?(0,Qu.clearVideoElement)(a):Nm(a)};var Gu=K(er(),1),q=require("@vkontakte/videoplayer-shared");var ti=require("@vkontakte/videoplayer-shared"),Qs=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=(0,ti.isNullable)(r),l=new ti.Subscription;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},kt=(a,e,t)=>Qs(e,()=>a.loop,i=>{(0,ti.isNonNullable)(i)&&(a.loop=i)},{onError:t}),He=(a,e,t,i)=>Qs(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,ti.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),nt=(a,e,t,i)=>Qs(e,()=>a.playbackRate,r=>{(0,ti.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Xr=Qs;var ck=a=>["__",a.language,a.label].join("|"),dk=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Wu=class a{constructor(e){this.available$=new q.Subject;this.current$=new q.ValueSubject(void 0);this.error$=new q.Subject;this.subscription=new q.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:q.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Xr(t.internalTextTracks,()=>(0,Gu.default)(this.internalTracks),s=>{(0,q.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,q.isNonNullable)(s)&&(0,q.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,q.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Xr(t.externalTextTracks,()=>(0,Gu.default)(this.externalTracks),s=>{(0,q.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,q.isNonNullable)(s)&&(0,q.isNonNullable)(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe((0,q.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Xr(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Xr(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,q.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,q.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,q.merge)((0,q.fromEvent)(e,"addtrack"),(0,q.fromEvent)(e,"removetrack"),(0,q.observableFrom)(["init"])).pipe((0,q.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,q.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,q.merge)((0,q.fromEvent)(e,"change"),(0,q.observableFrom)(["init"])).pipe((0,q.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,q.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,q.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,q.fromEvent)(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add((0,q.fromEvent)(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;(0,q.isNonNullable)(t.align)&&(r.align=t.align),(0,q.isNonNullable)(t.position)&&(r.position=t.position),(0,q.isNonNullable)(t.size)&&(r.size=t.size),(0,q.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,q.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:ck(e),s=this.externalTracks.has(r),n=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{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:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,q.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,q.isNullable)(e)||!dk(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){(0,q.assertNonNullable)(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){(0,q.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},ot=Wu;var Ii=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 Wm=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},zu=a=>{let e=Wm(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},zm=a=>{let e=Wm(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var C=require("@vkontakte/videoplayer-shared");var pk=3,Ym=(a,e,t=pk)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var Gs=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._isMiuiBrowser=/(XiaoMi)|(MiuiBrowser)/i.test(e),this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Km=K(st(),1);var tr=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var Ws=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Km.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=tr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var zs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Je=()=>window.ManagedMediaSource||window.MediaSource,ir=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Xm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Ys=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var hk=document.createElement("video"),fk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',mk='video/mp4; codecs="hev1.1.6.L93.B0"',Jm='video/webm; codecs="vp09.00.10.08"',Zm='video/webm; codecs="av01.0.00M.08"',bk='audio/mp4; codecs="mp4a.40.2"',gk='audio/webm; codecs="opus"',eb,Sk=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Zm}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Jm}})]);eb={DASH_WEBM_AV1:e,DASH_WEBM:t}};Sk().catch(a=>{console.log(hk),console.error(a)});var Ks=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 eb}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:ir(),mse:Xm(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Je()?.isTypeSupported?.(fk),t=!!Je()?.isTypeSupported?.(mk),i=!!Je()?.isTypeSupported?.(bk);this._codecs={h264:e,h265:t,vp9:!!Je()?.isTypeSupported?.(Jm),av1:!!Je()?.isTypeSupported?.(Zm),aac:i,opus:!!Je()?.isTypeSupported?.(gk),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){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}};var tb="audio/mpeg",Xs=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(tb)},this._codecs={mp3:!!Je()?.isTypeSupported?.(tb)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}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 ib=require("@vkontakte/videoplayer-shared"),Yu=class{constructor(){this.isInited$=new ib.ValueSubject(!1);this._displayChecker=new zs,this._deviceChecker=new Ws(this._displayChecker),this._browserChecker=new Gs,this._videoChecker=new Ks(this._deviceChecker,this._browserChecker),this._audioChecker=new Xs,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},j=new Yu;var je=a=>{let e=x=>(0,C.fromEvent)(a,x).pipe((0,C.mapTo)(void 0)),t=new C.Subscription,i=()=>t.unsubscribe(),r=(0,C.merge)((0,C.fromEvent)(a,"progress"),(0,C.fromEvent)(a,"timeupdate")).pipe((0,C.map)(()=>Ym(a.buffered,a.currentTime))),s=j.browser.isSafari?(0,C.combine)({play:e("play").pipe((0,C.once)()),playing:e("playing")}).pipe((0,C.mapTo)(void 0)):e("playing"),n=(0,C.fromEvent)(a,"volumechange").pipe((0,C.map)(()=>({muted:a.muted,volume:a.volume}))),o=(0,C.fromEvent)(a,"ratechange").pipe((0,C.map)(()=>a.playbackRate)),u=(0,C.fromEvent)(a,"error").pipe((0,C.filter)(()=>!!(a.error||a.played.length)),(0,C.map)(()=>{let x=a.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:C.ErrorCategory.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:a.error??void 0}})),l=(0,C.fromEvent)(a,"timeupdate").pipe((0,C.map)(()=>a.currentTime)),c=["waiting","seeking","seeked","timeupdate"],d=new C.Subject,p=.3,h;t.add((0,C.merge)(...c.map(x=>(0,C.fromEvent)(a,x))).subscribe(x=>{let F=a.currentTime;a.loop&&(0,C.isNonNullable)(h)&&(0,C.isNonNullable)(F)&&h>=a.duration-p&&F<=p&&d.next(h),h=F}));let m=e("pause").pipe((0,C.filter)(()=>!a.error&&h!==a.duration)),g=(0,C.fromEvent)(a,"enterpictureinpicture"),y=(0,C.fromEvent)(a,"leavepictureinpicture"),T=new C.ValueSubject(zm(a));t.add(g.subscribe(()=>T.next(!0))),t.add(y.subscribe(()=>T.next(!1)));let k=new C.ValueSubject(zu(a)),I=(0,C.fromEvent)(a,"fullscreenchange");t.add(I.pipe((0,C.map)(()=>zu(a))).subscribe(k));let $=.1,M=1e3,_=(0,C.fromEvent)(a,"timeupdate").pipe((0,C.map)(x=>a.duration-a.currentTime<$),(0,C.filterChanged)()),Y=(0,C.merge)(_.pipe((0,C.filter)(x=>!a.loop&&x)),(0,C.fromEvent)(a,"ended")).pipe((0,C.throttle)(M),(0,C.mapTo)(void 0)),O=(0,C.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>(0,C.fromEvent)(a,x)),_.pipe((0,C.map)(x=>({type:x?"ended":"unknown"})))).pipe((0,C.map)(x=>j.browser.isFirefox&&x.type==="ended"?a.readyState<2:a.readyState<3),(0,C.filterChanged)());return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:Y,looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,C.fromEvent)(a,"durationchange").pipe((0,C.map)(()=>a.duration)),isBuffering$:O,currentBuffer$:r,volumeState$:n,playbackRateState$:o,inPiP$:T,inFullscreen$:k,enterPip$:g,leavePip$:y,destroy:i}};var Ft=require("@vkontakte/videoplayer-shared"),ii=a=>{switch(a){case"mobile":return Ft.VideoQuality.Q_144P;case"lowest":return Ft.VideoQuality.Q_240P;case"low":return Ft.VideoQuality.Q_360P;case"sd":case"medium":return Ft.VideoQuality.Q_480P;case"hd":case"high":return Ft.VideoQuality.Q_720P;case"fullhd":case"full":return Ft.VideoQuality.Q_1080P;case"quadhd":case"quad":return Ft.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Ft.VideoQuality.Q_2160P}};var Oe=K(Pt(),1),Ju=K(st(),1),Ei=K(ji(),1),L=require("@vkontakte/videoplayer-shared");var Ku=!1,Nt={},lb=a=>{Ku=a},cb=()=>{Nt={}},db=a=>{a(Nt)},Jr=(a,e)=>{Ku&&(Nt.meta=Nt.meta??{},Nt.meta[a]=e)},_e=class{constructor(e){this.name=e}next(e){if(!Ku)return;Nt.series=Nt.series??{};let t=Nt.series[this.name]??[];t.push([Date.now(),e]),Nt.series[this.name]=t}};var Ie=require("@vkontakte/videoplayer-shared");function Xu(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Js(a,e,t){return!!a&&Xu(a,e,t)==="high_quality"}function rr(a,e,t){return(0,Ie.isNullable)(a)||(0,Ie.isNonNullable)(a.min)&&(0,Ie.isNonNullable)(a.max)&&(0,Ie.isLower)(a.max,a.min)||(0,Ie.isNonNullable)(a.min)&&e&&(0,Ie.isHigher)(a.min,e)||(0,Ie.isNonNullable)(a.max)&&t&&(0,Ie.isLower)(a.max,t)}function pb({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return rr({max:a?.max?(0,Ie.videoHeightToQuality)(a.max):void 0,min:a?.min?(0,Ie.videoHeightToQuality)(a.min):void 0},e?(0,Ie.videoHeightToQuality)(e):void 0,t?(0,Ie.videoHeightToQuality)(t):void 0)}var gb=new _e("best_bitrate"),en=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var ar=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),ri=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,L.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},tn='Assertion "ABR Tracks is empty array" failed',Zs=new WeakMap,hb=new WeakMap,fb=new WeakMap,Zr=(a,e,t,i)=>{let r=[...e].sort(ar(1)),s=[...t].sort(ar(1)),n=s.filter(u=>(0,L.isNonNullable)(u.bitrate)&&(0,L.isNonNullable)(a.bitrate)?a.bitrate/u.bitrate>i:!0),o=(0,Oe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Oe.default)(s,-1);return o&&(0,Ju.default)(n,o)?o:n.length?(0,Oe.default)(n,-1):(0,Oe.default)(s,0)},ea=(a,e,t,i)=>{let r=Zs.get(e);r||(r=[...e].sort(ar(1)),Zs.set(e,r));let s=Zs.get(t);s||(s=[...t].sort(ar(1)),Zs.set(t,s));let n=fb.get(a);n||(n=s.filter(u=>(0,L.isNonNullable)(u.bitrate)&&(0,L.isNonNullable)(a.bitrate)?a.bitrate/u.bitrate>i:!0),fb.set(a,n));let o=(0,Oe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Oe.default)(s,-1);return o&&(0,Ju.default)(n,o)?o:n.length?(0,Oe.default)(n,-1):(0,Oe.default)(s,0)},mb=a=>"quality"in a,rn=(a,e,t,i)=>{let r=(0,L.isNonNullable)(i?.last?.bitrate)&&(0,L.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,L.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let o=mb(n)?"video":"audio",u=mb(n)?n.quality:n.bitrate;return e({message:`
|
|
8
|
-
[last ${
|
|
9
|
-
`}),n}return i?.recordSwitch(t),t}
|
|
6
|
+
"use strict";var Ev=Object.create;var os=Object.defineProperty;var xv=Object.getOwnPropertyDescriptor;var wv=Object.getOwnPropertyNames;var Av=Object.getPrototypeOf,kv=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Pv=(a,e)=>{for(var t in e)os(a,t,{get:e[t],enumerable:!0})},Kl=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of wv(e))!kv.call(a,r)&&r!==t&&os(a,r,{get:()=>e[r],enumerable:!(i=xv(e,r))||i.enumerable});return a};var Q=(a,e,t)=>(t=a!=null?Ev(Av(a)):{},Kl(e||!a||!a.__esModule?os(t,"default",{value:a,enumerable:!0}):t,a)),Rv=a=>Kl(os({},"__esModule",{value:!0}),a);var Se=b((Jn,Xl)=>{"use strict";var Ar=function(a){return a&&a.Math===Math&&a};Xl.exports=Ar(typeof globalThis=="object"&&globalThis)||Ar(typeof window=="object"&&window)||Ar(typeof self=="object"&&self)||Ar(typeof global=="object"&&global)||Ar(typeof Jn=="object"&&Jn)||function(){return this}()||Function("return this")()});var we=b((gL,Jl)=>{"use strict";Jl.exports=function(a){try{return!!a()}catch{return!0}}});var kr=b((SL,Zl)=>{"use strict";var Lv=we();Zl.exports=!Lv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Zn=b((vL,rc)=>{"use strict";var $v=kr(),ic=Function.prototype,ec=ic.apply,tc=ic.call;rc.exports=typeof Reflect=="object"&&Reflect.apply||($v?tc.bind(ec):function(){return tc.apply(ec,arguments)})});var Ae=b((yL,nc)=>{"use strict";var ac=kr(),sc=Function.prototype,eo=sc.call,Mv=ac&&sc.bind.bind(eo,eo);nc.exports=ac?Mv:function(a){return function(){return eo.apply(a,arguments)}}});var pi=b((TL,uc)=>{"use strict";var oc=Ae(),Dv=oc({}.toString),Cv=oc("".slice);uc.exports=function(a){return Cv(Dv(a),8,-1)}});var to=b((IL,lc)=>{"use strict";var Bv=pi(),Vv=Ae();lc.exports=function(a){if(Bv(a)==="Function")return Vv(a)}});var ve=b((EL,cc)=>{"use strict";var io=typeof document=="object"&&document.all;cc.exports=typeof io>"u"&&io!==void 0?function(a){return typeof a=="function"||a===io}:function(a){return typeof a=="function"}});var Ye=b((xL,dc)=>{"use strict";var _v=we();dc.exports=!_v(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ke=b((wL,pc)=>{"use strict";var Ov=kr(),cs=Function.prototype.call;pc.exports=Ov?cs.bind(cs):function(){return cs.apply(cs,arguments)}});var ro=b(mc=>{"use strict";var hc={}.propertyIsEnumerable,fc=Object.getOwnPropertyDescriptor,Fv=fc&&!hc.call({1:2},1);mc.f=Fv?function(e){var t=fc(this,e);return!!t&&t.enumerable}:hc});var Pr=b((kL,bc)=>{"use strict";bc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Sc=b((PL,gc)=>{"use strict";var Nv=Ae(),Uv=we(),qv=pi(),ao=Object,Hv=Nv("".split);gc.exports=Uv(function(){return!ao("z").propertyIsEnumerable(0)})?function(a){return qv(a)==="String"?Hv(a,""):ao(a)}:ao});var Rr=b((RL,vc)=>{"use strict";vc.exports=function(a){return a==null}});var Xt=b((LL,yc)=>{"use strict";var jv=Rr(),Qv=TypeError;yc.exports=function(a){if(jv(a))throw new Qv("Can't call method on "+a);return a}});var hi=b(($L,Tc)=>{"use strict";var Gv=Sc(),Wv=Xt();Tc.exports=function(a){return Gv(Wv(a))}});var Ne=b((ML,Ic)=>{"use strict";var zv=ve();Ic.exports=function(a){return typeof a=="object"?a!==null:zv(a)}});var fi=b((DL,Ec)=>{"use strict";Ec.exports={}});var Vt=b((CL,wc)=>{"use strict";var so=fi(),no=Se(),Yv=ve(),xc=function(a){return Yv(a)?a:void 0};wc.exports=function(a,e){return arguments.length<2?xc(so[a])||xc(no[a]):so[a]&&so[a][e]||no[a]&&no[a][e]}});var Lr=b((BL,Ac)=>{"use strict";var Kv=Ae();Ac.exports=Kv({}.isPrototypeOf)});var mi=b((VL,Rc)=>{"use strict";var Xv=Se(),kc=Xv.navigator,Pc=kc&&kc.userAgent;Rc.exports=Pc?String(Pc):""});var uo=b((_L,Bc)=>{"use strict";var Cc=Se(),oo=mi(),Lc=Cc.process,$c=Cc.Deno,Mc=Lc&&Lc.versions||$c&&$c.version,Dc=Mc&&Mc.v8,ht,ds;Dc&&(ht=Dc.split("."),ds=ht[0]>0&&ht[0]<4?1:+(ht[0]+ht[1]));!ds&&oo&&(ht=oo.match(/Edge\/(\d+)/),(!ht||ht[1]>=74)&&(ht=oo.match(/Chrome\/(\d+)/),ht&&(ds=+ht[1])));Bc.exports=ds});var lo=b((OL,_c)=>{"use strict";var Vc=uo(),Jv=we(),Zv=Se(),ey=Zv.String;_c.exports=!!Object.getOwnPropertySymbols&&!Jv(function(){var a=Symbol("symbol detection");return!ey(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Vc&&Vc<41})});var co=b((FL,Oc)=>{"use strict";var ty=lo();Oc.exports=ty&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var po=b((NL,Fc)=>{"use strict";var iy=Vt(),ry=ve(),ay=Lr(),sy=co(),ny=Object;Fc.exports=sy?function(a){return typeof a=="symbol"}:function(a){var e=iy("Symbol");return ry(e)&&ay(e.prototype,ny(a))}});var $r=b((UL,Nc)=>{"use strict";var oy=String;Nc.exports=function(a){try{return oy(a)}catch{return"Object"}}});var wt=b((qL,Uc)=>{"use strict";var uy=ve(),ly=$r(),cy=TypeError;Uc.exports=function(a){if(uy(a))return a;throw new cy(ly(a)+" is not a function")}});var Mr=b((HL,qc)=>{"use strict";var dy=wt(),py=Rr();qc.exports=function(a,e){var t=a[e];return py(t)?void 0:dy(t)}});var jc=b((jL,Hc)=>{"use strict";var ho=Ke(),fo=ve(),mo=Ne(),hy=TypeError;Hc.exports=function(a,e){var t,i;if(e==="string"&&fo(t=a.toString)&&!mo(i=ho(t,a))||fo(t=a.valueOf)&&!mo(i=ho(t,a))||e!=="string"&&fo(t=a.toString)&&!mo(i=ho(t,a)))return i;throw new hy("Can't convert object to primitive value")}});var ft=b((QL,Qc)=>{"use strict";Qc.exports=!0});var zc=b((GL,Wc)=>{"use strict";var Gc=Se(),fy=Object.defineProperty;Wc.exports=function(a,e){try{fy(Gc,a,{value:e,configurable:!0,writable:!0})}catch{Gc[a]=e}return e}});var Dr=b((WL,Xc)=>{"use strict";var my=ft(),by=Se(),gy=zc(),Yc="__core-js_shared__",Kc=Xc.exports=by[Yc]||gy(Yc,{});(Kc.versions||(Kc.versions=[])).push({version:"3.43.0",mode:my?"pure":"global",copyright:"\xA9 2014-2025 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.43.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var bo=b((zL,Zc)=>{"use strict";var Jc=Dr();Zc.exports=function(a,e){return Jc[a]||(Jc[a]=e||{})}});var Fi=b((YL,ed)=>{"use strict";var Sy=Xt(),vy=Object;ed.exports=function(a){return vy(Sy(a))}});var mt=b((KL,td)=>{"use strict";var yy=Ae(),Ty=Fi(),Iy=yy({}.hasOwnProperty);td.exports=Object.hasOwn||function(e,t){return Iy(Ty(e),t)}});var go=b((XL,id)=>{"use strict";var Ey=Ae(),xy=0,wy=Math.random(),Ay=Ey(1.1.toString);id.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Ay(++xy+wy,36)}});var $e=b((JL,ad)=>{"use strict";var ky=Se(),Py=bo(),rd=mt(),Ry=go(),Ly=lo(),$y=co(),Ni=ky.Symbol,So=Py("wks"),My=$y?Ni.for||Ni:Ni&&Ni.withoutSetter||Ry;ad.exports=function(a){return rd(So,a)||(So[a]=Ly&&rd(Ni,a)?Ni[a]:My("Symbol."+a)),So[a]}});var ud=b((ZL,od)=>{"use strict";var Dy=Ke(),sd=Ne(),nd=po(),Cy=Mr(),By=jc(),Vy=$e(),_y=TypeError,Oy=Vy("toPrimitive");od.exports=function(a,e){if(!sd(a)||nd(a))return a;var t=Cy(a,Oy),i;if(t){if(e===void 0&&(e="default"),i=Dy(t,a,e),!sd(i)||nd(i))return i;throw new _y("Can't convert object to primitive value")}return e===void 0&&(e="number"),By(a,e)}});var vo=b((e$,ld)=>{"use strict";var Fy=ud(),Ny=po();ld.exports=function(a){var e=Fy(a,"string");return Ny(e)?e:e+""}});var ps=b((t$,dd)=>{"use strict";var Uy=Se(),cd=Ne(),yo=Uy.document,qy=cd(yo)&&cd(yo.createElement);dd.exports=function(a){return qy?yo.createElement(a):{}}});var To=b((i$,pd)=>{"use strict";var Hy=Ye(),jy=we(),Qy=ps();pd.exports=!Hy&&!jy(function(){return Object.defineProperty(Qy("div"),"a",{get:function(){return 7}}).a!==7})});var md=b(fd=>{"use strict";var Gy=Ye(),Wy=Ke(),zy=ro(),Yy=Pr(),Ky=hi(),Xy=vo(),Jy=mt(),Zy=To(),hd=Object.getOwnPropertyDescriptor;fd.f=Gy?hd:function(e,t){if(e=Ky(e),t=Xy(t),Zy)try{return hd(e,t)}catch{}if(Jy(e,t))return Yy(!Wy(zy.f,e,t),e[t])}});var Io=b((a$,bd)=>{"use strict";var eT=we(),tT=ve(),iT=/#|\.prototype\./,Cr=function(a,e){var t=aT[rT(a)];return t===nT?!0:t===sT?!1:tT(e)?eT(e):!!e},rT=Cr.normalize=function(a){return String(a).replace(iT,".").toLowerCase()},aT=Cr.data={},sT=Cr.NATIVE="N",nT=Cr.POLYFILL="P";bd.exports=Cr});var Ui=b((s$,Sd)=>{"use strict";var gd=to(),oT=wt(),uT=kr(),lT=gd(gd.bind);Sd.exports=function(a,e){return oT(a),e===void 0?a:uT?lT(a,e):function(){return a.apply(e,arguments)}}});var Eo=b((n$,vd)=>{"use strict";var cT=Ye(),dT=we();vd.exports=cT&&dT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var At=b((o$,yd)=>{"use strict";var pT=Ne(),hT=String,fT=TypeError;yd.exports=function(a){if(pT(a))return a;throw new fT(hT(a)+" is not an object")}});var bi=b(Id=>{"use strict";var mT=Ye(),bT=To(),gT=Eo(),hs=At(),Td=vo(),ST=TypeError,xo=Object.defineProperty,vT=Object.getOwnPropertyDescriptor,wo="enumerable",Ao="configurable",ko="writable";Id.f=mT?gT?function(e,t,i){if(hs(e),t=Td(t),hs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&ko in i&&!i[ko]){var r=vT(e,t);r&&r[ko]&&(e[t]=i.value,i={configurable:Ao in i?i[Ao]:r[Ao],enumerable:wo in i?i[wo]:r[wo],writable:!1})}return xo(e,t,i)}:xo:function(e,t,i){if(hs(e),t=Td(t),hs(i),bT)try{return xo(e,t,i)}catch{}if("get"in i||"set"in i)throw new ST("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var qi=b((l$,Ed)=>{"use strict";var yT=Ye(),TT=bi(),IT=Pr();Ed.exports=yT?function(a,e,t){return TT.f(a,e,IT(1,t))}:function(a,e,t){return a[e]=t,a}});var Te=b((c$,wd)=>{"use strict";var Br=Se(),ET=Zn(),xT=to(),wT=ve(),AT=md().f,kT=Io(),Hi=fi(),PT=Ui(),ji=qi(),xd=mt();Dr();var RT=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return ET(a,this,arguments)};return e.prototype=a.prototype,e};wd.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Br:r?Br[t]:Br[t]&&Br[t].prototype,u=i?Hi:Hi[t]||ji(Hi,t,{})[t],o=u.prototype,l,c,p,d,h,m,g,S,T;for(d in e)l=kT(i?d:t+(r?".":"#")+d,a.forced),c=!l&&n&&xd(n,d),m=u[d],c&&(a.dontCallGetSet?(T=AT(n,d),g=T&&T.value):g=n[d]),h=c&&g?g:e[d],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?S=PT(h,Br):a.wrap&&c?S=RT(h):s&&wT(h)?S=xT(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&ji(S,"sham",!0),ji(u,d,S),s&&(p=t+"Prototype",xd(Hi,p)||ji(Hi,p,{}),ji(Hi[p],d,h),a.real&&o&&(l||!o[d])&&ji(o,d,h)))}});var kd=b((d$,Ad)=>{"use strict";var LT=Math.ceil,$T=Math.floor;Ad.exports=Math.trunc||function(e){var t=+e;return(t>0?$T:LT)(t)}});var Vr=b((p$,Pd)=>{"use strict";var MT=kd();Pd.exports=function(a){var e=+a;return e!==e||e===0?0:MT(e)}});var Ld=b((h$,Rd)=>{"use strict";var DT=Vr(),CT=Math.max,BT=Math.min;Rd.exports=function(a,e){var t=DT(a);return t<0?CT(t+e,0):BT(t,e)}});var Po=b((f$,$d)=>{"use strict";var VT=Vr(),_T=Math.min;$d.exports=function(a){var e=VT(a);return e>0?_T(e,9007199254740991):0}});var Qi=b((m$,Md)=>{"use strict";var OT=Po();Md.exports=function(a){return OT(a.length)}});var Ro=b((b$,Cd)=>{"use strict";var FT=hi(),NT=Ld(),UT=Qi(),Dd=function(a){return function(e,t,i){var r=FT(e),s=UT(r);if(s===0)return!a&&-1;var n=NT(i,s),u;if(a&&t!==t){for(;s>n;)if(u=r[n++],u!==u)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};Cd.exports={includes:Dd(!0),indexOf:Dd(!1)}});var _r=b((g$,Bd)=>{"use strict";Bd.exports=function(){}});var Vd=b(()=>{"use strict";var qT=Te(),HT=Ro().includes,jT=we(),QT=_r(),GT=jT(function(){return!Array(1).includes()});qT({target:"Array",proto:!0,forced:GT},{includes:function(e){return HT(this,e,arguments.length>1?arguments[1]:void 0)}});QT("includes")});var Jt=b((y$,_d)=>{"use strict";var WT=Vt();_d.exports=WT});var Fd=b((T$,Od)=>{"use strict";Vd();var zT=Jt();Od.exports=zT("Array","includes")});var Ud=b((I$,Nd)=>{"use strict";var YT=Fd();Nd.exports=YT});var st=b((E$,qd)=>{"use strict";var KT=Ud();qd.exports=KT});var ms=b((C$,Qd)=>{"use strict";var JT=bo(),ZT=go(),jd=JT("keys");Qd.exports=function(a){return jd[a]||(jd[a]=ZT(a))}});var Wd=b((B$,Gd)=>{"use strict";var eI=we();Gd.exports=!eI(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var bs=b((V$,Yd)=>{"use strict";var tI=mt(),iI=ve(),rI=Fi(),aI=ms(),sI=Wd(),zd=aI("IE_PROTO"),Lo=Object,nI=Lo.prototype;Yd.exports=sI?Lo.getPrototypeOf:function(a){var e=rI(a);if(tI(e,zd))return e[zd];var t=e.constructor;return iI(t)&&e instanceof t?t.prototype:e instanceof Lo?nI:null}});var gs=b((_$,Kd)=>{"use strict";Kd.exports={}});var Zd=b((O$,Jd)=>{"use strict";var oI=Ae(),$o=mt(),uI=hi(),lI=Ro().indexOf,cI=gs(),Xd=oI([].push);Jd.exports=function(a,e){var t=uI(a),i=0,r=[],s;for(s in t)!$o(cI,s)&&$o(t,s)&&Xd(r,s);for(;e.length>i;)$o(t,s=e[i++])&&(~lI(r,s)||Xd(r,s));return r}});var Mo=b((F$,ep)=>{"use strict";ep.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Do=b((N$,tp)=>{"use strict";var dI=Zd(),pI=Mo();tp.exports=Object.keys||function(e){return dI(e,pI)}});var Co=b((U$,np)=>{"use strict";var rp=Ye(),hI=we(),ap=Ae(),fI=bs(),mI=Do(),bI=hi(),gI=ro().f,sp=ap(gI),SI=ap([].push),vI=rp&&hI(function(){var a=Object.create(null);return a[2]=2,!sp(a,2)}),ip=function(a){return function(e){for(var t=bI(e),i=mI(t),r=vI&&fI(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!rp||(r?o in t:sp(t,o)))&&SI(u,a?[o,t[o]]:t[o]);return u}};np.exports={entries:ip(!0),values:ip(!1)}});var op=b(()=>{"use strict";var yI=Te(),TI=Co().entries;yI({target:"Object",stat:!0},{entries:function(e){return TI(e)}})});var lp=b((j$,up)=>{"use strict";op();var II=fi();up.exports=II.Object.entries});var dp=b((Q$,cp)=>{"use strict";var EI=lp();cp.exports=EI});var Gi=b((G$,pp)=>{"use strict";var xI=dp();pp.exports=xI});var gi=b((W$,hp)=>{"use strict";hp.exports={}});var bp=b((z$,mp)=>{"use strict";var wI=Se(),AI=ve(),fp=wI.WeakMap;mp.exports=AI(fp)&&/native code/.test(String(fp))});var Oo=b((Y$,vp)=>{"use strict";var kI=bp(),Sp=Se(),PI=Ne(),RI=qi(),Bo=mt(),Vo=Dr(),LI=ms(),$I=gs(),gp="Object already initialized",_o=Sp.TypeError,MI=Sp.WeakMap,Ss,Or,vs,DI=function(a){return vs(a)?Or(a):Ss(a,{})},CI=function(a){return function(e){var t;if(!PI(e)||(t=Or(e)).type!==a)throw new _o("Incompatible receiver, "+a+" required");return t}};kI||Vo.state?(bt=Vo.state||(Vo.state=new MI),bt.get=bt.get,bt.has=bt.has,bt.set=bt.set,Ss=function(a,e){if(bt.has(a))throw new _o(gp);return e.facade=a,bt.set(a,e),e},Or=function(a){return bt.get(a)||{}},vs=function(a){return bt.has(a)}):(Si=LI("state"),$I[Si]=!0,Ss=function(a,e){if(Bo(a,Si))throw new _o(gp);return e.facade=a,RI(a,Si,e),e},Or=function(a){return Bo(a,Si)?a[Si]:{}},vs=function(a){return Bo(a,Si)});var bt,Si;vp.exports={set:Ss,get:Or,has:vs,enforce:DI,getterFor:CI}});var Uo=b((K$,Tp)=>{"use strict";var Fo=Ye(),BI=mt(),yp=Function.prototype,VI=Fo&&Object.getOwnPropertyDescriptor,No=BI(yp,"name"),_I=No&&function(){}.name==="something",OI=No&&(!Fo||Fo&&VI(yp,"name").configurable);Tp.exports={EXISTS:No,PROPER:_I,CONFIGURABLE:OI}});var Ep=b(Ip=>{"use strict";var FI=Ye(),NI=Eo(),UI=bi(),qI=At(),HI=hi(),jI=Do();Ip.f=FI&&!NI?Object.defineProperties:function(e,t){qI(e);for(var i=HI(t),r=jI(t),s=r.length,n=0,u;s>n;)UI.f(e,u=r[n++],i[u]);return e}});var qo=b((J$,xp)=>{"use strict";var QI=Vt();xp.exports=QI("document","documentElement")});var Go=b((Z$,$p)=>{"use strict";var GI=At(),WI=Ep(),wp=Mo(),zI=gs(),YI=qo(),KI=ps(),XI=ms(),Ap=">",kp="<",jo="prototype",Qo="script",Rp=XI("IE_PROTO"),Ho=function(){},Lp=function(a){return kp+Qo+Ap+a+kp+"/"+Qo+Ap},Pp=function(a){a.write(Lp("")),a.close();var e=a.parentWindow.Object;return a=null,e},JI=function(){var a=KI("iframe"),e="java"+Qo+":",t;return a.style.display="none",YI.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Lp("document.F=Object")),t.close(),t.F},ys,Ts=function(){try{ys=new ActiveXObject("htmlfile")}catch{}Ts=typeof document<"u"?document.domain&&ys?Pp(ys):JI():Pp(ys);for(var a=wp.length;a--;)delete Ts[jo][wp[a]];return Ts()};zI[Rp]=!0;$p.exports=Object.create||function(e,t){var i;return e!==null?(Ho[jo]=GI(e),i=new Ho,Ho[jo]=null,i[Rp]=e):i=Ts(),t===void 0?i:WI.f(i,t)}});var Wi=b((eM,Mp)=>{"use strict";var ZI=qi();Mp.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:ZI(a,e,t),a}});var Ko=b((tM,Bp)=>{"use strict";var eE=we(),tE=ve(),iE=Ne(),rE=Go(),Dp=bs(),aE=Wi(),sE=$e(),nE=ft(),Yo=sE("iterator"),Cp=!1,_t,Wo,zo;[].keys&&(zo=[].keys(),"next"in zo?(Wo=Dp(Dp(zo)),Wo!==Object.prototype&&(_t=Wo)):Cp=!0);var oE=!iE(_t)||eE(function(){var a={};return _t[Yo].call(a)!==a});oE?_t={}:nE&&(_t=rE(_t));tE(_t[Yo])||aE(_t,Yo,function(){return this});Bp.exports={IteratorPrototype:_t,BUGGY_SAFARI_ITERATORS:Cp}});var Is=b((iM,_p)=>{"use strict";var uE=$e(),lE=uE("toStringTag"),Vp={};Vp[lE]="z";_p.exports=String(Vp)==="[object z]"});var Fr=b((rM,Op)=>{"use strict";var cE=Is(),dE=ve(),Es=pi(),pE=$e(),hE=pE("toStringTag"),fE=Object,mE=Es(function(){return arguments}())==="Arguments",bE=function(a,e){try{return a[e]}catch{}};Op.exports=cE?Es:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=bE(e=fE(a),hE))=="string"?t:mE?Es(e):(i=Es(e))==="Object"&&dE(e.callee)?"Arguments":i}});var Np=b((aM,Fp)=>{"use strict";var gE=Is(),SE=Fr();Fp.exports=gE?{}.toString:function(){return"[object "+SE(this)+"]"}});var Nr=b((sM,qp)=>{"use strict";var vE=Is(),yE=bi().f,TE=qi(),IE=mt(),EE=Np(),xE=$e(),Up=xE("toStringTag");qp.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(IE(r,Up)||yE(r,Up,{configurable:!0,value:e}),i&&!vE&&TE(r,"toString",EE))}});var jp=b((nM,Hp)=>{"use strict";var wE=Ko().IteratorPrototype,AE=Go(),kE=Pr(),PE=Nr(),RE=gi(),LE=function(){return this};Hp.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=AE(wE,{next:kE(+!i,t)}),PE(a,r,!1,!0),RE[r]=LE,a}});var Gp=b((oM,Qp)=>{"use strict";var $E=Ae(),ME=wt();Qp.exports=function(a,e,t){try{return $E(ME(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var zp=b((uM,Wp)=>{"use strict";var DE=Ne();Wp.exports=function(a){return DE(a)||a===null}});var Kp=b((lM,Yp)=>{"use strict";var CE=zp(),BE=String,VE=TypeError;Yp.exports=function(a){if(CE(a))return a;throw new VE("Can't set "+BE(a)+" as a prototype")}});var Xo=b((cM,Xp)=>{"use strict";var _E=Gp(),OE=Ne(),FE=Xt(),NE=Kp();Xp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=_E(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return FE(r),NE(s),OE(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var uh=b((dM,oh)=>{"use strict";var UE=Te(),qE=Ke(),xs=ft(),sh=Uo(),HE=ve(),jE=jp(),Jp=bs(),Zp=Xo(),QE=Nr(),GE=qi(),Jo=Wi(),WE=$e(),eh=gi(),nh=Ko(),zE=sh.PROPER,YE=sh.CONFIGURABLE,th=nh.IteratorPrototype,ws=nh.BUGGY_SAFARI_ITERATORS,Ur=WE("iterator"),ih="keys",qr="values",rh="entries",ah=function(){return this};oh.exports=function(a,e,t,i,r,s,n){jE(t,e,i);var u=function(T){if(T===r&&d)return d;if(!ws&&T&&T in c)return c[T];switch(T){case ih:return function(){return new t(this,T)};case qr:return function(){return new t(this,T)};case rh:return function(){return new t(this,T)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,c=a.prototype,p=c[Ur]||c["@@iterator"]||r&&c[r],d=!ws&&p||u(r),h=e==="Array"&&c.entries||p,m,g,S;if(h&&(m=Jp(h.call(new a)),m!==Object.prototype&&m.next&&(!xs&&Jp(m)!==th&&(Zp?Zp(m,th):HE(m[Ur])||Jo(m,Ur,ah)),QE(m,o,!0,!0),xs&&(eh[o]=ah))),zE&&r===qr&&p&&p.name!==qr&&(!xs&&YE?GE(c,"name",qr):(l=!0,d=function(){return qE(p,this)})),r)if(g={values:u(qr),keys:s?d:u(ih),entries:u(rh)},n)for(S in g)(ws||l||!(S in c))&&Jo(c,S,g[S]);else UE({target:e,proto:!0,forced:ws||l},g);return(!xs||n)&&c[Ur]!==d&&Jo(c,Ur,d,{name:r}),eh[e]=d,g}});var ch=b((pM,lh)=>{"use strict";lh.exports=function(a,e){return{value:a,done:e}}});var eu=b((hM,mh)=>{"use strict";var KE=hi(),Zo=_r(),dh=gi(),hh=Oo(),XE=bi().f,JE=uh(),As=ch(),ZE=ft(),ex=Ye(),fh="Array Iterator",tx=hh.set,ix=hh.getterFor(fh);mh.exports=JE(Array,"Array",function(a,e){tx(this,{type:fh,target:KE(a),index:0,kind:e})},function(){var a=ix(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,As(void 0,!0);switch(a.kind){case"keys":return As(t,!1);case"values":return As(e[t],!1)}return As([t,e[t]],!1)},"values");var ph=dh.Arguments=dh.Array;Zo("keys");Zo("values");Zo("entries");if(!ZE&&ex&&ph.name!=="values")try{XE(ph,"name",{value:"values"})}catch{}});var gh=b((fM,bh)=>{"use strict";var rx=$e(),ax=gi(),sx=rx("iterator"),nx=Array.prototype;bh.exports=function(a){return a!==void 0&&(ax.Array===a||nx[sx]===a)}});var tu=b((mM,vh)=>{"use strict";var ox=Fr(),Sh=Mr(),ux=Rr(),lx=gi(),cx=$e(),dx=cx("iterator");vh.exports=function(a){if(!ux(a))return Sh(a,dx)||Sh(a,"@@iterator")||lx[ox(a)]}});var Th=b((bM,yh)=>{"use strict";var px=Ke(),hx=wt(),fx=At(),mx=$r(),bx=tu(),gx=TypeError;yh.exports=function(a,e){var t=arguments.length<2?bx(a):e;if(hx(t))return fx(px(t,a));throw new gx(mx(a)+" is not iterable")}});var xh=b((gM,Eh)=>{"use strict";var Sx=Ke(),Ih=At(),vx=Mr();Eh.exports=function(a,e,t){var i,r;Ih(a);try{if(i=vx(a,"return"),!i){if(e==="throw")throw t;return t}i=Sx(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Ih(i),t}});var Ps=b((SM,Ph)=>{"use strict";var yx=Ui(),Tx=Ke(),Ix=At(),Ex=$r(),xx=gh(),wx=Qi(),wh=Lr(),Ax=Th(),kx=tu(),Ah=xh(),Px=TypeError,ks=function(a,e){this.stopped=a,this.result=e},kh=ks.prototype;Ph.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),u=!!(t&&t.INTERRUPTED),o=yx(e,i),l,c,p,d,h,m,g,S=function(k){return l&&Ah(l,"normal"),new ks(!0,k)},T=function(k){return r?(Ix(k),u?o(k[0],k[1],S):o(k[0],k[1])):u?o(k,S):o(k)};if(s)l=a.iterator;else if(n)l=a;else{if(c=kx(a),!c)throw new Px(Ex(a)+" is not iterable");if(xx(c)){for(p=0,d=wx(a);d>p;p++)if(h=T(a[p]),h&&wh(kh,h))return h;return new ks(!1)}l=Ax(a,c)}for(m=s?a.next:l.next;!(g=Tx(m,l)).done;){try{h=T(g.value)}catch(k){Ah(l,"throw",k)}if(typeof h=="object"&&h&&wh(kh,h))return h}return new ks(!1)}});var Lh=b((vM,Rh)=>{"use strict";var Rx=Ye(),Lx=bi(),$x=Pr();Rh.exports=function(a,e,t){Rx?Lx.f(a,e,$x(0,t)):a[e]=t}});var $h=b(()=>{"use strict";var Mx=Te(),Dx=Ps(),Cx=Lh();Mx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Dx(e,function(i,r){Cx(t,i,r)},{AS_ENTRIES:!0}),t}})});var Dh=b((IM,Mh)=>{"use strict";eu();$h();var Bx=fi();Mh.exports=Bx.Object.fromEntries});var Bh=b((EM,Ch)=>{"use strict";Ch.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 _h=b(()=>{"use strict";eu();var Vx=Bh(),_x=Se(),Ox=Nr(),Vh=gi();for(Rs in Vx)Ox(_x[Rs],Rs),Vh[Rs]=Vh.Array;var Rs});var Fh=b((AM,Oh)=>{"use strict";var Fx=Dh();_h();Oh.exports=Fx});var iu=b((kM,Nh)=>{"use strict";var Nx=Fh();Nh.exports=Nx});var Uh=b(()=>{"use strict"});var ru=b((LM,qh)=>{"use strict";var Hr=Se(),Ux=mi(),qx=pi(),Ls=function(a){return Ux.slice(0,a.length)===a};qh.exports=function(){return Ls("Bun/")?"BUN":Ls("Cloudflare-Workers")?"CLOUDFLARE":Ls("Deno/")?"DENO":Ls("Node.js/")?"NODE":Hr.Bun&&typeof Bun.version=="string"?"BUN":Hr.Deno&&typeof Deno.version=="object"?"DENO":qx(Hr.process)==="process"?"NODE":Hr.window&&Hr.document?"BROWSER":"REST"}()});var $s=b(($M,Hh)=>{"use strict";var Hx=ru();Hh.exports=Hx==="NODE"});var Qh=b((MM,jh)=>{"use strict";var jx=bi();jh.exports=function(a,e,t){return jx.f(a,e,t)}});var zh=b((DM,Wh)=>{"use strict";var Qx=Vt(),Gx=Qh(),Wx=$e(),zx=Ye(),Gh=Wx("species");Wh.exports=function(a){var e=Qx(a);zx&&e&&!e[Gh]&&Gx(e,Gh,{configurable:!0,get:function(){return this}})}});var Kh=b((CM,Yh)=>{"use strict";var Yx=Lr(),Kx=TypeError;Yh.exports=function(a,e){if(Yx(e,a))return a;throw new Kx("Incorrect invocation")}});var su=b((BM,Xh)=>{"use strict";var Xx=Ae(),Jx=ve(),au=Dr(),Zx=Xx(Function.toString);Jx(au.inspectSource)||(au.inspectSource=function(a){return Zx(a)});Xh.exports=au.inspectSource});var ou=b((VM,rf)=>{"use strict";var ew=Ae(),tw=we(),Jh=ve(),iw=Fr(),rw=Vt(),aw=su(),Zh=function(){},ef=rw("Reflect","construct"),nu=/^\s*(?:class|function)\b/,sw=ew(nu.exec),nw=!nu.test(Zh),jr=function(e){if(!Jh(e))return!1;try{return ef(Zh,[],e),!0}catch{return!1}},tf=function(e){if(!Jh(e))return!1;switch(iw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return nw||!!sw(nu,aw(e))}catch{return!0}};tf.sham=!0;rf.exports=!ef||tw(function(){var a;return jr(jr.call)||!jr(Object)||!jr(function(){a=!0})||a})?tf:jr});var sf=b((_M,af)=>{"use strict";var ow=ou(),uw=$r(),lw=TypeError;af.exports=function(a){if(ow(a))return a;throw new lw(uw(a)+" is not a constructor")}});var uu=b((OM,of)=>{"use strict";var nf=At(),cw=sf(),dw=Rr(),pw=$e(),hw=pw("species");of.exports=function(a,e){var t=nf(a).constructor,i;return t===void 0||dw(i=nf(t)[hw])?e:cw(i)}});var lf=b((FM,uf)=>{"use strict";var fw=Ae();uf.exports=fw([].slice)});var df=b((NM,cf)=>{"use strict";var mw=TypeError;cf.exports=function(a,e){if(a<e)throw new mw("Not enough arguments");return a}});var lu=b((UM,pf)=>{"use strict";var bw=mi();pf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(bw)});var Su=b((qM,Tf)=>{"use strict";var Xe=Se(),gw=Zn(),Sw=Ui(),hf=ve(),vw=mt(),yf=we(),ff=qo(),yw=lf(),mf=ps(),Tw=df(),Iw=lu(),Ew=$s(),mu=Xe.setImmediate,bu=Xe.clearImmediate,xw=Xe.process,cu=Xe.Dispatch,ww=Xe.Function,bf=Xe.MessageChannel,Aw=Xe.String,du=0,Qr={},gf="onreadystatechange",Gr,vi,pu,hu;yf(function(){Gr=Xe.location});var gu=function(a){if(vw(Qr,a)){var e=Qr[a];delete Qr[a],e()}},fu=function(a){return function(){gu(a)}},Sf=function(a){gu(a.data)},vf=function(a){Xe.postMessage(Aw(a),Gr.protocol+"//"+Gr.host)};(!mu||!bu)&&(mu=function(e){Tw(arguments.length,1);var t=hf(e)?e:ww(e),i=yw(arguments,1);return Qr[++du]=function(){gw(t,void 0,i)},vi(du),du},bu=function(e){delete Qr[e]},Ew?vi=function(a){xw.nextTick(fu(a))}:cu&&cu.now?vi=function(a){cu.now(fu(a))}:bf&&!Iw?(pu=new bf,hu=pu.port2,pu.port1.onmessage=Sf,vi=Sw(hu.postMessage,hu)):Xe.addEventListener&&hf(Xe.postMessage)&&!Xe.importScripts&&Gr&&Gr.protocol!=="file:"&&!yf(vf)?(vi=vf,Xe.addEventListener("message",Sf,!1)):gf in mf("script")?vi=function(a){ff.appendChild(mf("script"))[gf]=function(){ff.removeChild(this),gu(a)}}:vi=function(a){setTimeout(fu(a),0)});Tf.exports={set:mu,clear:bu}});var xf=b((HM,Ef)=>{"use strict";var If=Se(),kw=Ye(),Pw=Object.getOwnPropertyDescriptor;Ef.exports=function(a){if(!kw)return If[a];var e=Pw(If,a);return e&&e.value}});var vu=b((jM,Af)=>{"use strict";var wf=function(){this.head=null,this.tail=null};wf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};Af.exports=wf});var Pf=b((QM,kf)=>{"use strict";var Rw=mi();kf.exports=/ipad|iphone|ipod/i.test(Rw)&&typeof Pebble<"u"});var Lf=b((GM,Rf)=>{"use strict";var Lw=mi();Rf.exports=/web0s(?!.*chrome)/i.test(Lw)});var _f=b((WM,Vf)=>{"use strict";var Yi=Se(),$w=xf(),$f=Ui(),yu=Su().set,Mw=vu(),Dw=lu(),Cw=Pf(),Bw=Lf(),Tu=$s(),Mf=Yi.MutationObserver||Yi.WebKitMutationObserver,Df=Yi.document,Cf=Yi.process,Ms=Yi.Promise,xu=$w("queueMicrotask"),zi,Iu,Eu,Ds,Bf;xu||(Wr=new Mw,zr=function(){var a,e;for(Tu&&(a=Cf.domain)&&a.exit();e=Wr.get();)try{e()}catch(t){throw Wr.head&&zi(),t}a&&a.enter()},!Dw&&!Tu&&!Bw&&Mf&&Df?(Iu=!0,Eu=Df.createTextNode(""),new Mf(zr).observe(Eu,{characterData:!0}),zi=function(){Eu.data=Iu=!Iu}):!Cw&&Ms&&Ms.resolve?(Ds=Ms.resolve(void 0),Ds.constructor=Ms,Bf=$f(Ds.then,Ds),zi=function(){Bf(zr)}):Tu?zi=function(){Cf.nextTick(zr)}:(yu=$f(yu,Yi),zi=function(){yu(zr)}),xu=function(a){Wr.head||zi(),Wr.add(a)});var Wr,zr;Vf.exports=xu});var Ff=b((zM,Of)=>{"use strict";Of.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var Cs=b((YM,Nf)=>{"use strict";Nf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var yi=b((KM,Uf)=>{"use strict";var Vw=Se();Uf.exports=Vw.Promise});var Ki=b((XM,Qf)=>{"use strict";var _w=Se(),Yr=yi(),Ow=ve(),Fw=Io(),Nw=su(),Uw=$e(),qf=ru(),qw=ft(),wu=uo(),Hf=Yr&&Yr.prototype,Hw=Uw("species"),Au=!1,jf=Ow(_w.PromiseRejectionEvent),jw=Fw("Promise",function(){var a=Nw(Yr),e=a!==String(Yr);if(!e&&wu===66||qw&&!(Hf.catch&&Hf.finally))return!0;if(!wu||wu<51||!/native code/.test(a)){var t=new Yr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[Hw]=i,Au=t.then(function(){})instanceof i,!Au)return!0}return!e&&(qf==="BROWSER"||qf==="DENO")&&!jf});Qf.exports={CONSTRUCTOR:jw,REJECTION_EVENT:jf,SUBCLASSING:Au}});var Xi=b((JM,Wf)=>{"use strict";var Gf=wt(),Qw=TypeError,Gw=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new Qw("Bad Promise constructor");e=i,t=r}),this.resolve=Gf(e),this.reject=Gf(t)};Wf.exports.f=function(a){return new Gw(a)}});var hm=b(()=>{"use strict";var Ww=Te(),zw=ft(),Os=$s(),Zt=Se(),Yw=fi(),tr=Ke(),zf=Wi(),Yf=Xo(),Kw=Nr(),Xw=zh(),Jw=wt(),_s=ve(),Zw=Ne(),eA=Kh(),tA=uu(),em=Su().set,$u=_f(),iA=Ff(),rA=Cs(),aA=vu(),tm=Oo(),Fs=yi(),Mu=Ki(),im=Xi(),Ns="Promise",rm=Mu.CONSTRUCTOR,sA=Mu.REJECTION_EVENT,nA=Mu.SUBCLASSING,ku=tm.getterFor(Ns),oA=tm.set,Ji=Fs&&Fs.prototype,Ti=Fs,Bs=Ji,am=Zt.TypeError,Pu=Zt.document,Du=Zt.process,Ru=im.f,uA=Ru,lA=!!(Pu&&Pu.createEvent&&Zt.dispatchEvent),sm="unhandledrejection",cA="rejectionhandled",Kf=0,nm=1,dA=2,Cu=1,om=2,Vs,Xf,um,Jf,lm=function(a){var e;return Zw(a)&&_s(e=a.then)?e:!1},cm=function(a,e){var t=e.value,i=e.state===nm,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,c;try{r?(i||(e.rejection===om&&hA(e),e.rejection=Cu),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),c=!0)),o===a.promise?n(new am("Promise-chain cycle")):(l=lm(o))?tr(l,o,s,n):s(o)):n(t)}catch(p){u&&!c&&u.exit(),n(p)}},dm=function(a,e){a.notified||(a.notified=!0,$u(function(){for(var t=a.reactions,i;i=t.get();)cm(i,a);a.notified=!1,e&&!a.rejection&&pA(a)}))},pm=function(a,e,t){var i,r;lA?(i=Pu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Zt.dispatchEvent(i)):i={promise:e,reason:t},!sA&&(r=Zt["on"+a])?r(i):a===sm&&iA("Unhandled promise rejection",t)},pA=function(a){tr(em,Zt,function(){var e=a.facade,t=a.value,i=Zf(a),r;if(i&&(r=rA(function(){Os?Du.emit("unhandledRejection",t,e):pm(sm,e,t)}),a.rejection=Os||Zf(a)?om:Cu,r.error))throw r.value})},Zf=function(a){return a.rejection!==Cu&&!a.parent},hA=function(a){tr(em,Zt,function(){var e=a.facade;Os?Du.emit("rejectionHandled",e):pm(cA,e,a.value)})},Zi=function(a,e,t){return function(i){a(e,i,t)}},er=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=dA,dm(a,!0))},Lu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new am("Promise can't be resolved itself");var i=lm(e);i?$u(function(){var r={done:!1};try{tr(i,e,Zi(Lu,r,a),Zi(er,r,a))}catch(s){er(r,s,a)}}):(a.value=e,a.state=nm,dm(a,!1))}catch(r){er({done:!1},r,a)}}};if(rm&&(Ti=function(e){eA(this,Bs),Jw(e),tr(Vs,this);var t=ku(this);try{e(Zi(Lu,t),Zi(er,t))}catch(i){er(t,i)}},Bs=Ti.prototype,Vs=function(e){oA(this,{type:Ns,done:!1,notified:!1,parent:!1,reactions:new aA,rejection:!1,state:Kf,value:null})},Vs.prototype=zf(Bs,"then",function(e,t){var i=ku(this),r=Ru(tA(this,Ti));return i.parent=!0,r.ok=_s(e)?e:!0,r.fail=_s(t)&&t,r.domain=Os?Du.domain:void 0,i.state===Kf?i.reactions.add(r):$u(function(){cm(r,i)}),r.promise}),Xf=function(){var a=new Vs,e=ku(a);this.promise=a,this.resolve=Zi(Lu,e),this.reject=Zi(er,e)},im.f=Ru=function(a){return a===Ti||a===um?new Xf(a):uA(a)},!zw&&_s(Fs)&&Ji!==Object.prototype)){Jf=Ji.then,nA||zf(Ji,"then",function(e,t){var i=this;return new Ti(function(r,s){tr(Jf,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Ji.constructor}catch{}Yf&&Yf(Ji,Bs)}Ww({global:!0,constructor:!0,wrap:!0,forced:rm},{Promise:Ti});um=Yw.Promise;Kw(Ti,Ns,!1,!0);Xw(Ns)});var Sm=b((tD,gm)=>{"use strict";var fA=$e(),mm=fA("iterator"),bm=!1;try{fm=0,Bu={next:function(){return{done:!!fm++}},return:function(){bm=!0}},Bu[mm]=function(){return this},Array.from(Bu,function(){throw 2})}catch{}var fm,Bu;gm.exports=function(a,e){try{if(!e&&!bm)return!1}catch{return!1}var t=!1;try{var i={};i[mm]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Vu=b((iD,vm)=>{"use strict";var mA=yi(),bA=Sm(),gA=Ki().CONSTRUCTOR;vm.exports=gA||!bA(function(a){mA.all(a).then(void 0,function(){})})});var ym=b(()=>{"use strict";var SA=Te(),vA=Ke(),yA=wt(),TA=Xi(),IA=Cs(),EA=Ps(),xA=Vu();SA({target:"Promise",stat:!0,forced:xA},{all:function(e){var t=this,i=TA.f(t),r=i.resolve,s=i.reject,n=IA(function(){var u=yA(t.resolve),o=[],l=0,c=1;EA(e,function(p){var d=l++,h=!1;c++,vA(u,t,p).then(function(m){h||(h=!0,o[d]=m,--c||r(o))},s)}),--c||r(o)});return n.error&&s(n.value),i.promise}})});var Im=b(()=>{"use strict";var wA=Te(),AA=ft(),kA=Ki().CONSTRUCTOR,Ou=yi(),PA=Vt(),RA=ve(),LA=Wi(),Tm=Ou&&Ou.prototype;wA({target:"Promise",proto:!0,forced:kA,real:!0},{catch:function(a){return this.then(void 0,a)}});!AA&&RA(Ou)&&(_u=PA("Promise").prototype.catch,Tm.catch!==_u&&LA(Tm,"catch",_u,{unsafe:!0}));var _u});var Em=b(()=>{"use strict";var $A=Te(),MA=Ke(),DA=wt(),CA=Xi(),BA=Cs(),VA=Ps(),_A=Vu();$A({target:"Promise",stat:!0,forced:_A},{race:function(e){var t=this,i=CA.f(t),r=i.reject,s=BA(function(){var n=DA(t.resolve);VA(e,function(u){MA(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var xm=b(()=>{"use strict";var OA=Te(),FA=Xi(),NA=Ki().CONSTRUCTOR;OA({target:"Promise",stat:!0,forced:NA},{reject:function(e){var t=FA.f(this),i=t.reject;return i(e),t.promise}})});var Fu=b((dD,wm)=>{"use strict";var UA=At(),qA=Ne(),HA=Xi();wm.exports=function(a,e){if(UA(a),qA(e)&&e.constructor===a)return e;var t=HA.f(a),i=t.resolve;return i(e),t.promise}});var Pm=b(()=>{"use strict";var jA=Te(),QA=Vt(),Am=ft(),GA=yi(),km=Ki().CONSTRUCTOR,WA=Fu(),zA=QA("Promise"),YA=Am&&!km;jA({target:"Promise",stat:!0,forced:Am||km},{resolve:function(e){return WA(YA&&this===zA?GA:this,e)}})});var Rm=b(()=>{"use strict";hm();ym();Im();Em();xm();Pm()});var Dm=b(()=>{"use strict";var KA=Te(),XA=ft(),Us=yi(),JA=we(),$m=Vt(),Mm=ve(),ZA=uu(),Lm=Fu(),ek=Wi(),Uu=Us&&Us.prototype,tk=!!Us&&JA(function(){Uu.finally.call({then:function(){}},function(){})});KA({target:"Promise",proto:!0,real:!0,forced:tk},{finally:function(a){var e=ZA(this,$m("Promise")),t=Mm(a);return this.then(t?function(i){return Lm(e,a()).then(function(){return i})}:a,t?function(i){return Lm(e,a()).then(function(){throw i})}:a)}});!XA&&Mm(Us)&&(Nu=$m("Promise").prototype.finally,Uu.finally!==Nu&&ek(Uu,"finally",Nu,{unsafe:!0}));var Nu});var Bm=b((SD,Cm)=>{"use strict";Uh();Rm();Dm();var ik=Jt();Cm.exports=ik("Promise","finally")});var _m=b((vD,Vm)=>{"use strict";var rk=Bm();Vm.exports=rk});var qs=b((yD,Om)=>{"use strict";var ak=_m();Om.exports=ak});var Xm=b(()=>{"use strict";var mk=Te(),bk=Co().values;mk({target:"Object",stat:!0},{values:function(e){return bk(e)}})});var Zm=b((LC,Jm)=>{"use strict";Xm();var gk=fi();Jm.exports=gk.Object.values});var tb=b(($C,eb)=>{"use strict";var Sk=Zm();eb.exports=Sk});var ar=b((MC,ib)=>{"use strict";var vk=tb();ib.exports=vk});var nb=b(()=>{"use strict";var Ek=Te(),xk=Fi(),wk=Qi(),Ak=Vr(),kk=_r();Ek({target:"Array",proto:!0},{at:function(e){var t=xk(this),i=wk(t),r=Ak(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});kk("at")});var ub=b((aB,ob)=>{"use strict";nb();var Pk=Jt();ob.exports=Pk("Array","at")});var cb=b((sB,lb)=>{"use strict";var Rk=ub();lb.exports=Rk});var gt=b((nB,db)=>{"use strict";var Lk=cb();db.exports=Lk});var ll=b((N0,Bb)=>{"use strict";var Uk=pi();Bb.exports=Array.isArray||function(e){return Uk(e)==="Array"}});var _b=b((U0,Vb)=>{"use strict";var qk=TypeError,Hk=9007199254740991;Vb.exports=function(a){if(a>Hk)throw qk("Maximum allowed index exceeded");return a}});var Nb=b((q0,Fb)=>{"use strict";var jk=ll(),Qk=Qi(),Gk=_b(),Wk=Ui(),Ob=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,c=n?Wk(n,u):!1,p,d;l<i;)l in t&&(p=c?c(t[l],l,e):t[l],s>0&&jk(p)?(d=Qk(p),o=Ob(a,e,p,d,o,s-1)-1):(Gk(o+1),a[o]=p),o++),l++;return o};Fb.exports=Ob});var jb=b((H0,Hb)=>{"use strict";var Ub=ll(),zk=ou(),Yk=Ne(),Kk=$e(),Xk=Kk("species"),qb=Array;Hb.exports=function(a){var e;return Ub(a)&&(e=a.constructor,zk(e)&&(e===qb||Ub(e.prototype))?e=void 0:Yk(e)&&(e=e[Xk],e===null&&(e=void 0))),e===void 0?qb:e}});var Gb=b((j0,Qb)=>{"use strict";var Jk=jb();Qb.exports=function(a,e){return new(Jk(a))(e===0?0:e)}});var Wb=b(()=>{"use strict";var Zk=Te(),eP=Nb(),tP=wt(),iP=Fi(),rP=Qi(),aP=Gb();Zk({target:"Array",proto:!0},{flatMap:function(e){var t=iP(this),i=rP(t),r;return tP(e),r=aP(t,0),r.length=eP(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var zb=b(()=>{"use strict";var sP=_r();sP("flatMap")});var Kb=b((Y0,Yb)=>{"use strict";Wb();zb();var nP=Jt();Yb.exports=nP("Array","flatMap")});var Jb=b((K0,Xb)=>{"use strict";var oP=Kb();Xb.exports=oP});var oa=b((X0,Zb)=>{"use strict";var uP=Jb();Zb.exports=uP});var ua=b((J0,eg)=>{"use strict";var lP=Fr(),cP=String;eg.exports=function(a){if(lP(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return cP(a)}});var cl=b((Z0,tg)=>{"use strict";tg.exports=`
|
|
7
|
+
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var ag=b((eV,rg)=>{"use strict";var dP=Ae(),pP=Xt(),hP=ua(),pl=cl(),ig=dP("".replace),fP=RegExp("^["+pl+"]+"),mP=RegExp("(^|[^"+pl+"])["+pl+"]+$"),dl=function(a){return function(e){var t=hP(pP(e));return a&1&&(t=ig(t,fP,"")),a&2&&(t=ig(t,mP,"$1")),t}};rg.exports={start:dl(1),end:dl(2),trim:dl(3)}});var ug=b((tV,og)=>{"use strict";var bP=Uo().PROPER,gP=we(),sg=cl(),ng="\u200B\x85\u180E";og.exports=function(a){return gP(function(){return!!sg[a]()||ng[a]()!==ng||bP&&sg[a].name!==a})}});var hl=b((iV,lg)=>{"use strict";var SP=ag().start,vP=ug();lg.exports=vP("trimStart")?function(){return SP(this)}:"".trimStart});var dg=b(()=>{"use strict";var yP=Te(),cg=hl();yP({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==cg},{trimLeft:cg})});var hg=b(()=>{"use strict";dg();var TP=Te(),pg=hl();TP({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==pg},{trimStart:pg})});var mg=b((oV,fg)=>{"use strict";hg();var IP=Jt();fg.exports=IP("String","trimLeft")});var gg=b((uV,bg)=>{"use strict";var EP=mg();bg.exports=EP});var vg=b((lV,Sg)=>{"use strict";var xP=gg();Sg.exports=xP});var Cg=b(()=>{"use strict"});var Bg=b(()=>{"use strict"});var _g=b((jO,Vg)=>{"use strict";var jP=Ne(),QP=pi(),GP=$e(),WP=GP("match");Vg.exports=function(a){var e;return jP(a)&&((e=a[WP])!==void 0?!!e:QP(a)==="RegExp")}});var Ng=b((QO,Fg)=>{"use strict";var zP=Se(),YP=we(),Og=zP.RegExp,KP=!YP(function(){var a=!0;try{Og(".","d")}catch{a=!1}var e={},t="",i=a?"dgimsy":"gimsy",r=function(o,l){Object.defineProperty(e,o,{get:function(){return t+=l,!0}})},s={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};a&&(s.hasIndices="d");for(var n in s)r(n,s[n]);var u=Object.getOwnPropertyDescriptor(Og.prototype,"flags").get.call(e);return u!==i||t!==i});Fg.exports={correct:KP}});var qg=b((GO,Ug)=>{"use strict";var XP=At();Ug.exports=function(){var a=XP(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var Qg=b((WO,jg)=>{"use strict";var JP=Ke(),ZP=mt(),eR=Lr(),Hg=Ng(),tR=qg(),iR=RegExp.prototype;jg.exports=Hg.correct?function(a){return a.flags}:function(a){return!Hg.correct&&eR(iR,a)&&!ZP(a,"flags")?JP(tR,a):a.flags}});var Wg=b((zO,Gg)=>{"use strict";var gl=Ae(),rR=Fi(),aR=Math.floor,ml=gl("".charAt),sR=gl("".replace),bl=gl("".slice),nR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,oR=/\$([$&'`]|\d{1,2})/g;Gg.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=oR;return r!==void 0&&(r=rR(r),o=nR),sR(s,o,function(l,c){var p;switch(ml(c,0)){case"$":return"$";case"&":return a;case"`":return bl(e,0,t);case"'":return bl(e,n);case"<":p=r[bl(c,1,-1)];break;default:var d=+c;if(d===0)return l;if(d>u){var h=aR(d/10);return h===0?l:h<=u?i[h-1]===void 0?ml(c,1):i[h-1]+ml(c,1):l}p=i[d-1]}return p===void 0?"":p})}});var Kg=b(()=>{"use strict";var uR=Te(),lR=Ke(),vl=Ae(),zg=Xt(),cR=ve(),dR=Ne(),pR=_g(),fr=ua(),hR=Mr(),fR=Qg(),mR=Wg(),bR=$e(),gR=ft(),SR=bR("replace"),vR=TypeError,Sl=vl("".indexOf),yR=vl("".replace),Yg=vl("".slice),TR=Math.max;uR({target:"String",proto:!0},{replaceAll:function(e,t){var i=zg(this),r,s,n,u,o,l,c,p,d,h,m=0,g="";if(dR(e)){if(r=pR(e),r&&(s=fr(zg(fR(e))),!~Sl(s,"g")))throw new vR("`.replaceAll` does not allow non-global regexes");if(n=hR(e,SR),n)return lR(n,e,i,t);if(gR&&r)return yR(fr(i),e,t)}for(u=fr(i),o=fr(e),l=cR(t),l||(t=fr(t)),c=o.length,p=TR(1,c),d=Sl(u,o);d!==-1;)h=l?fr(t(o,d,u)):mR(o,u,d,[],void 0,t),g+=Yg(u,m,d)+h,m=d+c,d=d+p>u.length?-1:Sl(u,o,d+p);return m<u.length&&(g+=Yg(u,m)),g}})});var Jg=b((XO,Xg)=>{"use strict";Cg();Bg();Kg();var IR=Jt();Xg.exports=IR("String","replaceAll")});var eS=b((JO,Zg)=>{"use strict";var ER=Jg();Zg.exports=ER});var iS=b((ZO,tS)=>{"use strict";var xR=eS();tS.exports=xR});var aS=b((eF,rS)=>{"use strict";var wR=Vr(),AR=ua(),kR=Xt(),PR=RangeError;rS.exports=function(e){var t=AR(kR(this)),i="",r=wR(e);if(r<0||r===1/0)throw new PR("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var lS=b((tF,uS)=>{"use strict";var oS=Ae(),RR=Po(),sS=ua(),LR=aS(),$R=Xt(),MR=oS(LR),DR=oS("".slice),CR=Math.ceil,nS=function(a){return function(e,t,i){var r=sS($R(e)),s=RR(t),n=r.length,u=i===void 0?" ":sS(i),o,l;return s<=n||u===""?r:(o=s-n,l=MR(u,CR(o/u.length)),l.length>o&&(l=DR(l,0,o)),a?r+l:l+r)}};uS.exports={start:nS(!1),end:nS(!0)}});var dS=b((iF,cS)=>{"use strict";var BR=mi();cS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(BR)});var pS=b(()=>{"use strict";var VR=Te(),_R=lS().start,OR=dS();VR({target:"String",proto:!0,forced:OR},{padStart:function(e){return _R(this,e,arguments.length>1?arguments[1]:void 0)}})});var fS=b((sF,hS)=>{"use strict";pS();var FR=Jt();hS.exports=FR("String","padStart")});var bS=b((nF,mS)=>{"use strict";var NR=fS();mS.exports=NR});var SS=b((oF,gS)=>{"use strict";var UR=bS();gS.exports=UR});var hL={};Pv(hL,{ChromecastState:()=>xr,HttpConnectionType:()=>us,Observable:()=>Ct.Observable,PlaybackState:()=>Ve,Player:()=>Ja,PredefinedQualityLimits:()=>wr,SDK_VERSION:()=>pL,Subject:()=>Ct.Subject,Subscription:()=>Ct.Subscription,Surface:()=>ls,VERSION:()=>Xn,ValueSubject:()=>Ct.ValueSubject,VideoFormat:()=>xt,VideoQuality:()=>Ct.VideoQuality,areValidLiveRecordSources:()=>Gm,clientChecker:()=>j,isMobile:()=>ir});module.exports=Rv(hL);var Xn="2.0.136-dev.b7a1035a.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ve||{}),xt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(xt||{});var xr=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(xr||{}),us=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(us||{});var ls=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ls||{}),wr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(wr||{});var Sv=Q(st(),1);var J=require("@vkontakte/videoplayer-shared");var Hd=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var fs=class{constructor(e){this.connection$=new J.ValueSubject(void 0);this.castState$=new J.ValueSubject("NOT_AVAILABLE");this.errorEvent$=new J.Subject;this.realCastState$=new J.ValueSubject("NOT_AVAILABLE");this.subscription=new J.Subscription;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=(0,J.isNonNullable)(window.chrome?.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},r||Hd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:J.ErrorCategory.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(){(0,J.isNonNullable)(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();(0,J.isNullable)(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();(0,J.isNullable)(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((0,J.fromEvent)(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(0,J.assertNever)(r.sessionState)}})).add((0,J.merge)((0,J.fromEvent)(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe((0,J.tap)(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),(0,J.map)(r=>r.castState)),(0,J.observableFrom)([i.getCastState()])).pipe((0,J.filterChanged)(),(0,J.map)(XT),(0,J.tap)(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{let s=r==="CONNECTED",n=(0,J.isNonNullable)(this.connection$.getValue());if(s&&!n){let u=i.getCurrentSession();(0,J.assertNonNullable)(u);let o=u.getCastDevice(),l=u.getMediaSession()?.media?.contentId;((0,J.isNullable)(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:o}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?(0,J.isNonNullable)(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:J.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:r})}}},XT=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return(0,J.assertNever)(a)}};var Gl=Q(st(),1),sv=Q(Gi(),1),nv=Q(iu(),1);var zm=Q(qs(),1);var qu=require("@vkontakte/videoplayer-shared");var ye=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:(0,qu.assertNever)(t)}return a},ei=(a,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(a);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(a);return Number(t.searchParams.get("offset_p")??0)}default:(0,qu.assertNever)(e)}};var B=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var kt=require("@vkontakte/videoplayer-shared"),Z=class{constructor(e){this.transitionStarted$=new kt.Subject;this.transitionEnded$=new kt.Subject;this.transitionUpdated$=new kt.Subject;this.forceChanged$=new kt.Subject;this.stateChangeStarted$=(0,kt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,kt.merge)(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||(0,kt.isNonNullable)(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}};var ju=require("@vkontakte/videoplayer-shared");var Hs=class{constructor(){this._isMiuiBrowser=!1}get current(){return this._current}get isChrome(){return this.current==="Chrome"}get isFirefox(){return this.current==="Firefox"}get isSafari(){return this.current==="Safari"}get isOpera(){return this.current==="Opera"}get isEdge(){return this.current==="Edge"}get isYandex(){return this.current==="Yandex"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get currentVersion(){return this._current_version}get chromeVersion(){return this._chromeVersion}get firefoxVersion(){return this._firefoxVersion}get safariVersion(){return this._safariVersion}get operaVersion(){return this._operaVersion}get edgeVersion(){return this._edgeVersion}get yandexVersion(){return this._yandexVersion}get isMiuiBrowser(){return this._isMiuiBrowser}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,u=/webkit|safari|khtml/i.test(e)?"Safari":void 0,o=/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||o||l||r||s||u||"Rest"}catch(t){console.error(t)}this.isChrome&&this.detectChromeVersion(),this.isFirefox&&this.detectFirefoxVersion(),this.isSafari&&this.detectSafariVersion(),this.isOpera&&this.detectOperaVersion(),this.isEdge&&this.detectEdgeVersion(),this.isYandex&&this.detectYandexVersion()}detectVersion(e){try{let{userAgent:t}=window.navigator,i=t.match(e);if(!i)return;let r=i[1],s=parseInt(r,10);if(!isNaN(s))return this._current_version=s,s}catch(t){console.error(t)}}detectChromeVersion(){this._chromeVersion=this.detectVersion(/Chrome\/(\d+\.\d+)/)}detectFirefoxVersion(){this._firefoxVersion=this.detectVersion(/Firefox\/(\d+\.\d+)/)}detectSafariVersion(){this._safariVersion=this.detectVersion(/Version\/(\d+)/)}detectOperaVersion(){this._operaVersion=this.detectVersion(/OPR\/(\d+\.\d+)/)}detectEdgeVersion(){this._edgeVersion=this.detectVersion(/Edg\/(\d+\.\d+)/)}detectYandexVersion(){this._yandexVersion=this.detectVersion(/YaBrowser\/(\d+\.\d+\.\d+)/)}};var Fm=Q(st(),1);var ir=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var js=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Fm.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=ir()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}async detectHighEntropyValues(){let{userAgentData:e}=navigator;if(e?.getHighEntropyValues){let t=await e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,u=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||u||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var Qs=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e??0,this._isHdr=!!matchMedia("(dynamic-range: high)")?.matches,this._colorDepth=screen.colorDepth}catch(t){console.error(t)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(t){console.error(t)}}};var Je=()=>window.ManagedMediaSource||window.MediaSource,rr=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Nm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Gs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var sk=document.createElement("video"),nk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',ok='video/mp4; codecs="hev1.1.6.L93.B0"',Um='video/webm; codecs="vp09.00.10.08"',qm='video/webm; codecs="av01.0.00M.08"',uk='audio/mp4; codecs="mp4a.40.2"',lk='audio/webm; codecs="opus"',Hm,ck=async()=>{if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:qm}}),window.navigator.mediaCapabilities.decodingInfo({...a,video:{...a.video,contentType:Um}})]);Hm={DASH_WEBM_AV1:e,DASH_WEBM:t}};ck().catch(a=>{console.log(sk),console.error(a)});var Ws=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 Hm}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){this._video=document.createElement("video");try{this._protocols={mms:rr(),mse:Nm(),hls:!!(this._video.canPlayType?.("application/x-mpegurl")||this._video.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!this._video.canPlayType?.("video/mp4"),webm:!!this._video.canPlayType?.("video/webm"),cmaf:!0};let e=!!Je()?.isTypeSupported?.(nk),t=!!Je()?.isTypeSupported?.(ok),i=!!Je()?.isTypeSupported?.(uk);this._codecs={h264:e,h265:t,vp9:!!Je()?.isTypeSupported?.(Um),av1:!!Je()?.isTypeSupported?.(qm),aac:i,opus:!!Je()?.isTypeSupported?.(lk),mpeg:(e||t)&&i},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(e){console.error(e)}try{this.destroyVideoElement()}catch(e){console.error("Error destroying video element:",e)}}destroyVideoElement(){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}};var jm="audio/mpeg",zs=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){this._audio=document.createElement("audio");try{this._containers={mpeg:!!this._audio.canPlayType?.(jm)},this._codecs={mp3:!!Je()?.isTypeSupported?.(jm)}}catch(e){console.error(e)}try{this.destroyAudioElement()}catch(e){console.error("Error destroying audio element:",e)}}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 Qm=require("@vkontakte/videoplayer-shared"),Hu=class{constructor(){this.isInited$=new Qm.ValueSubject(!1);this._displayChecker=new Qs,this._deviceChecker=new js(this._displayChecker),this._browserChecker=new Hs,this._videoChecker=new Ws(this._deviceChecker,this._browserChecker),this._audioChecker=new zs,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}async detect(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)}},j=new Hu;var Qu=(a,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:n}=j.video,u=(s.h264||s.h265)&&s.aac,o=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return a.filter(l=>{switch(l){case"DASH_SEP":return o&&i.mp4&&u;case"DASH_WEBM":return o&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return o&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return o&&(i.mp4&&u||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return o&&i.mp4&&u;case"DASH_LIVE_CMAF":return o&&i.mp4&&u&&i.cmaf;case"DASH_ONDEMAND":return o&&i.mp4&&u;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return(0,ju.assertNever)(l)}})},Gu=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,ju.assertNever)(a)}},Gm=(a,e)=>{let i=Object.keys(a).filter(r=>!Gu(r));return Qu(i,e).length>0};var U=require("@vkontakte/videoplayer-shared");var dk=5,pk=5,hk=500,Wm=7e3,Kr=class{constructor(e){this.subscription=new U.Subscription;this.loadMediaTimeoutSubscription=new U.Subscription;this.videoState=new Z("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(r?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:(0,U.assertNever)(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:(0,U.assertNever)(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:(0,U.assertNever)(e)}break}default:(0,U.assertNever)(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Gu(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 U.Subscription;this.subscription.add(e),this.subscription.add((0,U.merge)(this.videoState.stateChangeStarted$.pipe((0,U.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,U.map)(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new U.Subject;e.add(r.pipe((0,U.debounce)(hk)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let u=n.value;this.params.output.position$.next(u),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(u-s)>dk)&&r.next(u),s=u})),e.add((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.value,u=this.params.output.isBuffering$.getValue(),o=n===chrome.cast.media.PlayerState.BUFFERING;switch(u!==o&&this.params.output.isBuffering$.next(o),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<pk&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),B(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:(0,U.assertNever)(n)}}),t((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,U.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,U.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,U.observableFrom)(["init"])).pipe((0,U.debounce)(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),B(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&B(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()}createMediaInfo(e){let t=this.params.source,i,r,s;switch(e){case"MPEG":{let l=t[e];(0,U.assertNonNullable)(l);let c=(0,U.getHighestQuality)(Object.keys(l));(0,U.assertNonNullable)(c);let p=l[c];(0,U.assertNonNullable)(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];(0,U.assertNonNullable)(l),i=l.url,r="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let l=t[e];(0,U.assertNonNullable)(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];(0,U.assertNonNullable)(l),i=l.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];(0,U.assertNonNullable)(l),i=ye(l.url),r="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:U.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,U.assertNever)(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:u,subtitle:o}=this.params.meta;return(0,U.isNonNullable)(u)&&(n.metadata.title=u),(0,U.isNonNullable)(o)&&(n.metadata.subtitle=o),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add((0,U.timeout)(Wm).subscribe(()=>s(`timeout(${Wm})`)))});(0,zm.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:U.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ol=Q(st(),1);var Ku=require("@vkontakte/videoplayer-shared");var Ym=require("@vkontakte/videoplayer-shared"),Km=a=>{try{a.pause(),a.playbackRate=0,(0,Ym.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Ys=require("@vkontakte/videoplayer-shared"),Wu=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)}},zu=window.WeakMap?new WeakMap:new Wu,Yu=window.WeakMap?new WeakMap:new Map,fk=(a,e=20)=>{let t=0;return(0,Ys.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ue=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,Ku.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),zu.set(i,r);let s=new Ys.Subscription;return s.add(fk(i,e)),Yu.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},qe=a=>{Yu.get(a)?.unsubscribe(),Yu.delete(a);let t=zu.get(a);zu.delete(a),t?(0,Ku.clearVideoElement)(a):Km(a)};var Xu=Q(ar(),1),q=require("@vkontakte/videoplayer-shared");var ti=require("@vkontakte/videoplayer-shared"),Ks=(a,e,t,{equal:i=(n,u)=>n===u,changed$:r,onError:s}={})=>{let n=a.getState(),u=e(),o=(0,ti.isNullable)(r),l=new ti.Subscription;return r&&l.add(r.subscribe(c=>{let p=a.getState();i(c,p)&&a.setState(c)},s)),i(u,n)||(t(n),o&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),o&&a.setState(c.to)},s)),l},Pt=(a,e,t)=>Ks(e,()=>a.loop,i=>{(0,ti.isNonNullable)(i)&&(a.loop=i)},{onError:t}),He=(a,e,t,i)=>Ks(e,()=>({muted:a.muted,volume:a.volume}),r=>{(0,ti.isNonNullable)(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||r?.muted===s?.muted&&r?.volume===s?.volume,changed$:t,onError:i}),nt=(a,e,t,i)=>Ks(e,()=>a.playbackRate,r=>{(0,ti.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Xr=Ks;var yk=a=>["__",a.language,a.label].join("|"),Tk=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},Ju=class a{constructor(e){this.available$=new q.Subject;this.current$=new q.ValueSubject(void 0);this.error$=new q.Subject;this.subscription=new q.Subscription;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:q.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Xr(t.internalTextTracks,()=>(0,Xu.default)(this.internalTracks),s=>{(0,q.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,q.isNonNullable)(s)&&(0,q.isNonNullable)(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe((0,q.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Xr(t.externalTextTracks,()=>(0,Xu.default)(this.externalTracks),s=>{(0,q.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,q.isNonNullable)(s)&&(0,q.isNonNullable)(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe((0,q.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Xr(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:r})),this.subscription.add(Xr(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,q.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,q.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,q.merge)((0,q.fromEvent)(e,"addtrack"),(0,q.fromEvent)(e,"removetrack"),(0,q.observableFrom)(["init"])).pipe((0,q.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,q.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,q.merge)((0,q.fromEvent)(e,"change"),(0,q.observableFrom)(["init"])).pipe((0,q.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,q.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,q.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,q.fromEvent)(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let r=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",r))};i.track?.addEventListener("cuechange",r)})),this.subscription.add((0,q.fromEvent)(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;(0,q.isNonNullable)(t.align)&&(r.align=t.align),(0,q.isNonNullable)(t.position)&&(r.position=t.position),(0,q.isNonNullable)(t.size)&&(r.size=t.size),(0,q.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,q.assertNonNullable)(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,r=e.id?e.id:yk(e),s=this.externalTracks.has(r),n=(s?this.externalTracks.get(r)?.isAuto:this.internalTracks.get(r)?.isAuto)??r.includes("auto");return s?{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:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){(0,q.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,q.isNullable)(e)||!Tk(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){(0,q.assertNonNullable)(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){(0,q.assertNonNullable)(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},ot=Ju;var Ii=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 rb=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Zu=a=>{let e=rb(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ab=a=>{let e=rb(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var $=require("@vkontakte/videoplayer-shared");var Ik=3,sb=(a,e,t=Ik)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),u=a.end(s);if(n<=e&&e<=u){if(i=n,r=u,!t)return{from:i,to:r};for(let o=s-1;o>=0;o--)a.end(o)+t>=i&&(i=a.start(o));for(let o=s+1;o<a.length;o++)a.start(o)-t<=r&&(r=a.end(o))}}return{from:i,to:r}};var je=a=>{let e=w=>(0,$.fromEvent)(a,w).pipe((0,$.mapTo)(void 0),(0,$.shareReplay)(1)),t=new $.Subscription,i=()=>t.unsubscribe(),r=(0,$.merge)((0,$.fromEvent)(a,"progress"),(0,$.fromEvent)(a,"timeupdate")).pipe((0,$.map)(()=>sb(a.buffered,a.currentTime)),(0,$.shareReplay)(1)),s=j.browser.isSafari?(0,$.combine)({play:e("play").pipe((0,$.once)()),playing:e("playing")}).pipe((0,$.mapTo)(void 0),(0,$.shareReplay)(1)):e("playing"),n=(0,$.fromEvent)(a,"volumechange").pipe((0,$.map)(()=>({muted:a.muted,volume:a.volume})),(0,$.shareReplay)(1)),u=(0,$.fromEvent)(a,"ratechange").pipe((0,$.map)(()=>a.playbackRate),(0,$.shareReplay)(1)),o=(0,$.fromEvent)(a,"error").pipe((0,$.filter)(()=>!!(a.error||a.played.length)),(0,$.map)(()=>{let w=a.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:$.ErrorCategory.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:a.error??void 0}}),(0,$.shareReplay)(1)),l=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(()=>a.currentTime),(0,$.shareReplay)(1)),c=["waiting","seeking","seeked","timeupdate"],p=new $.Subject,d=.3,h;t.add((0,$.merge)(...c.map(w=>(0,$.fromEvent)(a,w))).subscribe(w=>{let ee=a.currentTime;a.loop&&(0,$.isNonNullable)(h)&&(0,$.isNonNullable)(ee)&&h>=a.duration-d&&ee<=d&&p.next(h),h=ee}));let m=e("pause").pipe((0,$.filter)(()=>!a.error&&h!==a.duration),(0,$.shareReplay)(1)),g=(0,$.fromEvent)(a,"enterpictureinpicture").pipe((0,$.shareReplay)(1)),S=(0,$.fromEvent)(a,"leavepictureinpicture").pipe((0,$.shareReplay)(1)),T=new $.ValueSubject(ab(a));t.add(g.subscribe(()=>T.next(!0))),t.add(S.subscribe(()=>T.next(!1)));let k=new $.ValueSubject(Zu(a)),x=(0,$.fromEvent)(a,"fullscreenchange").pipe((0,$.shareReplay)(1));t.add(x.pipe((0,$.map)(()=>Zu(a))).subscribe(k));let L=.1,C=1e3,V=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(w=>a.duration-a.currentTime<L),(0,$.filterChanged)(),(0,$.shareReplay)(1)),O=(0,$.merge)(V.pipe((0,$.filter)(w=>!a.loop&&w)),(0,$.fromEvent)(a,"ended")).pipe((0,$.throttle)(C),(0,$.mapTo)(void 0),(0,$.shareReplay)(1)),_=(0,$.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>(0,$.fromEvent)(a,w)),V.pipe((0,$.map)(w=>({type:w?"ended":"unknown"})))).pipe((0,$.map)(w=>j.browser.isFirefox&&w.type==="ended"?a.readyState<2:a.readyState<3),(0,$.filterChanged)(),(0,$.shareReplay)(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:O,looped$:p,error$:o,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:(0,$.fromEvent)(a,"durationchange").pipe((0,$.map)(()=>a.duration),(0,$.shareReplay)(1)),isBuffering$:_,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:T,inFullscreen$:k,enterPip$:g,leavePip$:S,destroy:i}};var Ft=require("@vkontakte/videoplayer-shared"),ii=a=>{switch(a){case"mobile":return Ft.VideoQuality.Q_144P;case"lowest":return Ft.VideoQuality.Q_240P;case"low":return Ft.VideoQuality.Q_360P;case"sd":case"medium":return Ft.VideoQuality.Q_480P;case"hd":case"high":return Ft.VideoQuality.Q_720P;case"fullhd":case"full":return Ft.VideoQuality.Q_1080P;case"quadhd":case"quad":return Ft.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return Ft.VideoQuality.Q_2160P}};var Oe=Q(gt(),1),il=Q(st(),1),Ei=Q(Gi(),1),M=require("@vkontakte/videoplayer-shared");var el=!1,Nt={},pb=a=>{el=a},hb=()=>{Nt={}},fb=a=>{a(Nt)},Jr=(a,e)=>{el&&(Nt.meta=Nt.meta??{},Nt.meta[a]=e)},_e=class{constructor(e){this.name=e}next(e){if(!el)return;Nt.series=Nt.series??{};let t=Nt.series[this.name]??[];t.push([Date.now(),e]),Nt.series[this.name]=t}};var Ie=require("@vkontakte/videoplayer-shared");function tl(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Xs(a,e,t){return!!a&&tl(a,e,t)==="high_quality"}function sr(a,e,t){return(0,Ie.isNullable)(a)||(0,Ie.isNonNullable)(a.min)&&(0,Ie.isNonNullable)(a.max)&&(0,Ie.isLower)(a.max,a.min)||(0,Ie.isNonNullable)(a.min)&&e&&(0,Ie.isHigher)(a.min,e)||(0,Ie.isNonNullable)(a.max)&&t&&(0,Ie.isLower)(a.max,t)}function mb({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return sr({max:a?.max?(0,Ie.videoHeightToQuality)(a.max):void 0,min:a?.min?(0,Ie.videoHeightToQuality)(a.min):void 0},e?(0,Ie.videoHeightToQuality)(e):void 0,t?(0,Ie.videoHeightToQuality)(t):void 0)}var yb=new _e("best_bitrate"),Zs=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var nr=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),ri=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=(0,M.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},en='Assertion "ABR Tracks is empty array" failed',Js=new WeakMap,bb=new WeakMap,gb=new WeakMap,Zr=(a,e,t,i)=>{let r=[...e].sort(nr(1)),s=[...t].sort(nr(1)),n=s.filter(o=>(0,M.isNonNullable)(o.bitrate)&&(0,M.isNonNullable)(a.bitrate)?a.bitrate/o.bitrate>i:!0),u=(0,Oe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Oe.default)(s,-1);return u&&(0,il.default)(n,u)?u:n.length?(0,Oe.default)(n,-1):(0,Oe.default)(s,0)},ea=(a,e,t,i)=>{let r=Js.get(e);r||(r=[...e].sort(nr(1)),Js.set(e,r));let s=Js.get(t);s||(s=[...t].sort(nr(1)),Js.set(t,s));let n=gb.get(a);n||(n=s.filter(o=>(0,M.isNonNullable)(o.bitrate)&&(0,M.isNonNullable)(a.bitrate)?a.bitrate/o.bitrate>i:!0),gb.set(a,n));let u=(0,Oe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Oe.default)(s,-1);return u&&(0,il.default)(n,u)?u:n.length?(0,Oe.default)(n,-1):(0,Oe.default)(s,0)},Sb=a=>"quality"in a,tn=(a,e,t,i)=>{let r=(0,M.isNonNullable)(i?.last?.bitrate)&&(0,M.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,M.now)()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let u=Sb(n)?"video":"audio",o=Sb(n)?n.quality:n.bitrate;return e({message:`
|
|
8
|
+
[last ${u} selected] ${o}
|
|
9
|
+
`}),n}return i?.recordSwitch(t),t},$k=(a,e)=>Math.log(e)/Math.log(a),Tb=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&j.display.pixelRatio){let s=j.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[u=0,o=0,l=0]=a.pixelRatioLogCoefficients,c=$k(n,u*s+o)+l;Number.isFinite(c)&&(r*=c)}}return Xs(t,a.highQualityLimit,a.trafficSavingLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},vb=new WeakMap,Rt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:c,droppedVideoMaxQualityLimit:p,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:g})=>{(0,M.assertNotEmptyArray)(a,en);let{containerSizeFactor:S,containerSizeLimit:T}=Tb({container:e,tuning:i,limits:r,panelSize:g}),k=i.considerPlaybackRate&&(0,M.isNonNullable)(u)?u:1,x=vb.get(a);x||(x=a.filter(E=>!(0,M.isInvariantQuality)(E.quality)).sort((E,R)=>(0,M.isHigher)(E.quality,R.quality)?-1:1),vb.set(a,x));let L=(0,Oe.default)(x,-1)?.quality,C=(0,Oe.default)(x,0)?.quality,V=sr(r,C,L),O=k*Zs(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),D={},_=null;for(let E of x){let R=!0;if(T)if(E.size)R=E.size.width<=T.width&&E.size.height<=T.height;else{let ae=T&&(0,M.videoSizeToQuality)(T);R=ae?(0,M.isLowerOrEqual)(E.quality,ae):!0}if(!R){D[E.quality]="FitsContainer";continue}let oe=h||t,N=(0,M.isNonNullable)(oe)&&isFinite(oe)&&(0,M.isNonNullable)(E.bitrate)?oe-s>=E.bitrate*O:!0,re=Xs(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===E.quality;if(!N&&!re){D[E.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,M.isNonNullable)(i.minBufferToSwitchUp)&&o&&!(0,M.isInvariantQuality)(o.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,M.isHigher)(E.quality,o.quality)){D[E.quality]="Buffer";continue}if(!!p&&(0,M.isHigherOrEqual)(E.quality,p)&&!re){D[E.quality]="DroppedFramesLimit";continue}if(!!d&&(0,M.isHigherOrEqual)(E.quality,d)&&!re){D[E.quality]="StallsLimit";continue}let Re=V||((0,M.isNullable)(r?.max)||(0,M.isLowerOrEqual)(E.quality,r.max))&&((0,M.isNullable)(r?.min)||(0,M.isHigherOrEqual)(E.quality,r.min)),Le=(0,M.isNonNullable)(c)&&!c?(0,M.isLowerOrEqual)(E.quality,i.backgroundVideoQualityLimit):!0;if(!Re||!Le){D[E.quality]="FitsQualityLimits";continue}_||(_=E)}_&&_.bitrate&&yb.next(_.bitrate);let w=_??(0,Oe.default)(x,-1)??a[0],ee=l?.last,F=tn(i,m,w,l);return(0,M.isNonNullable)(l)&&F.quality!==ee?.quality&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(
|
|
12
|
+
${a.map(E=>`{ id: ${E.id}, quality: ${E.quality}, bitrate: ${E.bitrate}, size: ${E.size?.width}:${E.size?.height} }`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,Ei.default)(i??{}).map(([R
|
|
16
|
+
${(0,Ei.default)(i??{}).map(([E,R])=>`${E}: ${R}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
|
-
containerSizeFactor: ${
|
|
20
|
+
containerSizeFactor: ${S},
|
|
21
21
|
containerSizeLimit: ${T?.width??0} x ${T?.height??0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${h},
|
|
24
24
|
reserve: ${s},
|
|
25
|
-
playbackRate: ${
|
|
25
|
+
playbackRate: ${u},
|
|
26
26
|
playbackRateFactor: ${k},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${O},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
|
-
droppedVideoMaxQualityLimit: ${
|
|
31
|
-
stallsVideoMaxQualityLimit: ${
|
|
32
|
-
limitsAreInvalid: ${
|
|
30
|
+
droppedVideoMaxQualityLimit: ${p},
|
|
31
|
+
stallsVideoMaxQualityLimit: ${d},
|
|
32
|
+
limitsAreInvalid: ${V},
|
|
33
33
|
maxQualityLimit: ${r?.max},
|
|
34
34
|
minQualityLimit: ${r?.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,Ei.default)(D).map(([R
|
|
37
|
+
${(0,Ei.default)(D).map(([E,R])=>`${E}: ${R}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${_?.quality}
|
|
41
|
+
[selected video track] ${F?.quality}
|
|
42
|
+
`}),F},rn=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:c,droppedVideoMaxQualityLimit:p,stallsVideoMaxQualityLimit:d,stallsPredictedThroughput:h,abrLogger:m,panelSize:g})=>{(0,M.assertNotEmptyArray)(a,en);let{containerSizeFactor:S,containerSizeLimit:T}=Tb({container:e,tuning:i,limits:r,panelSize:g}),k=i.considerPlaybackRate&&(0,M.isNonNullable)(u)?u:1,x=a.filter(R=>!(0,M.isInvariantQuality)(R.quality)).sort((R,oe)=>(0,M.isHigher)(R.quality,oe.quality)?-1:1),L=(0,Oe.default)(x,-1)?.quality,C=(0,Oe.default)(x,0)?.quality,V=sr(r,C,L),O=k*Zs(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),D={},w=x.filter(R=>{let oe=!0;if(T)if(R.size)oe=R.size.width<=T.width&&R.size.height<=T.height;else{let te=T&&(0,M.videoSizeToQuality)(T);oe=te?(0,M.isLowerOrEqual)(R.quality,te):!0}if(!oe)return D[R.quality]="FitsContainer",!1;let N=h||t,re=(0,M.isNonNullable)(N)&&isFinite(N)&&(0,M.isNonNullable)(R.bitrate)?N-s>=R.bitrate*O:!0,le=Xs(r,i.highQualityLimit,i.trafficSavingLimit)&&r?.min===R.quality;if(!re&&!le)return D[R.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,M.isNonNullable)(i.minBufferToSwitchUp)&&o&&!(0,M.isInvariantQuality)(o.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,M.isHigher)(R.quality,o.quality))return D[R.quality]="Buffer",!1;if(!!p&&(0,M.isHigherOrEqual)(R.quality,p)&&!le)return D[R.quality]="DroppedFramesLimit",!1;if(!!d&&(0,M.isHigherOrEqual)(R.quality,d)&&!le)return D[R.quality]="StallsLimit",!1;let Le=V||((0,M.isNullable)(r?.max)||(0,M.isLowerOrEqual)(R.quality,r.max))&&((0,M.isNullable)(r?.min)||(0,M.isHigherOrEqual)(R.quality,r.min)),ae=(0,M.isNonNullable)(c)&&!c?(0,M.isLowerOrEqual)(R.quality,i.backgroundVideoQualityLimit):!0;return!Le||!ae?(D[R.quality]="FitsQualityLimits",!1):!0})[0];w&&w.bitrate&&yb.next(w.bitrate);let ee=w??(0,Oe.default)(x,-1)??a[0],F=l?.last,E=tn(i,m,ee,l);return(0,M.isNonNullable)(l)&&E.quality!==F?.quality&&m({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
|
-
${a.map(
|
|
45
|
+
${a.map(R=>`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate}, size: ${R.size?.width}:${R.size?.height} }`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,Ei.default)(i??{}).map(([
|
|
49
|
+
${(0,Ei.default)(i??{}).map(([R,oe])=>`${R}: ${oe}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
|
-
containerSizeFactor: ${
|
|
53
|
+
containerSizeFactor: ${S},
|
|
54
54
|
containerSizeLimit: ${T?.width??0} x ${T?.height??0},
|
|
55
55
|
estimatedThroughput: ${t},
|
|
56
56
|
stallsPredictedThroughput: ${h},
|
|
57
57
|
reserve: ${s},
|
|
58
|
-
playbackRate: ${
|
|
58
|
+
playbackRate: ${u},
|
|
59
59
|
playbackRateFactor: ${k},
|
|
60
60
|
forwardBufferHealth: ${n},
|
|
61
|
-
bitrateFactor: ${
|
|
61
|
+
bitrateFactor: ${O},
|
|
62
62
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
|
-
droppedVideoMaxQualityLimit: ${
|
|
64
|
-
stallsVideoMaxQualityLimit: ${
|
|
65
|
-
limitsAreInvalid: ${
|
|
63
|
+
droppedVideoMaxQualityLimit: ${p},
|
|
64
|
+
stallsVideoMaxQualityLimit: ${d},
|
|
65
|
+
limitsAreInvalid: ${V},
|
|
66
66
|
maxQualityLimit: ${r?.max},
|
|
67
67
|
minQualityLimit: ${r?.min},
|
|
68
68
|
|
|
69
69
|
[limited video tracks]
|
|
70
|
-
${(0,Ei.default)(D).map(([
|
|
70
|
+
${(0,Ei.default)(D).map(([R,oe])=>`${R}: ${oe}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
|
-
[best video track] ${
|
|
74
|
-
[selected video track] ${
|
|
75
|
-
`}),
|
|
73
|
+
[best video track] ${w?.quality}
|
|
74
|
+
[selected video track] ${E?.quality}
|
|
75
|
+
`}),E},an=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{(0,M.assertNotEmptyArray)(t,en);let c=r.considerPlaybackRate&&(0,M.isNonNullable)(s)?s:1,p=[...t].sort(nr(-1)),d=a.bitrate;(0,M.assertNonNullable)(d);let h=c*Zs(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,g=Zr(a,e,t,r.minVideoAudioRatio),S=l||i;(0,M.isNonNullable)(S)&&isFinite(S)&&(m=p.find(x=>(0,M.isNonNullable)(x.bitrate)&&(0,M.isNonNullable)(g?.bitrate)?S-d>=x.bitrate*h&&x.bitrate>=g.bitrate:!1)),m||(m=g);let T=u?.last,k=m&&tn(r,o,m,u);return(0,M.isNonNullable)(u)&&k?.bitrate!==T?.bitrate&&o({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
|
-
${t.map(
|
|
78
|
+
${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
81
|
[tuning]
|
|
82
|
-
${(0,Ei.default)(r??{}).map(([
|
|
82
|
+
${(0,Ei.default)(r??{}).map(([x,L])=>`${x}: ${L}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
86
86
|
estimatedThroughput: ${i},
|
|
87
87
|
stallsPredictedThroughput: ${l},
|
|
88
|
-
reserve: ${
|
|
88
|
+
reserve: ${d},
|
|
89
89
|
playbackRate: ${s},
|
|
90
90
|
playbackRateFactor: ${c},
|
|
91
91
|
forwardBufferHealth: ${n},
|
|
@@ -93,20 +93,20 @@
|
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
95
|
[selected audio track] ${k?.id}
|
|
96
|
-
`}),k},
|
|
96
|
+
`}),k},sn=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{(0,M.assertNotEmptyArray)(t,en);let c=r.considerPlaybackRate&&(0,M.isNonNullable)(s)?s:1,p=bb.get(t);p||(p=[...t].sort(nr(-1)),bb.set(t,p));let d=a.bitrate;(0,M.assertNonNullable)(d);let h=c*Zs(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,g=ea(a,e,t,r.minVideoAudioRatio),S=l||i;(0,M.isNonNullable)(S)&&isFinite(S)&&(m=p.find(x=>(0,M.isNonNullable)(x.bitrate)&&(0,M.isNonNullable)(g?.bitrate)?S-d>=x.bitrate*h&&x.bitrate>=g.bitrate:!1)),m||(m=g);let T=u?.last,k=m&&tn(r,o,m,u);return(0,M.isNonNullable)(u)&&k?.bitrate!==T?.bitrate&&o({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
|
-
${t.map(
|
|
99
|
+
${t.map(x=>`{ id: ${x.id}, bitrate: ${x.bitrate} }`).join(`
|
|
100
100
|
`)}
|
|
101
101
|
|
|
102
102
|
[tuning]
|
|
103
|
-
${(0,Ei.default)(r??{}).map(([
|
|
103
|
+
${(0,Ei.default)(r??{}).map(([x,L])=>`${x}: ${L}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
107
107
|
estimatedThroughput: ${i},
|
|
108
108
|
stallsPredictedThroughput: ${l},
|
|
109
|
-
reserve: ${
|
|
109
|
+
reserve: ${d},
|
|
110
110
|
playbackRate: ${s},
|
|
111
111
|
playbackRateFactor: ${c},
|
|
112
112
|
forwardBufferHealth: ${n},
|
|
@@ -114,14 +114,14 @@
|
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
116
|
[selected audio track] ${k?.id}
|
|
117
|
-
`}),k};var Me=a=>new URL(a).hostname;var H=require("@vkontakte/videoplayer-shared");var xb=K(Pt(),1);var yb=K(st(),1),vb=a=>{if(a instanceof DOMException&&(0,yb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Qe=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!vb(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return vb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};var Ze=require("@vkontakte/videoplayer-shared");var Tb=K(er(),1),Lt=require("@vkontakte/videoplayer-shared");function ke(){return(0,Lt.now)()}function Zu(a){return ke()-a}function el(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Ib(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function sr(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,g=2e3,y=()=>{if(u)return;(0,Lt.assertNonNullable)(c);let P=Zu(c),R;if(P<g){R=g-P,setTimeout(y,R);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,_()},T=P=>(s=P,F),k=P=>(d=P,F),I=()=>(h="json",F),$=()=>{if(!u){if(--l>=0){y(),i&&i();return}u=!0,d&&d(),t&&t()}},M=P=>(p=P,F),_=()=>{c=ke(),n=new r,n.open("get",a);let P=0,R,B=0,me=()=>((0,Lt.assertNonNullable)(c),Math.max(c,Math.max(R||0,B||0)));if(s&&n.addEventListener("progress",N=>{let re=ke();s.updateChunk&&N.loaded>P&&(s.updateChunk(me(),N.loaded-P),P=N.loaded,R=re)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(u)return;(0,Lt.assertNonNullable)(n);let N=n.status;if(N>=200&&N<300){let{response:re,responseType:ue}=n,ge=re?.byteLength;if(typeof ge=="number"&&s){let Ee=ge-P;Ee&&s.updateChunk&&s.updateChunk(me(),Ee)}ue==="json"&&(!re||!(0,Tb.default)(re).length)?$():(d&&d(),e(re))}else $()}),n.addEventListener("error",()=>{$()}),p){let N=()=>{(0,Lt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(B=ke(),n.removeEventListener("readystatechange",N))};n.addEventListener("readystatechange",N)}return n.responseType=h,n.send(),F},F={withBitrateReporting:T,withParallel:M,withJSONResponse:I,withRetryCount:P=>(l=P,F),withRetryInterval:(P,R)=>((0,Lt.isNonNullable)(P)&&(g=P),(0,Lt.isNonNullable)(R)&&(m=R),F),withTimeout:P=>(o=P,F),withFinally:k,send:_,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return F}var ta=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Eb=K(er(),1);var ia=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ke(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ke()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=sr(t,s,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ke()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ke();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Eb.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var wb=require("@vkontakte/videoplayer-shared");var on=1e4,tl=3;var Rk=6e4,Lk=10,$k=1,Mk=500,ra=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new wb.Subject,this.chunkRateEstimator=new ta(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=el(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=el(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(j.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!pb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,xb.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ze.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Ib(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ia(tl,on,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let $=s&&(!c||c===this.rep);return $||t("Not running!"),$},p=($,M,_)=>{u&&u.abort(),u=sr(this.urlResolver.resolve($,!1),M,_,()=>this._retryCallback()).withTimeout(on).withBitrateReporting(this.bitrateSwitcher).withRetryCount(tl).withFinally(()=>{u=null}).send()},h=($,M,_)=>{(0,Ze.assertNonNullable)(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),M,_,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=$=>{let M=i.playbackRate;i.playbackRate!==$&&(t(`Playback rate switch: ${M}=>${$}`),i.playbackRate=$)},g=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let _=ke()-1e4,Y=0;for(let O=0;O<this.bufferStates.length;O++){let x=this.bufferStates[O];$=Math.min($,x.buf),x.ts<_&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${$} drop=${Y} jitter=${this.sourceJitter}`);let D=$-$k;this.sourceJitter>=0?D-=this.sourceJitter/2:this.sourceJitter-=1,D>3?m(1.15):D>1?m(1.1):D>.3?m(1.05):m(1)}},T=$=>{let M,_=()=>M&&M.start?M.start.length:0,Y=N=>M.start[N]/1e3,D=N=>M.dur[N]/1e3,O=N=>M.fragIndex+N,x=(N,re)=>({chunkIdx:O(N),startTS:Y(N),dur:D(N),discontinuity:re}),F=()=>{let N=0;if(M&&M.dur){let re=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ue=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ge=re;this.sourceJitter>1&&(ge+=this.sourceJitter-1);let Ee=M.dur.length-1;for(;Ee>=0&&(ge-=M.dur[Ee],!(ge<=0));--Ee);N=Math.min(Ee,M.dur.length-1-ue),N=Math.max(N,0)}return x(N,!0)},P=N=>{let re=_();if(!(re<=0)){if((0,Ze.isNonNullable)(N)){for(let ue=0;ue<re;ue++)if(Y(ue)>N)return x(ue)}return F()}},R=N=>{let re=_(),ue=N?N.chunkIdx+1:0,ge=ue-M.fragIndex;if(!(re<=0)){if(!N||ge<0||ge-re>Lk)return t(`Resync: offset=${ge} bChunks=${re} chunk=`+JSON.stringify(N)),F();if(!(ge>=re))return x(ue-M.fragIndex,!1)}},B=(N,re,ue)=>{l&&l.abort(),l=sr(this.urlResolver.resolve(N,!0,this.lowLatency),re,ue,()=>this._retryCallback()).withTimeout(on).withRetryCount(tl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(N,re)=>{B($,ue=>{if(!d())return;M=ue;let ge=!!M.lowLatency;ge!==this.lowLatency&&g(ge);let Ee=0;for(let Re=0;Re<M.dur.length;++Re)Ee+=M.dur[Re];Ee>0&&((0,Ze.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ee/M.dur.length)),r({name:"index",zeroTime:M.zeroTime,shiftDuration:M.shiftDuration}),this.sourceJitter=M.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,M.jitter/1e3)):1,N(P(re))},()=>this._handleNetworkError())},nextChunk:R}},k=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),(0,Ze.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:$=>{let{videoElement:M,logger:_}=this.params,Y=T(e.jidxUrl),D,O,x,F,P=0,R,B,me,N=()=>{R&&(clearTimeout(R),R=void 0);let te=Math.max(Mk,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Fe=P+te,Ce=ke(),xe=Math.min(1e4,Fe-Ce);P=Ce;let rt=()=>{l||d()&&Y.seek(()=>{d()&&(P=ke(),re(),N())})};xe>0?R=window.setTimeout(()=>{this.paused?N():rt()},xe):rt()},re=()=>{let te;for(;te=Y.nextChunk(F);)F=te,Le(te);let Fe=Y.nextChunk(x);if(Fe){if(x&&Fe.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?N():(k(),this._initPlayerWith(e));return}Re(Fe)}else N()},ue=(te,Fe)=>{if(!d()||!this.sourceBuffer)return;let Ce,xe,rt,Wt=vt=>{window.setTimeout(()=>{d()&&ue(te,Fe)},vt)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),Wt(100);else{let vt=ke(),ze=M.currentTime;!this.paused&&M.buffered.length>1&&B===ze&&vt-me>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),B!==ze&&(B=ze,me=vt);let zt=this._getBufferSizeSec();if(zt>30)_(`Buffered ${zt} seconds; delaying appendBuffer`),Wt(2e3);else try{this.sourceBuffer.appendBuffer(te),this.videoPlayStarted?(this.bufferStates.push({ts:vt,buf:zt}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Fe&&Fe()}catch(yt){if(yt.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),rt=this.sourceBuffer.buffered.length,rt!==0&&(Ce=this.sourceBuffer.buffered.start(0),xe=ze,xe-Ce>4&&this.sourceBuffer.remove(Ce,xe-3)),Wt(1e3);else throw yt}}},ge=()=>{O&&D&&(_([`Appending chunk, sz=${O.byteLength}:`,JSON.stringify(x)]),ue(O,function(){O=null,re()}))},Ee=te=>e.fragUrlTemplate.replace("%%id%%",te.chunkIdx),Re=te=>{d()&&h(Ee(te),(Fe,Ce)=>{if(d()){if(Ce/=1e3,O=Fe,x=te,n=te.startTS,Ce){let xe=Math.min(10,te.dur/Ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}ge()}},()=>this._handleNetworkError())},Le=te=>{d()&&((0,Ze.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(te),!1)))},ae=te=>{d()&&(e.cachedHeader=te,ue(te,()=>{D=!0,ge()}))};s=!0,Y.seek(te=>{if(d()){if(P=ke(),!te){N();return}F=te,!(0,Ze.isNullable)($)||te.startTS>$?Re(te):(x=te,re())}},$),e.cachedHeader?ae(e.cachedHeader):p(e.headerUrl,ae,()=>this._handleNetworkError())},stop:k,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,Ze.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ze.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ze.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=ke();if(this.chunkRateEstimator.addInterval(p,m,h)){let y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:y}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Zu(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ke();d<o&&(n=p),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=sr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(on).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Qe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Rk))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ab=K(ji(),1),be=require("@vkontakte/videoplayer-shared"),il=class{constructor(){this.onDroopedVideoFramesLimit$=new be.Subject;this.subscription=new be.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new be.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,be.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,be.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,be.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,be.interval)(this.droppedFramesChecker.checkTime).pipe((0,be.filter)(()=>this.playing),(0,be.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,be.debounce)(this.droppedFramesChecker.checkTime)),i=(0,be.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=(0,Ab.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>(0,be.isLower)(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},nr=il;var un=require("@vkontakte/videoplayer-shared"),kb=require("@vkontakte/videoplayer-shared");var aa=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Dk=(a,e)=>new un.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||aa()))},{...i,...e});r.observe(a);let s=(0,kb.fromEvent)(document,"visibilitychange").pipe((0,un.map)(n=>!document.hidden||aa())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),ut=Dk;var Ck=["paused","playing","ready"],Bk=["paused","playing","ready"],sa=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new ee("stopped");this.representations$=new H.ValueSubject([]);this.droppedFramesManager=new nr;this.maxSeekBackTime$=new H.ValueSubject(1/0);this.zeroTime$=new H.ValueSubject(void 0);this.liveOffset=new Ii;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:H.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),n=ii(r.name)??(0,H.videoSizeToQuality)(r.video),o=r.bitrate/1e3,u={...r.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),(0,H.isNonNullable)(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,rl.default)(Bk,e)&&(n||o)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,rl.default)(Ck,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ye(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ye(this.params.source.url,u))}return;default:return(0,H.assertNever)(e)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:H.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,H.merge)(this.videoState.stateChangeStarted$.pipe((0,H.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,H.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Me(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=je(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,H.map)(r=>r.map(({track:s})=>s)),(0,H.filter)(r=>!!r.length),(0,H.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,H.filterChanged)(),(0,H.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,H.combine)({zeroTime:this.zeroTime$.pipe((0,H.filter)(H.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(kt(this.video,this.params.desiredState.isLooped,t)).add(He(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(nt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ut(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&(0,H.videoQualityToHeight)(r),min:s&&(0,H.videoQualityToHeight)(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,H.assertNever)(r.to)}},t)).add((0,H.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),qe(this.video)}createLiveDashPlayer(){let e=new ra({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,H.isNonNullable)(t)?t:Rt(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let l=e.find(({track:c})=>c.id===s)?.representation;(0,H.assertNonNullable)(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;(0,H.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ye(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Pb=sa;var VS=K(st(),1);var Pe=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var G=require("@vkontakte/videoplayer-shared");var{NativeAbortSignal:T0,NativeAbortController:I0}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self<"u"?self:global);function Rb(a){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=a,e}function Lb(a){if(a===void 0)if(typeof document>"u")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch{a=new Error("This operation was aborted"),a.name="AbortError"}return a}var ln=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},or=class extends ln{constructor(){super(),this.listeners||ln.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 xi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new xi;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},xi=class{constructor(){Object.defineProperty(this,"signal",{value:new or,writable:!0,configurable:!0})}abort(e){let t=Lb(e),i=Rb(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(xi.prototype[Symbol.toStringTag]="AbortController",or.prototype[Symbol.toStringTag]="AbortSignal");function cn(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function al(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!cn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Vk=()=>"fetch"in window,na=Vk()&&cn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),$b=na?al({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=na?$b.fetch:window.fetch,M0=na?$b.Request:window.Request,oe=na?xi:window.AbortController,D0=na?or:window.AbortSignal;var kl=K(oa(),1);var gg=K(bg(),1),ur=require("@vkontakte/videoplayer-shared"),dn=a=>{if(!a)return{id:"EmptyResponse",category:ur.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ur.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,gg.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ur.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:ur.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ur.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var De=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var v=require("@vkontakte/videoplayer-shared");var hn=K(st(),1),mr=K(Pt(),1),fn=K(oa(),1);var TP=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},IP=a=>window.clearTimeout(a),Sg=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),vg=!Sg(window.requestIdleCallback)||!Sg(window.cancelIdleCallback),lr=vg?TP:window.requestIdleCallback,$t=vg?IP:window.cancelIdleCallback;var AS=K(Hs(),1);var ai=require("@vkontakte/videoplayer-shared");var EP=18,yg=!1;try{yg=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=EP}catch(a){console.error(a)}var cl=class{constructor(e){this.bufferFull$=new ai.Subject;this.error$=new ai.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:ai.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};yg&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=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:ai.ErrorCategory.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:(0,ai.assertNever)(t)}}},Tg=cl;var cr=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var w=require("@vkontakte/videoplayer-shared");var se=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var dr=class extends se{};var la=class extends se{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ca=class extends se{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var da=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var de=class extends se{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var pa=class extends de{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ha=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends se{constructor(e,t){super(e,t),this.data=this.content}};var wi=class extends de{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var ma=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends de{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Sa=class extends de{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var va=class extends de{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ya=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends de{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 Ia=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xa=class extends de{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var wa=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Aa=class extends de{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 ka=class extends de{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 Pa=class extends de{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 Ra=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var La=class extends de{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var $a=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var wP={ftyp:ca,moov:da,mvhd:pa,moof:ha,mdat:fa,sidx:wi,trak:ma,mdia:ya,mfhd:xa,tkhd:Ta,traf:wa,tfhd:Aa,tfdt:ka,trun:Pa,minf:Ia,sv3d:ba,st3d:ga,prhd:Sa,proj:Ea,equi:va,uuid:la,stbl:Ra,stsd:La,avc1:$a,unknown:dr},Ut=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=wP[e];return i?new i(t,new a):new dr(t,new a)}};var si=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(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 kP=new TextDecoder("ascii"),PP=a=>kP.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",RP=a=>{let e=new wi(a,new Ut),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},LP=(a,e)=>{let i=new Ut().parse(a),r=new si(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},$P=a=>{let t=new Ut().parse(a),i=new si(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},MP=a=>{let t=new Ut().parse(a);return new si(t).find("sidx")?.timescale},DP=(a,e)=>{let i=new Ut().parse(a),s=new si(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},CP=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Ut().parse(a),r=new si(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},Ig={validateData:PP,parseInit:CP,getIndexRange:()=>{},parseSegments:RP,parseFeedableSegmentChunk:LP,getChunkEndTime:DP,getServerLatencyTimestamps:$P,getTimescaleFromIndex:MP};var Ca=K(st(),1),qt=require("@vkontakte/videoplayer-shared");var xg=require("@vkontakte/videoplayer-shared");var Eg={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"}},wg=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Da(a,t),r=i in Eg,s=r?Eg[i].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Da(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Da=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},gt=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Da(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,xg.assertNever)(e)}},Ai=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=wg(i);if(!e(r))return;r.type==="master"&&Ai(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Ag=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=wg(a);return Ai(r.value,({tag:s,type:n,value:o})=>(s===17143?e=gt(o,n):s===17026?t=gt(o,n):s===17029&&(i=gt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var kg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],BP=[231,22612,22743,167,171,163,160,175],VP=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Ai(a,({tag:p,type:h,value:m,valueSize:g})=>{if(p===21419){let y=gt(m,h);l=Da(y)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+g):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=gt(m,h):p===17545?r=gt(m,h):p===21420&&l===475249515?u=gt(m,h):p===374648427?Ai(m,({tag:y,type:T,value:k})=>y===30321?(c=gt(k,T)===1,!1):!0):s&&n&&(0,Ca.default)(kg,p)&&(o=!0),!o}),(0,qt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,qt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,qt.assertNonNullable)(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:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},_P=a=>{if((0,qt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},OP=(a,e)=>{let t=!1,i=!1,r=o=>(0,qt.isNonNullable)(o.time)&&(0,qt.isNonNullable)(o.position),s=[],n;return Ai(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=gt(l,u));break;case 183:break;case 241:n&&(n.position=gt(l,u));break;default:t&&(0,Ca.default)(kg,o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},FP=a=>{let e=0,t=!1;try{Ai(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ca.default)(BP,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Ca.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Pg={validateData:Ag,parseInit:VP,getIndexRange:_P,parseSegments:OP,parseFeedableSegmentChunk:FP};var Mt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Pg;case"mp4":return Ig}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Dt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var gl=K(Xg(),1),SS=K(ji(),1),vS=K(hS(),1),yS=K(Pt(),1),Sl=K(er(),1);var fS=K(st(),1),bl=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,fS.default)(["6E","7A","F4"],o)}}return!1};var Ba=require("@vkontakte/videoplayer-shared");var mS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var bS=a=>{try{let e=OR(),t=a.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 s=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:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function OR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
117
|
+
`}),k};var Me=a=>new URL(a).hostname;var H=require("@vkontakte/videoplayer-shared");var kb=Q(gt(),1);var Eb=Q(st(),1),Ib=a=>{if(a instanceof DOMException&&(0,Eb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Qe=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!Ib(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return Ib(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};var Ze=require("@vkontakte/videoplayer-shared");var xb=Q(ar(),1),Lt=require("@vkontakte/videoplayer-shared");function ke(){return(0,Lt.now)()}function rl(a){return ke()-a}function al(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,u,o=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return o&&(n+=l+"lowLat=1",l="&"),u&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function wb(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function or(a,e,t,i){let r=window.XMLHttpRequest,s,n,u,o=!1,l=0,c,p,d=!1,h="arraybuffer",m=7e3,g=2e3,S=()=>{if(o)return;(0,Lt.assertNonNullable)(c);let F=rl(c),E;if(F<g){E=g-F,setTimeout(S,E);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,V()},T=F=>(s=F,ee),k=F=>(p=F,ee),x=()=>(h="json",ee),L=()=>{if(!o){if(--l>=0){S(),i&&i();return}o=!0,p&&p(),t&&t()}},C=F=>(d=F,ee),V=()=>{c=ke(),n=new r,n.open("get",a);let F=0,E,R=0,oe=()=>((0,Lt.assertNonNullable)(c),Math.max(c,Math.max(E||0,R||0)));if(s&&n.addEventListener("progress",N=>{let re=ke();s.updateChunk&&N.loaded>F&&(s.updateChunk(oe(),N.loaded-F),F=N.loaded,E=re)}),u&&(n.timeout=u,n.addEventListener("timeout",()=>L())),n.addEventListener("load",()=>{if(o)return;(0,Lt.assertNonNullable)(n);let N=n.status;if(N>=200&&N<300){let{response:re,responseType:le}=n,ge=re?.byteLength;if(typeof ge=="number"&&s){let Ee=ge-F;Ee&&s.updateChunk&&s.updateChunk(oe(),Ee)}le==="json"&&(!re||!(0,xb.default)(re).length)?L():(p&&p(),e(re))}else L()}),n.addEventListener("error",()=>{L()}),d){let N=()=>{(0,Lt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(R=ke(),n.removeEventListener("readystatechange",N))};n.addEventListener("readystatechange",N)}return n.responseType=h,n.send(),ee},ee={withBitrateReporting:T,withParallel:C,withJSONResponse:x,withRetryCount:F=>(l=F,ee),withRetryInterval:(F,E)=>((0,Lt.isNonNullable)(F)&&(g=F),(0,Lt.isNonNullable)(E)&&(m=E),ee),withTimeout:F=>(u=F,ee),withFinally:k,send:V,abort:()=>{n&&(n.abort(),n=void 0),o=!0,p&&p()}};return ee}var ta=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,u=s.end-s.start;i+=n;let o=s.bytes*n/u;r+=o,s.start=t,s.bytes-=o}}}if(r>0&&i>0){let s=r*8/(i/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ab=Q(ar(),1);var ia=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=ke(),r=o=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=o,e._errorCB?e._errorCB(o):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=o=>{e._complete=1,e._responseData=o,e._downloadTime=ke()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(o,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},u=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=or(t,s,()=>r("error"),u),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ke()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ke();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Ab.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let u=this.pendingQueue.indexOf(e);u!==-1&&this.pendingQueue.splice(u,1),this.logger(`Request not prefetched, starting new request, url=${e}${u===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=r,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Pb=require("@vkontakte/videoplayer-shared");var nn=1e4,sl=3;var Dk=6e4,Ck=10,Bk=1,Vk=500,ra=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new Pb.Subject,this.chunkRateEstimator=new ta(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=al(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){if(this.rep&&this.rep.stop(),this.currentManifestEntry){let e=this.params.playbackState.getState();this.paused=e==="paused",this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0)}}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=al(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{!!e.error&&!this.destroyed&&(t(`Video element error: ${e.error?.code}, details: ${e.error?.message}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&!this.waitingForFirstBufferAfterSrcChange&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(j.display.pixelRatio||1)*t.offsetHeight||520;for(let u=0;u<this.manifest.length;++u){s=this.manifest[u];let{max:o,min:l}=this.autoQualityLimits||{};!mb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,kb.default)(this.manifest,-1).video.height})&&(o&&s.video.height>o||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||(0,Ze.isNonNullable)(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{wb(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ia(sl,nn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,u=null,o=null,l=null,c=!1,p=()=>{let L=s&&(!c||c===this.rep);return L||t("Not running!"),L},d=(L,C,V)=>{o&&o.abort(),o=or(this.urlResolver.resolve(L,!1),C,V,()=>this._retryCallback()).withTimeout(nn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(sl).withFinally(()=>{o=null}).send()},h=(L,C,V)=>{(0,Ze.assertNonNullable)(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(L,!1),C,V,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},m=L=>{let C=i.playbackRate;i.playbackRate!==L&&(t(`Playback rate switch: ${C}=>${L}`),i.playbackRate=L)},g=L=>{this.lowLatency=L,t(`lowLatency changed to ${L}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let L=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let V=ke()-1e4,O=0;for(let _=0;_<this.bufferStates.length;_++){let w=this.bufferStates[_];L=Math.min(L,w.buf),w.ts<V&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${L} drop=${O} jitter=${this.sourceJitter}`);let D=L-Bk;this.sourceJitter>=0?D-=this.sourceJitter/2:this.sourceJitter-=1,D>3?m(1.15):D>1?m(1.1):D>.3?m(1.05):m(1)}},T=L=>{let C,V=()=>C&&C.start?C.start.length:0,O=N=>C.start[N]/1e3,D=N=>C.dur[N]/1e3,_=N=>C.fragIndex+N,w=(N,re)=>({chunkIdx:_(N),startTS:O(N),dur:D(N),discontinuity:re}),ee=()=>{let N=0;if(C&&C.dur){let re=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,le=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ge=re;this.sourceJitter>1&&(ge+=this.sourceJitter-1);let Ee=C.dur.length-1;for(;Ee>=0&&(ge-=C.dur[Ee],!(ge<=0));--Ee);N=Math.min(Ee,C.dur.length-1-le),N=Math.max(N,0)}return w(N,!0)},F=N=>{let re=V();if(!(re<=0)){if((0,Ze.isNonNullable)(N)){for(let le=0;le<re;le++)if(O(le)>N)return w(le)}return ee()}},E=N=>{let re=V(),le=N?N.chunkIdx+1:0,ge=le-C.fragIndex;if(!(re<=0)){if(!N||ge<0||ge-re>Ck)return t(`Resync: offset=${ge} bChunks=${re} chunk=`+JSON.stringify(N)),ee();if(!(ge>=re))return w(le-C.fragIndex,!1)}},R=(N,re,le)=>{l&&l.abort(),l=or(this.urlResolver.resolve(N,!0,this.lowLatency),re,le,()=>this._retryCallback()).withTimeout(nn).withRetryCount(sl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(N,re)=>{R(L,le=>{if(!p())return;C=le;let ge=!!C.lowLatency;ge!==this.lowLatency&&g(ge);let Ee=0;for(let Re=0;Re<C.dur.length;++Re)Ee+=C.dur[Re];Ee>0&&((0,Ze.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ee/C.dur.length)),r({name:"index",zeroTime:C.zeroTime,shiftDuration:C.shiftDuration}),this.sourceJitter=C.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,C.jitter/1e3)):1,N(F(re))},()=>this._handleNetworkError())},nextChunk:E}},k=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),(0,Ze.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:L=>{let{videoElement:C,logger:V}=this.params,O=T(e.jidxUrl),D,_,w,ee,F=0,E,R,oe,N=()=>{E&&(clearTimeout(E),E=void 0);let te=Math.max(Vk,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Fe=F+te,Ce=ke(),xe=Math.min(1e4,Fe-Ce);F=Ce;let rt=()=>{l||p()&&O.seek(()=>{p()&&(F=ke(),re(),N())})};xe>0?E=window.setTimeout(()=>{this.paused?N():rt()},xe):rt()},re=()=>{let te;for(;te=O.nextChunk(ee);)ee=te,Le(te);let Fe=O.nextChunk(w);if(Fe){if(w&&Fe.discontinuity){V("Detected discontinuity; restarting playback"),this.paused?N():(k(),this._initPlayerWith(e));return}Re(Fe)}else N()},le=(te,Fe)=>{if(!p()||!this.sourceBuffer)return;let Ce,xe,rt,Wt=yt=>{window.setTimeout(()=>{p()&&le(te,Fe)},yt)};if(this.sourceBuffer.updating)V("Source buffer is updating; delaying appendBuffer"),Wt(100);else{let yt=ke(),ze=C.currentTime;!this.paused&&C.buffered.length>1&&R===ze&&yt-oe>500&&(V("Stall suspected; trying to fix"),this._fixupStall()),R!==ze&&(R=ze,oe=yt);let zt=this._getBufferSizeSec();if(zt>30)V(`Buffered ${zt} seconds; delaying appendBuffer`),Wt(2e3);else try{this.sourceBuffer.appendBuffer(te),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:zt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Fe&&Fe()}catch(Tt){if(Tt.name==="QuotaExceededError")V("QuotaExceededError; delaying appendBuffer"),rt=this.sourceBuffer.buffered.length,rt!==0&&(Ce=this.sourceBuffer.buffered.start(0),xe=ze,xe-Ce>4&&this.sourceBuffer.remove(Ce,xe-3)),Wt(1e3);else throw Tt}}},ge=()=>{_&&D&&(V([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(w)]),le(_,function(){_=null,re()}))},Ee=te=>e.fragUrlTemplate.replace("%%id%%",te.chunkIdx),Re=te=>{p()&&h(Ee(te),(Fe,Ce)=>{if(p()){if(Ce/=1e3,_=Fe,w=te,n=te.startTS,Ce){let xe=Math.min(10,te.dur/Ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}ge()}},()=>this._handleNetworkError())},Le=te=>{p()&&((0,Ze.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(te),!1)))},ae=te=>{p()&&(e.cachedHeader=te,le(te,()=>{D=!0,ge()}))};s=!0,O.seek(te=>{if(p()){if(F=ke(),!te){N();return}ee=te,!(0,Ze.isNullable)(L)||te.startTS>L?Re(te):(w=te,re())}},L),e.cachedHeader?ae(e.cachedHeader):d(e.headerUrl,ae,()=>this._handleNetworkError())},stop:k,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,Ze.isNonNullable)(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,(0,Ze.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,Ze.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=p=>{if(!this.autoQuality)return;let d,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&p<this.bitrate&&(h=this._getBufferSizeSec(),m=p/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(p)}`);return}d=this._selectQuality(p),d?this._switchToQuality(d):e(`Could not find quality by bitrate ${p}`)},s={updateChunk:(d,h)=>{let m=ke();if(this.chunkRateEstimator.addInterval(d,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-d,speed:S}),!0}},get:()=>{let d=this.chunkRateEstimator.getBitRate();return d?d*.85:0}},n=-1/0,u,o=!0,l=()=>{let p=s.get();if(p&&u&&this.autoQuality){if(o&&p>u&&rl(n)<3e4)return;i(p)}o=this.autoQuality};return{updateChunk:(p,d)=>{let h=s.updateChunk(p,d);return h&&l(),h},notifySwitch:p=>{let d=ke();p<u&&(n=d),u=p}}}_fetchManifest(e,t,i){this.manifestRequest=or(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(nn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Qe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let u=[];return n?.length?(n.forEach((o,l)=>{o.video&&r.canPlayType(o.codecs).replace(/no/,"")&&window.MediaSource?.isTypeSupported?.(o.codecs)&&(o.index=l,u.push(o))}),u.sort(function(o,l){return o.video&&l.video?l.video.height-o.video.height:l.bitrate-o.bitrate}),u):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Dk))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Rb=Q(Gi(),1),be=require("@vkontakte/videoplayer-shared"),nl=class{constructor(){this.onDroopedVideoFramesLimit$=new be.Subject;this.subscription=new be.Subscription;this.playing=!1;this.tracks=[];this.forceChecker$=new be.Subject;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>t?.height===this.video.videoHeight&&t?.width===this.video.videoWidth);e&&!(0,be.isInvariantQuality)(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&(0,be.isHigher)(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=(this.limitCounts[this.currentQuality]??0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add((0,be.fromEvent)(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=(0,be.interval)(this.droppedFramesChecker.checkTime).pipe((0,be.filter)(()=>this.playing),(0,be.filter)(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe((0,be.debounce)(this.droppedFramesChecker.checkTime)),i=(0,be.merge)(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){let t=(0,Rb.default)(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[r])=>(0,be.isLower)(i,r)?-1:1)?.[0]?.[0];return e??t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},ur=nl;var on=require("@vkontakte/videoplayer-shared"),Lb=require("@vkontakte/videoplayer-shared");var aa=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var _k=(a,e)=>new on.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,u)=>{n.forEach(o=>t.next(o.isIntersecting||aa()))},{...i,...e});r.observe(a);let s=(0,Lb.fromEvent)(document,"visibilitychange").pipe((0,on.map)(n=>!document.hidden||aa())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),ut=_k;var Ok=["paused","playing","ready"],Fk=["paused","playing","ready"],sa=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new Z("stopped");this.representations$=new H.ValueSubject([]);this.droppedFramesManager=new ur;this.maxSeekBackTime$=new H.ValueSubject(1/0);this.zeroTime$=new H.ValueSubject(void 0);this.liveOffset=new Ii;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:H.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let r of t){let s=r.name??r.index.toString(10),n=ii(r.name)??(0,H.videoSizeToQuality)(r.video),u=r.bitrate/1e3,o={...r.video};if(!n)continue;let l={id:s,quality:n,bitrate:u,size:o};i.push({track:l,representation:r})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:r})=>r)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:r})=>r===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),(0,H.isNonNullable)(i)&&this.params.output.currentVideoTrack$.next(i);break}case"bandwidth":{let{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,ol.default)(Fk,e)&&(n||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,ol.default)(Ok,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ye(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let o=r?.from;o&&o==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let o=this.liveOffset.getTotalOffset();o>=this.maxSeekBackTime$.getValue()&&(o=0,this.liveOffset.resetTo(o)),this.liveOffset.resume(),this.params.output.position$.next(-o/1e3),this.dash.reinit(ye(this.params.source.url,o))}return;default:return(0,H.assertNever)(e)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:H.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,H.merge)(this.videoState.stateChangeStarted$.pipe((0,H.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,H.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Me(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=je(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,H.map)(r=>r.map(({track:s})=>s)),(0,H.filter)(r=>!!r.length),(0,H.once)()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe((0,H.filterChanged)(),(0,H.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,H.combine)({zeroTime:this.zeroTime$.pipe((0,H.filter)(H.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(Pt(this.video,this.params.desiredState.isLooped,t)).add(He(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(nt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(ut(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&(0,H.videoQualityToHeight)(r),min:s&&(0,H.videoQualityToHeight)(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":this.params.desiredState.playbackState.getTransition()?.to==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return(0,H.assertNever)(r.to)}},t)).add((0,H.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),qe(this.video)}createLiveDashPlayer(){let e=new ra({videoElement:this.video,videoState:this.videoState,playbackState:this.params.desiredState.playbackState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),i=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&(0,H.isNonNullable)(t)?t:Rt(e.map(({track:l})=>l),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=r?.id,n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.videoTrack.getState()?.id,o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==u)&&this.setVideoTrack(r),o&&this.setAutoQuality(i),n||o||s!==u){let l=e.find(({track:c})=>c.id===s)?.representation;(0,H.assertNonNullable)(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;(0,H.assertNonNullable)(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ye(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var $b=sa;var NS=Q(st(),1);var Pe=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var W=require("@vkontakte/videoplayer-shared");var{NativeAbortSignal:A0,NativeAbortController:k0}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self<"u"?self:global);function Mb(a){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=a,e}function Db(a){if(a===void 0)if(typeof document>"u")a=new Error("This operation was aborted"),a.name="AbortError";else try{a=new DOMException("signal is aborted without reason"),Object.defineProperty(a,"name",{value:"AbortError"})}catch{a=new Error("This operation was aborted"),a.name="AbortError"}return a}var un=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];try{n.callback.call(this,e)}catch(u){Promise.resolve().then(()=>{throw u})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},lr=class extends un{constructor(){super(),this.listeners||un.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 xi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new xi;function i(){t.abort(this.reason),r()}function r(){for(let s of e)s.removeEventListener("abort",i)}for(let s of e)if(s.aborted){t.abort(s.reason);break}else s.addEventListener("abort",i);return t.signal}},xi=class{constructor(){Object.defineProperty(this,"signal",{value:new lr,writable:!0,configurable:!0})}abort(e){let t=Db(e),i=Mb(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(xi.prototype[Symbol.toStringTag]="AbortController",lr.prototype[Symbol.toStringTag]="AbortSignal");function ln(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function ul(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!ln({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let p;c&&c.signal&&(p=c.signal,delete c.signal);let d=new t(l,c);return p&&Object.defineProperty(d,"signal",{writable:!1,enumerable:!1,configurable:!0,value:p}),d},s.prototype=t.prototype);let n=e;return{fetch:(o,l)=>{let c=s&&s.prototype.isPrototypeOf(o)?o.signal:l?l.signal:void 0;if(c){let p;try{p=new DOMException("Aborted","AbortError")}catch{p=new Error("Aborted"),p.name="AbortError"}if(c.aborted)return Promise.reject(p);let d=new Promise((h,m)=>{c.addEventListener("abort",()=>m(p),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([d,n(o,l)])}return n(o,l)},Request:s}}var Nk=()=>"fetch"in window,na=Nk()&&ln({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Cb=na?ul({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=na?Cb.fetch:window.fetch,_0=na?Cb.Request:window.Request,ue=na?xi:window.AbortController,O0=na?lr:window.AbortSignal;var $l=Q(oa(),1);var yg=Q(vg(),1),cr=require("@vkontakte/videoplayer-shared"),cn=a=>{if(!a)return{id:"EmptyResponse",category:cr.ErrorCategory.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:cr.ErrorCategory.NETWORK,message:`UV Error ${a}`};let e=(0,yg.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:cr.ErrorCategory.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:cr.ErrorCategory.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:cr.ErrorCategory.PARSER,message:"Response is valid XML, but parser failed"}};var De=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};var y=require("@vkontakte/videoplayer-shared");var hn=Q(st(),1),ki=Q(gt(),1),fn=Q(oa(),1);var wP=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},AP=a=>window.clearTimeout(a),Tg=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),Ig=!Tg(window.requestIdleCallback)||!Tg(window.cancelIdleCallback),dr=Ig?wP:window.requestIdleCallback,$t=Ig?AP:window.cancelIdleCallback;var $S=Q(qs(),1);var ai=require("@vkontakte/videoplayer-shared");var kP=18,Eg=!1;try{Eg=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=kP}catch(a){console.error(a)}var fl=class{constructor(e){this.bufferFull$=new ai.Subject;this.error$=new ai.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:ai.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};Eg&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=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:ai.ErrorCategory.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:(0,ai.assertNever)(t)}}},xg=fl;var pr=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};var A=require("@vkontakte/videoplayer-shared");var Ag=Q(gt(),1);var dn=a=>a.valid,se=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i===1&&(this.cursor+=8);let r=e.byteOffset+this.cursor,s;i===0?(this.size=void 0,this.valid=!1,s=void 0):i===1?(this.size=void 0,this.valid=!1,s=void 0):i>e.byteLength?(this.size=i,this.valid=!1,s=Math.min(i-this.cursor,e.byteLength-this.cursor)):(this.size=i,this.valid=!0,s=i-this.cursor),this.content=new DataView(e.buffer,r,s)}get id(){return this.type}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var hr=class extends se{};var wg=require("@vkontakte/videoplayer-shared");var la=class extends se{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:(0,wg.assertNever)(e)}}};var ca=class extends se{constructor(e,t){if(super(e,t),!this.valid)return;this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8);for(let r=0;r<i.byteLength;r+=4){let s=this.readString(4);this.compatibleBrands.push(s)}}};var da=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pe=class extends se{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 pa=class extends pe{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 ha=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var fa=class extends se{constructor(e,t){super(e,t),this.data=this.content}};var wi=class extends pe{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){if(super(e,t),!!this.valid){this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,u=this.readUint32();r=this.readUint32();let o=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:u,SAPType:o,SAPDeltaTime:l})}}}};var ma=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends pe{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 Sa=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var va=class extends pe{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 ya=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ta=class extends pe{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 Ia=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var xa=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var wa=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Aa=class extends pe{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 ka=class extends pe{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 Pa=class extends pe{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 Ra=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var La=class extends pe{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 $a=class extends se{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 RP={ftyp:ca,moov:da,mvhd:pa,moof:ha,mdat:fa,sidx:wi,trak:ma,mdia:ya,mfhd:xa,tkhd:Ta,traf:wa,tfhd:Aa,tfdt:ka,trun:Pa,minf:Ia,sv3d:ba,st3d:ga,prhd:Sa,proj:Ea,equi:va,uuid:la,stbl:Ra,stsd:La,avc1:$a,unknown:hr},Ut=class a{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;){let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n;try{n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i))}catch(u){if(!(u instanceof RangeError))throw u}if(!n||!dn(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=RP[e];return i?new i(t,new a):new hr(t,new a)}};var si=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{dn(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 $P=new TextDecoder("ascii"),MP=a=>$P.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",DP=a=>{let e=new wi(a,new Ut),t=e.earliestPresentationTime/e.timescale*1e3,i=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,u={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,u})},CP=(a,e)=>{let i=new Ut().parse(a),r=new si(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.findAll("mdat");if(!(n.length&&s.length))return null;let u=s[0],o=n[n.length-1],l=u.source.byteOffset,p=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(a.buffer,l,p)},BP=a=>{let t=new Ut().parse(a),i=new si(t),r={},s=i.findAll("uuid"),n=(0,Ag.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},VP=a=>{let t=new Ut().parse(a);return new si(t).find("sidx")?.timescale},_P=(a,e)=>{let i=new Ut().parse(a),s=new si(i).findAll("traf"),n=s[s.length-1].children.find(p=>p.type==="tfhd"),u=s[s.length-1].children.find(p=>p.type==="tfdt"),o=s[s.length-1].children.find(p=>p.type==="trun"),l=0;return o.sampleDuration.length?l=o.sampleDuration.reduce((p,d)=>p+d,0):l=n.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+l)/e*1e3},OP=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new Ut().parse(a),r=new si(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let u=r.find("prhd");u&&(e.projectionData.pose.yaw=u.poseYawDegrees,e.projectionData.pose.pitch=u.posePitchDegrees,e.projectionData.pose.roll=u.poseRollDegrees);let o=r.find("equi");o&&(e.projectionData.bounds.top=o.projectionBoundsTop,e.projectionData.bounds.right=o.projectionBoundsRight,e.projectionData.bounds.bottom=o.projectionBoundsBottom,e.projectionData.bounds.left=o.projectionBoundsLeft)}return e},kg={validateData:MP,parseInit:OP,getIndexRange:()=>{},parseSegments:DP,parseFeedableSegmentChunk:CP,getChunkEndTime:_P,getServerLatencyTimestamps:BP,getTimescaleFromIndex:VP};var Ca=Q(st(),1),qt=require("@vkontakte/videoplayer-shared");var Rg=require("@vkontakte/videoplayer-shared");var Pg={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"}},Lg=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Da(a,t),r=i in Pg,s=r?Pg[i].type:"binary",n=a.getUint8(t),u=0;n&128?u=1:n&64?u=2:n&32?u=3:n&16?u=4:n&8?u=5:n&4?u=6:n&2?u=7:n&1&&(u=8);let o=new DataView(a.buffer,a.byteOffset+t+1,u-1),l=n&255>>u,c=Da(o),p=l*2**((u-1)*8)+c,d=t+u,h;return d+p>a.byteLength?h=new DataView(a.buffer,a.byteOffset+d):h=new DataView(a.buffer,a.byteOffset+d,p),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:d,tagSize:d+p,value:h,valueSize:p}},Da=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*2**16+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*2**32+a.getUint32(1);case 6:return a.getUint16(0)*2**32+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},St=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Da(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:(0,Rg.assertNever)(e)}},Ai=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Lg(i);if(!e(r))return;r.type==="master"&&Ai(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},$g=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Lg(a);return Ai(r.value,({tag:s,type:n,value:u})=>(s===17143?e=St(u,n):s===17026?t=St(u,n):s===17029&&(i=St(u,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var Mg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],FP=[231,22612,22743,167,171,163,160,175],NP=a=>{let e,t,i,r,s=!1,n=!1,u=!1,o,l,c=!1,p=0;return Ai(a,({tag:d,type:h,value:m,valueSize:g})=>{if(d===21419){let S=St(m,h);l=Da(S)}else d!==21420&&(l=void 0);return d===408125543?(e=m.byteOffset,t=m.byteOffset+g):d===357149030?s=!0:d===290298740?n=!0:d===2807729?i=St(m,h):d===17545?r=St(m,h):d===21420&&l===475249515?o=St(m,h):d===374648427?Ai(m,({tag:S,type:T,value:k})=>S===30321?(c=St(k,T)===1,!1):!0):s&&n&&(0,Ca.default)(Mg,d)&&(u=!0),!u}),(0,qt.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,qt.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,qt.assertNonNullable)(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:o,is3dVideo:c,stereoMode:p,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},UP=a=>{if((0,qt.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},qP=(a,e)=>{let t=!1,i=!1,r=u=>(0,qt.isNonNullable)(u.time)&&(0,qt.isNonNullable)(u.position),s=[],n;return Ai(a,({tag:u,type:o,value:l})=>{switch(u){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=St(l,o));break;case 183:break;case 241:n&&(n.position=St(l,o));break;default:t&&(0,Ca.default)(Mg,u)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((u,o)=>{let{time:l,position:c}=u,p=s[o+1];return{status:"none",time:{from:l,to:p?p.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:p?e.segmentStart+p.position-1:e.segmentEnd-1}}})},HP=a=>{let e=0,t=!1;try{Ai(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ca.default)(FP,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Ca.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Dg={validateData:$g,parseInit:NP,getIndexRange:UP,parseSegments:qP,parseFeedableSegmentChunk:HP};var Mt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Dg;case"mp4":return kg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Dt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Tl=Q(iS(),1),ES=Q(Gi(),1),xS=Q(SS(),1),wS=Q(gt(),1),Il=Q(ar(),1);var vS=Q(st(),1),yl=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),u=s+n;return(0,vS.default)(["6E","7A","F4"],u)}}return!1};var Ba=require("@vkontakte/videoplayer-shared");var yS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var TS=a=>{try{let e=qR(),t=a.match(e),{groups:i}=t??{};if(i){let r={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(o=>{r[o[0]]=o.slice(2)})}let s=i.variants?.split(/-/).filter(u=>u!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:r,variants:s};return Object.keys(n).forEach(u=>{let o=n[u];(typeof o>"u"||o==="")&&delete n[u]}),n}return null}catch{return null}};function qR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
118
118
|
(?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
|
|
119
119
|
(-(?<script>[a-z]{4}))?
|
|
120
120
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
121
121
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
122
122
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
123
123
|
(?:-(?<privateuse>(?:${e})))?
|
|
124
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var gS=a=>{if(!a?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},St=(a,e)=>{let t=a;t=(0,gl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,SS.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,gl.default)(t,n,(o,u)=>(0,Ba.isNullable)(s)?o:(0,Ba.isNullable)(u)?s:(0,vS.default)(s,parseInt(u,10),"0"))}return t},pn=(a,e)=>{let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(O=>O.textContent?.trim()??""),o=(0,yS.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],p=d?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,g=d?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,y;u&&(y={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:p?new Date(p).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let T,k=s.getAttribute("mediaPresentationDuration"),I=[...s.getElementsByTagName("Period")],$=I.reduce((O,x)=>({...O,[x.id]:x.children}),{}),M=I.reduce((O,x)=>({...O,[x.id]:x.getAttribute("duration")}),{});k?T=gS(k):(0,Sl.default)(M).filter(O=>O).length&&!u?T=(0,Sl.default)(M).reduce((O,x)=>O+(gS(x)??0),0):g&&(T=parseInt(g,10));let _=0,Y=s.getAttribute("profiles")?.split(",")??[];for(let O of I.map(x=>x.id))for(let x of $[O]){let F=x.getAttribute("id")??"id"+(_++).toString(10),P=x.getAttribute("mimeType")??"",R=x.getAttribute("codecs")??"",B=x.getAttribute("contentType")??P?.split("/")[0],me=x.getAttribute("profiles")?.split(",")??[],N=bS(x.getAttribute("lang")??"")??{},re=x.querySelector("Label")?.textContent?.trim()??void 0,ue=x.querySelectorAll("Representation"),ge=x.querySelector("SegmentTemplate"),Ee=x.querySelector("Role")?.getAttribute("value")??void 0,Re=B,Le={id:F,language:N.language,isDefault:Ee==="main",label:re,codecs:R,hdr:Re==="video"&&bl(R),mime:P,representations:[]};for(let ae of ue){let te=ae.getAttribute("lang")??void 0,Fe=re??x.getAttribute("label")??ae.getAttribute("label")??void 0,Ce=ae.querySelector("BaseURL")?.textContent?.trim()??"",xe=new URL(Ce||o,e).toString(),rt=ae.getAttribute("mimeType")??P,Wt=ae.getAttribute("codecs")??R??"",vt;if(B==="text"){let ze=ae.getAttribute("id")||"",zt=N.privateuse?.includes("x-auto")||ze.includes("_auto"),yt=ae.querySelector("SegmentTemplate");if(yt){let yr={representationId:ae.getAttribute("id")??void 0,bandwidth:ae.getAttribute("bandwidth")??void 0},es=parseInt(ae.getAttribute("bandwidth")??"",10)/1e3,ts=parseInt(yt.getAttribute("startNumber")??"",10)??1,$i=parseInt(yt.getAttribute("timescale")??"",10),zn=yt.querySelectorAll("SegmentTimeline S")??[],Mi=yt.getAttribute("media");if(!Mi)continue;let is=[],rs=0,as="",Di=0,Tr=ts,Be=0;for(let dt of zn){let li=parseInt(dt.getAttribute("d")??"",10),at=parseInt(dt.getAttribute("r")??"",10)||0,Yt=parseInt(dt.getAttribute("t")??"",10);Be=Number.isFinite(Yt)?Yt:Be;let ci=li/$i*1e3,Ci=Be/$i*1e3;for(let Tt=0;Tt<at+1;Tt++){let Kt=St(Mi,{...yr,segmentNumber:Tr.toString(10),segmentTime:(Be+Tt*li).toString(10)}),Bi=(Ci??0)+Tt*ci,Er=Bi+ci;Tr++,is.push({time:{from:Bi,to:Er},url:Kt})}Be+=(at+1)*li,rs+=(at+1)*ci}Di=Be/$i*1e3,as=St(Mi,{...yr,segmentNumber:Tr.toString(10),segmentTime:Be.toString(10)});let Ir={time:{from:Di,to:1/0},url:as},Bt={type:"template",baseUrl:xe,segmentTemplateUrl:Mi,initUrl:"",totalSegmentsDurationMs:rs,segments:is,nextSegmentBeyondManifest:Ir,timescale:$i};vt={id:ze,kind:"text",segmentReference:Bt,profiles:[],duration:T,bitrate:es,mime:"",codecs:"",width:0,height:0,isAuto:zt}}else vt={id:ze,isAuto:zt,kind:"text",url:xe}}else{let ze=ae.getAttribute("contentType")??rt?.split("/")[0]??B,zt=x.getAttribute("profiles")?.split(",")??[],yt=parseInt(ae.getAttribute("width")??"",10),yr=parseInt(ae.getAttribute("height")??"",10),es=parseInt(ae.getAttribute("bandwidth")??"",10)/1e3,ts=ae.getAttribute("frameRate")??"",$i=ae.getAttribute("quality")??void 0,zn=ts?mS(ts):void 0,Mi=ae.getAttribute("id")??"id"+(_++).toString(10),is=ze==="video"?`${yr}p`:ze==="audio"?`${es}Kbps`:Wt,rs=`${Mi}@${is}`,as=[...Y,...me,...zt],Di,Tr=ae.querySelector("SegmentBase"),Be=ae.querySelector("SegmentTemplate")??ge;if(Tr){let Bt=ae.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[dt,li]=Bt.split("-").map(Kt=>parseInt(Kt,10)),at={from:dt,to:li},Yt=ae.querySelector("SegmentBase")?.getAttribute("indexRange"),[ci,Ci]=Yt?Yt.split("-").map(Kt=>parseInt(Kt,10)):[],Tt=Yt?{from:ci,to:Ci}:void 0;Di={type:"byteRange",url:xe,initRange:at,indexRange:Tt}}else if(Be){let Bt={representationId:ae.getAttribute("id")??void 0,bandwidth:ae.getAttribute("bandwidth")??void 0},dt=parseInt(Be.getAttribute("timescale")??"",10),li=Be.getAttribute("initialization")??"",at=Be.getAttribute("media"),Yt=parseInt(Be.getAttribute("startNumber")??"",10)??1,ci=St(li,Bt);if(!at)throw new ReferenceError("No media attribute in SegmentTemplate");let Ci=Be.querySelectorAll("SegmentTimeline S")??[],Tt=[],Kt=0,Bi="",Er=0;if(Ci.length){let ss=Yt,pt=0;for(let Vi of Ci){let It=parseInt(Vi.getAttribute("d")??"",10),di=parseInt(Vi.getAttribute("r")??"",10)||0,ns=parseInt(Vi.getAttribute("t")??"",10);pt=Number.isFinite(ns)?ns:pt;let Yn=It/dt*1e3,bv=pt/dt*1e3;for(let os=0;os<di+1;os++){let gv=St(at,{...Bt,segmentNumber:ss.toString(10),segmentTime:(pt+os*It).toString(10)}),Ql=(bv??0)+os*Yn,Sv=Ql+Yn;ss++,Tt.push({time:{from:Ql,to:Sv},url:gv})}pt+=(di+1)*It,Kt+=(di+1)*Yn}Er=pt/dt*1e3,Bi=St(at,{...Bt,segmentNumber:ss.toString(10),segmentTime:pt.toString(10)})}else if((0,Ba.isNonNullable)(T)){let pt=parseInt(Be.getAttribute("duration")??"",10)/dt*1e3,Vi=Math.ceil(T/pt),It=0;for(let di=1;di<Vi;di++){let ns=St(at,{...Bt,segmentNumber:di.toString(10),segmentTime:It.toString(10)});Tt.push({time:{from:It,to:It+pt},url:ns}),It+=pt}Er=It,Bi=St(at,{...Bt,segmentNumber:Vi.toString(10),segmentTime:It.toString(10)})}let mv={time:{from:Er,to:1/0},url:Bi};Di={type:"template",baseUrl:xe,segmentTemplateUrl:at,initUrl:ci,totalSegmentsDurationMs:Kt,segments:Tt,nextSegmentBeyondManifest:mv,timescale:dt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ze||!rt)continue;let Ir={video:"video",audio:"audio",text:"text"}[ze];if(!Ir)continue;Re||=Ir,vt={id:rs,kind:Ir,segmentReference:Di,profiles:as,duration:T,bitrate:es,mime:rt,codecs:Wt,width:yt,height:yr,fps:zn,quality:$i}}Le.language||=te,Le.label||=Fe,Le.mime||=rt,Le.codecs||=Wt,Le.hdr||=Re==="video"&&bl(Wt),Le.representations.push(vt)}if(Re){let ae=r[Re].find(te=>te.id===Le.id);if(ae&&Le.representations.every(te=>te.segmentReference.type==="template"))for(let te of ae.representations){let Ce=Le.representations.find(rt=>rt.id===te.id)?.segmentReference,xe=te.segmentReference;xe.segments.push(...Ce.segments),xe.nextSegmentBeyondManifest=Ce.nextSegmentBeyondManifest}else r[Re].push(Le)}}return{duration:T,streams:r,baseUrls:n,live:y}};var vl=K(Pt(),1);var TS=require("@vkontakte/videoplayer-shared"),IS=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let o=(s?ii(s):void 0)??(0,TS.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},ES=({id:a,bitrate:e})=>({id:a,bitrate:e}),xS=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),wS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),yl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,vl.default)(i.split("."),0),isDefault:r}),Tl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,vl.default)(r.split("."),0)}),Il=a=>"url"in a,et=a=>a.type==="template";var El=require("@vkontakte/videoplayer-shared"),Q=(a,e)=>(0,El.isNonNullable)(a)&&(0,El.isNonNullable)(e)&&a.readyState==="open"&&FR(a,e);function FR(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Va=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new w.ValueSubject(0);this.currentLowLatencySegmentLength$=new w.ValueSubject(0);this.currentSegmentLength$=new w.ValueSubject(0);this.onLastSegment$=new w.ValueSubject(!1);this.fullyBuffered$=new w.ValueSubject(!1);this.playingRepresentation$=new w.ValueSubject(void 0);this.playingRepresentationInit$=new w.ValueSubject(void 0);this.error$=new w.Subject;this.gaps=[];this.subscription=new w.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new oe;this.switchAbortController=new oe;this.destroyAbortController=new oe;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=(0,w.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,w.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Tg(this.sourceBuffer),this.subscription.add((0,w.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add((0,w.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:w.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Q(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,cr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,w.assertNonNullable)(i,"No init buffer for starting representation"),(0,w.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,w.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,w.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,w.isNullable)(s)||(0,w.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,w.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,w.isNonNullable)(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=(0,w.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,w.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,w.isNullable)(s)||(0,w.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,w.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,w.isNonNullable)(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=(0,w.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,fn.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!et(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,w.assertNonNullable)(r);let s=this.segments.get(i);(0,w.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,w.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new oe,(0,w.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,w.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,w.isNullable)(o)||(0,w.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,w.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,w.isNonNullable)(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(){!(0,w.isNullable)(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 oe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,w.isNullable)(e)||(0,w.isNullable)(this.downloadingRepresentationId)||(0,w.isNullable)(this.playingRepresentationId)||(0,w.isNullable)(this.sourceBuffer)||!Q(this.mediaSource,this.sourceBuffer)||(0,w.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,w.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);(0,w.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&cr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,hn.default)(u,r))c="high";else{let d=(0,mr.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,mr.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;(0,w.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,fn.default)(e?.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,fn.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!et(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],o=(0,mr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);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;(0,w.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!et(r))return;let s=this.segments.get(i.id)??[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=St(r.segmentTemplateUrl,{segmentTime:u});s.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(s=>s.time.from<=e&&s.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&&$t&&$t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&$t&&$t(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),s=e.findIndex(({status:p,time:{from:h,to:m}},g)=>{let y=h<=i&&m>=i,T=h>i||y||g===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&h<=i+k||r<k&&m-h>=k||m<=i+k;return(p==="none"||p==="partially_ejected"&&T&&I&&this.sourceBuffer&&Q(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,m)))&&T&&I});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=c||u<=d);p++){let h=n[p];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"){et(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,w.abortable)(o,async function*(){let c=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,w.now)(),!c)return;let d=new DataView(c),p=Mt(t.mime);if(!isFinite(r.segment.time.to)){let g=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(d,g)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Dt(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())et(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,w.abortable)(n,async function*(){let u=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,w.fromEvent)(window,"online").pipe((0,w.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,w.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Dt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(et(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,mr.default)(e,0).byte.from,to:(0,mr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,w.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!et(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,w.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:w.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,hn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!Q(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Q(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,d=l.byte.to-i,p=d-c+1,h=c<r,m=d<=r;if(!h)continue;let g=Mt(o.mime);if(l.status==="downloading"&&m){l.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(y,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-c),u.loadedBytes>u.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),T=u.loadedBytes===p?y:g.parseFeedableSegmentChunk(y);T?.byteLength&&(l.status="partially_fed",u.feedingBytes+=T.byteLength,await this.sourceBufferTaskQueue.append(T,s)&&!s.aborted?(u.fedBytes+=T.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!((0,w.isNullable)(this.sourceBuffer)||!Q(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(De(this.sourceBuffer.buffered,e.segment.time.from,100)&&De(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:w.ErrorCategory.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",Il(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,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=lr(()=>(0,AS.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?(0,w.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,w.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mt(e.mime),r)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&et(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),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:w.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,w.isNullable)(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{if(s>=t)return r;r.push({...u.time}),r=n(r);let l=Il(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,hn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,w.isNullable)(e)?0:Pe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=lr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:w.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,w.isNullable)(this.sourceBuffer)||!Q(this.mediaSource,this.sourceBuffer)||(0,w.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:w.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ni=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var mn=a=>{let e=a.get("X-Delivery-Type"),t=a.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}};var X=require("@vkontakte/videoplayer-shared");var bn=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Sn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.recoverableError$=new X.Subject;this.error$=new X.Subject;this.abortAllController=new oe;this.subscription=new X.Subscription;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ni(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=bn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(gn);return r?(t.log("success",(0,X.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,X.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,X.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=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 F=new URL(l,location.href);F.searchParams.append("bytes",`${i.from}-${i.to}`),l=F.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(l=ni(l));let p=this.abortAllController.signal,h;if(n){let F=new oe;if(h=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{F.abort()}catch(P){gn(P)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{F.abort()}catch(P){gn(P)}p=F.signal}let m=(0,X.now)();d.log("startRequest",(0,X.flattenObject)({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(l,{priority:s,headers:c,signal:p}),y=(0,X.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(y-m),!g.ok||!g.body){h?.unsubscribe();let F=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:F}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){h?.unsubscribe();let F=(0,X.now)(),P={requestStartedAt:m,requestEndedAt:F,duration:F-m};return d.log("endRequest",(0,X.flattenObject)(P)),d.end(),g.arrayBuffer()}let[T,k]=g.body.tee(),I=T.getReader();o&&this.throughputEstimator?.trackStream(k,u);let $=0,M=new Uint8Array(0),_=!1,Y=F=>{h?.unsubscribe(),_=!0,gn(F)},D=(0,X.abortable)(p,async function*({done:F,value:P}){if($===0&&this.lastRequestFirstBytes$.next((0,X.now)()-m),p.aborted){h?.unsubscribe();return}if(!F&&P){let R=new Uint8Array(M.length+P.length);R.set(M),R.set(P,M.length),M=R,$+=P.byteLength,r?.(new DataView(M.buffer),$),yield I?.read().then(D,Y)}}.bind(this));yield I?.read().then(D,Y),h?.unsubscribe();let O=(0,X.now)(),x={failed:_,requestStartedAt:m,requestEndedAt:O,duration:O-m};return _?(d.error("endRequest",(0,X.flattenObject)(x)),d.end(),null):(d.log("endRequest",(0,X.flattenObject)(x)),d.end(),M.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let y=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:y}}.bind(this));this.fetchTemplateRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=mn(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:(0,X.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await lt(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:X.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:X.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:X.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:X.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:X.ErrorCategory.FATAL})}}},gn=a=>{if(!Dt(a))throw a};var Ht=(a,e,t)=>t*e+(1-t)*a,xl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,kS=(a,e,t,i)=>{let r=0,s=t,n=xl(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};var _a=require("@vkontakte/videoplayer-shared"),oi=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 _a.ValueSubject(e.initial),this.debounced$=new _a.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new _e(`raw_${t}`),this.smoothedSeries$=new _e(`smoothed_${t}`),this.reportedSeries$=new _e(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,_a.isNullable)(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 vn=class extends oi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ht(this.slow,e,this.params.emaAlphaSlow),this.fast=Ht(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var yn=class extends oi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=xl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ht(this.emaSmoothed,e,this.params.emaAlpha);let i=kS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Tn=class extends oi{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ht(this.smoothed,t,this.params.emaAlpha):t}};var jt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new vn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new yn({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 Tn({initial:e,label:"liveEdgeDelay",...t})}};var br=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var In=require("@vkontakte/videoplayer-shared");var Oa=class a{constructor(e,t){this.currentRepresentation$=new In.ValueSubject(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(!(0,In.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,o=r.segments[s-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=a.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=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&et(t.segmentReference))}};var xn=K(Pt(),1);var Fa=require("@vkontakte/videoplayer-shared");var PS=(a,{useManagedMediaSource:e,useOldMSEDetection:t})=>{let{containers:i,protocols:r,codecs:s,nativeHlsSupported:n}=j.video,o=(s.h264||s.h265)&&s.aac,u=r.mse&&(!t||!!window.MediaStreamTrack)||r.mms&&e;return a.filter(l=>{switch(l){case"DASH_SEP":return u&&i.mp4&&o;case"DASH_WEBM":return u&&i.webm&&s.vp9&&s.opus;case"DASH_WEBM_AV1":return u&&i.webm&&s.av1&&s.opus;case"DASH_STREAMS":return u&&(i.mp4&&o||i.webm&&(s.vp9||s.av1)&&(s.opus||s.aac));case"DASH_LIVE":return u&&i.mp4&&o;case"DASH_LIVE_CMAF":return u&&i.mp4&&o&&i.cmaf;case"DASH_ONDEMAND":return u&&i.mp4&&o;case"HLS":case"HLS_ONDEMAND":case"HLS_LIVE":case"HLS_LIVE_CMAF":return n;case"MPEG":return i.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return r.webrtc&&r.ws&&s.h264&&(i.mp4||i.webm);default:return(0,Fa.assertNever)(l)}})},En=a=>{let{webmDecodingInfo:e}=j.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,Fa.assertNever)(a)}return[t,i]},RS=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...En(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(j.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...En(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...En(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...En(a),...r,"HLS","HLS_ONDEMAND"];default:(0,Fa.assertNever)(e)}return j.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},LS=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=j.device.isMac&&j.browser.isSafari;if(j.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:(0,Fa.assertNever)(a)}else j.video.nativeHlsSupported&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},wl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],wn=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,xn.default)(t.value.split("."),0)}for(let t of a){let i=(0,xn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,xn.default)(e.value.split("."),0)};var jR=["timeupdate","progress","play","seeked","stalled","waiting"],QR=["timeupdate","progress","loadeddata","playing","seeked"];var An=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new ee("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.currentLiveTextRepresentation$=new v.ValueSubject(null);this.isLive$=new v.ValueSubject(!1);this.isActiveLive$=new v.ValueSubject(!1);this.isLowLatency$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveSeekableDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(0);this.liveStreamStatus$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLatency$=new v.ValueSubject(void 0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.currentStallDuration$=new v.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new v.ValueSubject(0);this.fetcherRecoverableError$=new v.Subject;this.fetcherError$=new v.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new oe;this.initManifest=(0,v.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ye(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:v.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=pn(e??"",this.manifestUrlString)}catch(n){let o=dn(e)??{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&Je()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let d="active";l||(d=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(d)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:p})=>i(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=wn(l);if(c&&(r[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);j.display.isHDR&&d&&p?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,v.fromEvent)(p,"error").pipe((0,v.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Ys():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ir())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Va("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Va("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Oa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Oa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,v.merge)(...QR.map(p=>(0,v.fromEvent)(this.element,p))).pipe((0,v.map)(p=>this.element?Pe(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,v.merge)((0,v.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,v.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,v.now)())),this.subscription.add((0,v.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,v.interval)(1e3).subscribe(h=>{let m=ei(this.manifestUrlString,2);this.manifestUrlString=ye(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,v.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,v.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,v.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||br(this.element,1)})),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,v.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,v.filter)(({isLive:h})=>h),(0,v.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,v.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let y=ei(this.manifestUrlString,2);return(h/2+m+g+y)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,v.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let y=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,k=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-y;if(this.isManualDecreasePlaybackInLive())return;let $=1;Math.abs(I)>T&&($=1+Math.sign(I)*k),br(this.element,$)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let g=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(T=>T.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,y=ei(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,$=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,M=isFinite(h)?h:m,_=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),Y=T<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(Y);let D="none";if(_?D="active_low_latency":this.isLowLatency$.getValue()&&Y?(this.bufferManagers.forEach(O=>O.proceedLowLatencyLive()),D="active_low_latency"):y!==0&&M<k?D="live_forward_buffering":M<k+$&&(D="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),D==="live_forward_buffering"||D==="live_with_target_offset"){let O=p-(k+I),x=this.normolizeLiveOffset(Math.trunc(y+O/g)),F=Math.abs(x-y),P=0;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?P=y:x>0&&F>this.tuning.dashCmafLive.offsetCalculationError&&(P=x),this.manifestUrlString=ye(this.manifestUrlString,P,2)}(D==="live_with_target_offset"||D==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:v.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,v.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,v.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=(0,v.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,v.filterChanged)(),(0,v.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,v.filter)(p=>p));if(this.representationSubscription.add((0,v.merge)(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add((0,v.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{p&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:v.ErrorCategory.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 p=[this.manifest.duration??0,...(0,kl.default)((0,kl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),et(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,v.isNonNullable)(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=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.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.fetcher=new Sn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=jt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){(0,v.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,v.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ye(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(){(0,v.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,v.merge)(...jR.map(e=>(0,v.fromEvent)(this.element,e)),(0,v.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,v.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&De(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=(0,v.now)(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<s&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&r-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let p=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(p).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:v.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=p}else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}this.tracer.log("stallIntervalCallback",(0,v.flattenObject)(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(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),De(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,v.isNullable)(this.element)||(0,v.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,v.isNonNullable)(this.element)&&(0,v.isNonNullable)(this.source)&&(0,v.isNonNullable)(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}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.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=(0,v.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){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};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,v.flattenObject)(i)))}}};var kn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Pn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var DS=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var IS=a=>{if(!a?.startsWith("P"))return;let e=(n,u)=>{let o=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(o)?0:o)*u},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=i?.[1]==="-"?-1:1,s={days:e(i?.[5],r),hours:e(i?.[6],r),minutes:e(i?.[7],r),seconds:e(i?.[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},vt=(a,e)=>{let t=a;t=(0,Tl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,ES.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Tl.default)(t,n,(u,o)=>(0,Ba.isNullable)(s)?u:(0,Ba.isNullable)(o)?s:(0,xS.default)(s,parseInt(o,10),"0"))}return t},pn=(a,e)=>{let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(_=>_.textContent?.trim()??""),u=(0,wS.default)(n,0)??"",o=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),p=s.getElementsByTagName("vk:Attrs")[0],d=p?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=p?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=p?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,g=p?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;o&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:d?new Date(d).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let T,k=s.getAttribute("mediaPresentationDuration"),x=[...s.getElementsByTagName("Period")],L=x.reduce((_,w)=>({..._,[w.id]:w.children}),{}),C=x.reduce((_,w)=>({..._,[w.id]:w.getAttribute("duration")}),{});k?T=IS(k):(0,Il.default)(C).filter(_=>_).length&&!o?T=(0,Il.default)(C).reduce((_,w)=>_+(IS(w)??0),0):g&&(T=parseInt(g,10));let V=0,O=s.getAttribute("profiles")?.split(",")??[];for(let _ of x.map(w=>w.id))for(let w of L[_]){let ee=w.getAttribute("id")??"id"+(V++).toString(10),F=w.getAttribute("mimeType")??"",E=w.getAttribute("codecs")??"",R=w.getAttribute("contentType")??F?.split("/")[0],oe=w.getAttribute("profiles")?.split(",")??[],N=TS(w.getAttribute("lang")??"")??{},re=w.querySelector("Label")?.textContent?.trim()??void 0,le=w.querySelectorAll("Representation"),ge=w.querySelector("SegmentTemplate"),Ee=w.querySelector("Role")?.getAttribute("value")??void 0,Re=R,Le={id:ee,language:N.language,isDefault:Ee==="main",label:re,codecs:E,hdr:Re==="video"&&yl(E),mime:F,representations:[]};for(let ae of le){let te=ae.getAttribute("lang")??void 0,Fe=re??w.getAttribute("label")??ae.getAttribute("label")??void 0,Ce=ae.querySelector("BaseURL")?.textContent?.trim()??"",xe=new URL(Ce||u,e).toString(),rt=ae.getAttribute("mimeType")??F,Wt=ae.getAttribute("codecs")??E??"",yt;if(R==="text"){let ze=ae.getAttribute("id")||"",zt=N.privateuse?.includes("x-auto")||ze.includes("_auto"),Tt=ae.querySelector("SegmentTemplate");if(Tt){let yr={representationId:ae.getAttribute("id")??void 0,bandwidth:ae.getAttribute("bandwidth")??void 0},Za=parseInt(ae.getAttribute("bandwidth")??"",10)/1e3,es=parseInt(Tt.getAttribute("startNumber")??"",10)??1,Di=parseInt(Tt.getAttribute("timescale")??"",10),Yn=Tt.querySelectorAll("SegmentTimeline S")??[],Ci=Tt.getAttribute("media");if(!Ci)continue;let ts=[],is=0,rs="",Bi=0,Tr=es,Be=0;for(let dt of Yn){let li=parseInt(dt.getAttribute("d")??"",10),at=parseInt(dt.getAttribute("r")??"",10)||0,Yt=parseInt(dt.getAttribute("t")??"",10);Be=Number.isFinite(Yt)?Yt:Be;let ci=li/Di*1e3,Vi=Be/Di*1e3;for(let It=0;It<at+1;It++){let Kt=vt(Ci,{...yr,segmentNumber:Tr.toString(10),segmentTime:(Be+It*li).toString(10)}),_i=(Vi??0)+It*ci,Er=_i+ci;Tr++,ts.push({time:{from:_i,to:Er},url:Kt})}Be+=(at+1)*li,is+=(at+1)*ci}Bi=Be/Di*1e3,rs=vt(Ci,{...yr,segmentNumber:Tr.toString(10),segmentTime:Be.toString(10)});let Ir={time:{from:Bi,to:1/0},url:rs},Bt={type:"template",baseUrl:xe,segmentTemplateUrl:Ci,initUrl:"",totalSegmentsDurationMs:is,segments:ts,nextSegmentBeyondManifest:Ir,timescale:Di};yt={id:ze,kind:"text",segmentReference:Bt,profiles:[],duration:T,bitrate:Za,mime:"",codecs:"",width:0,height:0,isAuto:zt}}else yt={id:ze,isAuto:zt,kind:"text",url:xe}}else{let ze=ae.getAttribute("contentType")??rt?.split("/")[0]??R,zt=w.getAttribute("profiles")?.split(",")??[],Tt=parseInt(ae.getAttribute("width")??"",10),yr=parseInt(ae.getAttribute("height")??"",10),Za=parseInt(ae.getAttribute("bandwidth")??"",10)/1e3,es=ae.getAttribute("frameRate")??"",Di=ae.getAttribute("quality")??void 0,Yn=es?yS(es):void 0,Ci=ae.getAttribute("id")??"id"+(V++).toString(10),ts=ze==="video"?`${yr}p`:ze==="audio"?`${Za}Kbps`:Wt,is=`${Ci}@${ts}`,rs=[...O,...oe,...zt],Bi,Tr=ae.querySelector("SegmentBase"),Be=ae.querySelector("SegmentTemplate")??ge;if(Tr){let Bt=ae.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[dt,li]=Bt.split("-").map(Kt=>parseInt(Kt,10)),at={from:dt,to:li},Yt=ae.querySelector("SegmentBase")?.getAttribute("indexRange"),[ci,Vi]=Yt?Yt.split("-").map(Kt=>parseInt(Kt,10)):[],It=Yt?{from:ci,to:Vi}:void 0;Bi={type:"byteRange",url:xe,initRange:at,indexRange:It}}else if(Be){let Bt={representationId:ae.getAttribute("id")??void 0,bandwidth:ae.getAttribute("bandwidth")??void 0},dt=parseInt(Be.getAttribute("timescale")??"",10),li=Be.getAttribute("initialization")??"",at=Be.getAttribute("media"),Yt=parseInt(Be.getAttribute("startNumber")??"",10)??1,ci=vt(li,Bt);if(!at)throw new ReferenceError("No media attribute in SegmentTemplate");let Vi=Be.querySelectorAll("SegmentTimeline S")??[],It=[],Kt=0,_i="",Er=0;if(Vi.length){let as=Yt,pt=0;for(let Oi of Vi){let Et=parseInt(Oi.getAttribute("d")??"",10),di=parseInt(Oi.getAttribute("r")??"",10)||0,ss=parseInt(Oi.getAttribute("t")??"",10);pt=Number.isFinite(ss)?ss:pt;let Kn=Et/dt*1e3,yv=pt/dt*1e3;for(let ns=0;ns<di+1;ns++){let Tv=vt(at,{...Bt,segmentNumber:as.toString(10),segmentTime:(pt+ns*Et).toString(10)}),Yl=(yv??0)+ns*Kn,Iv=Yl+Kn;as++,It.push({time:{from:Yl,to:Iv},url:Tv})}pt+=(di+1)*Et,Kt+=(di+1)*Kn}Er=pt/dt*1e3,_i=vt(at,{...Bt,segmentNumber:as.toString(10),segmentTime:pt.toString(10)})}else if((0,Ba.isNonNullable)(T)){let pt=parseInt(Be.getAttribute("duration")??"",10)/dt*1e3,Oi=Math.ceil(T/pt),Et=0;for(let di=1;di<Oi;di++){let ss=vt(at,{...Bt,segmentNumber:di.toString(10),segmentTime:Et.toString(10)});It.push({time:{from:Et,to:Et+pt},url:ss}),Et+=pt}Er=Et,_i=vt(at,{...Bt,segmentNumber:Oi.toString(10),segmentTime:Et.toString(10)})}let vv={time:{from:Er,to:1/0},url:_i};Bi={type:"template",baseUrl:xe,segmentTemplateUrl:at,initUrl:ci,totalSegmentsDurationMs:Kt,segments:It,nextSegmentBeyondManifest:vv,timescale:dt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ze||!rt)continue;let Ir={video:"video",audio:"audio",text:"text"}[ze];if(!Ir)continue;Re||=Ir,yt={id:is,kind:Ir,segmentReference:Bi,profiles:rs,duration:T,bitrate:Za,mime:rt,codecs:Wt,width:Tt,height:yr,fps:Yn,quality:Di}}Le.language||=te,Le.label||=Fe,Le.mime||=rt,Le.codecs||=Wt,Le.hdr||=Re==="video"&&yl(Wt),Le.representations.push(yt)}if(Re){let ae=r[Re].find(te=>te.id===Le.id);if(ae&&Le.representations.every(te=>te.segmentReference.type==="template"))for(let te of ae.representations){let Ce=Le.representations.find(rt=>rt.id===te.id)?.segmentReference,xe=te.segmentReference;xe.segments.push(...Ce.segments),xe.nextSegmentBeyondManifest=Ce.nextSegmentBeyondManifest}else r[Re].push(Le)}}return{duration:T,streams:r,baseUrls:n,live:S}};var El=Q(gt(),1);var AS=require("@vkontakte/videoplayer-shared"),kS=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?ii(s):void 0)??(0,AS.videoSizeToQuality)({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},PS=({id:a,bitrate:e})=>({id:a,bitrate:e}),RS=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),LS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),xl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,El.default)(i.split("."),0),isDefault:r}),wl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,El.default)(r.split("."),0)}),Al=a=>"url"in a,et=a=>a.type==="template";var kl=require("@vkontakte/videoplayer-shared"),G=(a,e)=>(0,kl.isNonNullable)(a)&&(0,kl.isNonNullable)(e)&&a.readyState==="open"&&HR(a,e);function HR(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Va=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new A.ValueSubject(0);this.currentLowLatencySegmentLength$=new A.ValueSubject(0);this.currentSegmentLength$=new A.ValueSubject(0);this.onLastSegment$=new A.ValueSubject(!1);this.fullyBuffered$=new A.ValueSubject(!1);this.playingRepresentation$=new A.ValueSubject(void 0);this.playingRepresentationInit$=new A.ValueSubject(void 0);this.error$=new A.Subject;this.gaps=[];this.subscription=new A.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ue;this.switchAbortController=new ue;this.destroyAbortController=new ue;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=(0,A.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,A.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new xg(this.sourceBuffer),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),u??={id:"SegmentEjection",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(u)})),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:A.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!G(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,pr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=this.getForwardBufferDuration(u),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<c).catch(p=>{this.handleAsyncError(p,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,A.assertNonNullable)(i,"No init buffer for starting representation"),(0,A.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,A.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,A.isNullable)(s)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(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=(0,A.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,A.isNullable)(s)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(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=(0,A.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,fn.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let c=this.representations.get(o);if(!c||!et(c.segmentReference))return;let p=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,p)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,A.assertNonNullable)(r);let s=this.segments.get(i);(0,A.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,A.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ue,(0,A.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,A.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if((0,A.isNullable)(u)||(0,A.isNullable)(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),(0,A.assertNonNullable)(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();(0,A.isNonNullable)(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,A.isNullable)(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 ue,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,A.isNullable)(e)||(0,A.isNullable)(this.downloadingRepresentationId)||(0,A.isNullable)(this.playingRepresentationId)||(0,A.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||(0,A.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,A.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);(0,A.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),p=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=p)}if(isFinite(this.bufferLimit)&&pr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,hn.default)(o,r))c="high";else{let p=(0,ki.default)(o,0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,ki.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;(0,A.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,fn.default)(e?.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,fn.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!et(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,ki.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,A.assertNonNullable)(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,ki.default)(e,-1)?.time.to:0)||0}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!et(r))return;let s=this.segments.get(i.id)??[],n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=vt(r.segmentTemplateUrl,{segmentTime:o});s.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(s=>s.time.from<=e&&s.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&&$t&&$t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&$t&&$t(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),s=e.findIndex(({status:d,time:{from:h,to:m}},g)=>{let S=h<=i&&m>=i,T=h>i||S||g===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+k||r<k&&m-h>=k||m<=i+k;return(d==="none"||d==="partially_ejected"&&T&&x&&this.sourceBuffer&&G(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,m)))&&T&&x});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=c||o<=p);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=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"){et(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await(0,A.abortable)(u,async function*(){let c=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,c))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,A.now)(),!c)return;let p=new DataView(c),d=Mt(t.mime);if(!isFinite(r.segment.time.to)){let g=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(p,g)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(p,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(p);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Dt(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())et(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,A.abortable)(n,async function*(){let o=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),(0,A.fromEvent)(window,"online").pipe((0,A.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,A.now)(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Dt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(et(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,ki.default)(e,0).byte.from,to:(0,ki.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!et(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)();let p=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,hn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(o.status="partially_fed",u.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){let{segment:l}=o;if(o.representationId!==t)continue;if(s.aborted){await n();continue}let c=l.byte.from-i,p=l.byte.to-i,d=p-c+1,h=c<r,m=p<=r;if(!h)continue;let g=Mt(u.mime);if(l.status==="downloading"&&m){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,d);await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-c),o.loadedBytes>o.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+o.feedingBytes,o.loadedBytes-o.feedingBytes),T=o.loadedBytes===d?S:g.parseFeedableSegmentChunk(S);T?.byteLength&&(l.status="partially_fed",o.feedingBytes+=T.byteLength,await this.sourceBufferTaskQueue.append(T,s)&&!s.aborted?(o.fedBytes+=T.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}onSegmentFullyAppended(e,t){if(!((0,A.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(De(this.sourceBuffer.buffered,e.segment.time.from,100)&&De(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:A.ErrorCategory.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",Al(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,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=dr(()=>(0,$S.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?(0,A.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mt(e.mime),r)).then(async u=>{if(!u)return;let{init:o,dataView:l,segments:c}=u,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let d=c;this.isLive&&et(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:A.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});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||!G(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,A.isNullable)(e))return!1;let r=[],s=0,n=o=>{o.sort((c,p)=>c.from-p.from);let l=[o[0]];for(let c=1;c<o.length;c++){let{from:p,to:d}=o[c],h=l[l.length-1];h.to>=p?h.to=Math.max(h.to,d):l.push(o[c])}return l},u=o=>{if(s>=t)return r;r.push({...o.time}),r=n(r);let l=Al(o)?o.size??0:o.byte.to-o.byte.from;s+=l};for(let o of this.segments.values())for(let l of o){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,p=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||p)&&l.status==="fed"&&u(l)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let l=this.sourceBuffer.buffered.start(o)*1e3,c=this.sourceBuffer.buffered.end(o)*1e3,p=0;for(let d of this.segments.values())for(let h of d)(0,hn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&p++;if(p===this.segments.size){let d={time:{from:l,to:c},url:"",status:"none"};u(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+o&&c.status==="fed"&&u(c)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!G(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||!G(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||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,A.isNullable)(e)?0:Pe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,u=this.sourceBuffer.buffered.end(s)*1e3;if(!(u<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&u>=i.time.to){r=void 0;break}u>i.time.from&&u<i.time.to&&(r.from=u),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=dr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:A.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,A.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||(0,A.isNullable)(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=e.some(c=>c.from-t<=n&&c.to+t>=u),l=e.filter(c=>n>=c.from&&n<c.to-t||u>c.from+t&&u<=c.to);o||(l.length===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:A.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var ni=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var mn=a=>{let e=a.get("X-Delivery-Type"),t=a.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}};var K=require("@vkontakte/videoplayer-shared");var bn=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Sn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new K.ValueSubject(void 0);this.lastConnectionReused$=new K.ValueSubject(void 0);this.lastRequestFirstBytes$=new K.ValueSubject(void 0);this.recoverableError$=new K.Subject;this.error$=new K.Subject;this.abortAllController=new ue;this.subscription=new K.Subscription;this.fetchManifest=(0,K.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ni(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=bn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(gn);return r?(t.log("success",(0,K.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,K.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,K.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let c=e,p=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(c,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),c=E.toString();break}default:(0,K.assertNever)(t)}this.requestQuic&&(c=ni(c));let h=this.abortAllController.signal,m;if(n){let E=new ue;if(m=(0,K.merge)((0,K.fromEvent)(this.abortAllController.signal,"abort"),(0,K.fromEvent)(n,"abort")).subscribe(()=>{try{E.abort()}catch(R){gn(R)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(R){gn(R)}h=E.signal}let g=(0,K.now)();d.log("startRequest",(0,K.flattenObject)({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:g}));let S=yield this.doFetch(c,{priority:s,headers:p,signal:h}),T=(0,K.now)();if(!S)return d.error("error",{message:"No response in request"}),d.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(T-g),!S.ok||!S.body){m?.unsubscribe();let E=`Fetch error ${S.status}: ${S.statusText}`;return d.error("error",{message:E}),d.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!u){m?.unsubscribe();let E=(0,K.now)(),R={requestStartedAt:g,requestEndedAt:E,duration:E-g};return d.log("endRequest",(0,K.flattenObject)(R)),d.end(),S.arrayBuffer()}let k=S.body;if(u){let E;[k,E]=S.body.tee(),this.throughputEstimator?.trackStream(E,o)}let x=k.getReader(),L,C=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(C)&&(L=C),!L&&i&&(L=i.to-i.from+1);let V=0,O=L?new Uint8Array(L):new Uint8Array(0),D=!1,_=E=>{m?.unsubscribe(),D=!0,gn(E)},w=(0,K.abortable)(h,async function*({done:E,value:R}){if(V===0&&this.lastRequestFirstBytes$.next((0,K.now)()-g),h.aborted){m?.unsubscribe();return}if(!E&&R){if(l&&L)O.set(R,V),V+=R.byteLength;else{let oe=new Uint8Array(O.length+R.length);oe.set(O),oe.set(R,O.length),O=oe,V+=R.byteLength}r?.(new DataView(O.buffer),V),yield x?.read().then(w,_)}}.bind(this));yield x?.read().then(w,_),m?.unsubscribe();let ee=(0,K.now)(),F={failed:D,requestStartedAt:g,requestEndedAt:ee,duration:ee-g};return D?(d.error("endRequest",(0,K.flattenObject)(F)),d.end(),null):(d.log("endRequest",(0,K.flattenObject)(F)),d.end(),O.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,K.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(c,s))),n=Math.min(n,0);let p=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!p)return null;let d=new DataView(p,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(o)g=new DataView(p,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let S=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(p),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,K.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=mn(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:(0,K.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){let i=await lt(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:K.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:K.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:K.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:K.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:K.ErrorCategory.FATAL})}}},gn=a=>{if(!Dt(a))throw a};var Ht=(a,e,t)=>t*e+(1-t)*a,Pl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,MS=(a,e,t,i)=>{let r=0,s=t,n=Pl(a,e),u=e<i?e:i;for(let o=0;o<u;o++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===u};var _a=require("@vkontakte/videoplayer-shared"),oi=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 _a.ValueSubject(e.initial),this.debounced$=new _a.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new _e(`raw_${t}`),this.smoothedSeries$=new _e(`smoothed_${t}`),this.reportedSeries$=new _e(`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 u=0;u<this.pastMeasures.length;u++)this.pastMeasures[u]!==void 0&&(t+=(this.pastMeasures[u]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&((0,_a.isNullable)(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 vn=class extends oi{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ht(this.slow,e,this.params.emaAlphaSlow),this.fast=Ht(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var yn=class extends oi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Pl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ht(this.emaSmoothed,e,this.params.emaAlpha);let i=MS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Tn=class extends oi{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ht(this.smoothed,t,this.params.emaAlpha):t}};var jt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new vn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new yn({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 Tn({initial:e,label:"liveEdgeDelay",...t})}};var gr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var In=require("@vkontakte/videoplayer-shared");var Oa=class a{constructor(e,t){this.currentRepresentation$=new In.ValueSubject(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(!(0,In.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&et(t.segmentReference))}};var xn=Q(gt(),1),wn=require("@vkontakte/videoplayer-shared");var En=a=>{let{webmDecodingInfo:e}=j.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:(0,wn.assertNever)(a)}return[t,i]},DS=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...En(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(j.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...En(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...En(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...En(a),...r,"HLS","HLS_ONDEMAND"];default:(0,wn.assertNever)(e)}return j.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},CS=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],u,o=j.device.isMac&&j.browser.isSafari;if(j.device.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{u=s;break}case"hls":case"mpeg":{u=n;break}default:(0,wn.assertNever)(a)}else j.video.nativeHlsSupported&&!o?u=n:o?u=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:u=s;return t?["WEB_RTC_LIVE",...u]:[...u,"WEB_RTC_LIVE"]},Rl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],An=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,xn.default)(t.value.split("."),0)}for(let t of a){let i=(0,xn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,xn.default)(e.value.split("."),0)};var zR=["timeupdate","progress","play","seeked","stalled","waiting"],YR=["timeupdate","progress","loadeddata","playing","seeked"];var kn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new y.Subscription;this.representationSubscription=new y.Subscription;this.state$=new Z("none");this.currentVideoRepresentation$=new y.ValueSubject(void 0);this.currentVideoRepresentationInit$=new y.ValueSubject(void 0);this.currentAudioRepresentation$=new y.ValueSubject(void 0);this.currentVideoSegmentLength$=new y.ValueSubject(0);this.currentAudioSegmentLength$=new y.ValueSubject(0);this.error$=new y.Subject;this.lastConnectionType$=new y.ValueSubject(void 0);this.lastConnectionReused$=new y.ValueSubject(void 0);this.lastRequestFirstBytes$=new y.ValueSubject(void 0);this.currentLiveTextRepresentation$=new y.ValueSubject(null);this.isLive$=new y.ValueSubject(!1);this.isActiveLive$=new y.ValueSubject(!1);this.isLowLatency$=new y.ValueSubject(!1);this.liveDuration$=new y.ValueSubject(0);this.liveSeekableDuration$=new y.ValueSubject(0);this.liveAvailabilityStartTime$=new y.ValueSubject(0);this.liveStreamStatus$=new y.ValueSubject(void 0);this.bufferLength$=new y.ValueSubject(0);this.liveLatency$=new y.ValueSubject(void 0);this.liveLoadBufferLength$=new y.ValueSubject(0);this.livePositionFromPlayer$=new y.ValueSubject(0);this.currentStallDuration$=new y.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new y.ValueSubject(0);this.fetcherRecoverableError$=new y.Subject;this.fetcherError$=new y.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new y.Subject;this.gapWatchdogActive=!1;this.destroyController=new ue;this.initManifest=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ye(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:y.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,y.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:y.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=pn(e??"",this.manifestUrlString)}catch(n){let u=cn(e)??{id:"ManifestParsing",category:y.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(u)}if(!t)return null;let i=(n,u,o)=>!!(this.element?.canPlayType?.(u)&&Je()?.isTypeSupported?.(`${u}; codecs="${o}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:u,streamIsUnpublished:o,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((u-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";l||(p=o?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let o=t.streams[n].filter(({mime:p,codecs:d})=>i(n,p,d)),l=new Set(o.map(({codecs:p})=>p)),c=An(l);if(c&&(r[n]=o.filter(({codecs:p})=>p.startsWith(c))),n==="video"){let p=this.tuning.preferHDR,d=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);j.display.isHDR&&p&&d?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,y.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,y.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,y.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,y.assertNonNullable)(this.manifest),(0,y.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add((0,y.fromEvent)(d,"error").pipe((0,y.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Gs():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&rr())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},u=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new Va("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],(0,y.isNonNullable)(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Va("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}Oa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Oa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,y.merge)(...YR.map(d=>(0,y.fromEvent)(this.element,d))).pipe((0,y.map)(d=>this.element?Pe(this.element.buffered,this.element.currentTime*1e3):0),(0,y.filterChanged)(),(0,y.tap)(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,y.merge)((0,y.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,y.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,y.now)())),this.subscription.add((0,y.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,y.interval)(1e3).subscribe(h=>{let m=ei(this.manifestUrlString,2);this.manifestUrlString=ye(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,y.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,y.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,y.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||gr(this.element,1)})),this.representationSubscription.add((0,y.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,y.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,y.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,y.filter)(({isLive:h})=>h),(0,y.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,y.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let S=ei(this.manifestUrlString,2);return(h/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,y.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,k=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let L=1;Math.abs(x)>T&&(L=1+Math.sign(x)*k),gr(this.element,L)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let g=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(T=>T.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add((0,y.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,y.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=ei(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,L=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,C=isFinite(h)?h:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=T<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let D="none";if(V?D="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),D="active_low_latency"):S!==0&&C<k?D="live_forward_buffering":C<k+L&&(D="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),D==="live_forward_buffering"||D==="live_with_target_offset"){let _=d-(k+x),w=this.normolizeLiveOffset(Math.trunc(S+_/g)),ee=Math.abs(w-S),F=0;!h||ee<=this.tuning.dashCmafLive.offsetCalculationError?F=S:w>0&&ee>this.tuning.dashCmafLive.offsetCalculationError&&(F=w),this.manifestUrlString=ye(this.manifestUrlString,F,2)}(D==="live_with_target_offset"||D==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:y.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,y.merge)(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe((0,y.map)(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=(0,y.merge)(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe((0,y.map)(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),p=(0,y.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,y.filterChanged)(),(0,y.map)(({allBuffersFull:d,someBufferEnded:h})=>d&&h),(0,y.filter)(d=>d));if(this.representationSubscription.add((0,y.merge)(this.forceEnded$,p).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:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add((0,y.merge)(...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:y.ErrorCategory.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,$l.default)((0,$l.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),et(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&(0,y.isNonNullable)(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=(0,y.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:y.ErrorCategory.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.fetcher=new Sn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=jt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){(0,y.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,y.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ye(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(){(0,y.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,y.merge)(...zR.map(e=>(0,y.fromEvent)(this.element,e)),(0,y.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:y.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,y.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,y.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&De(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element||this.source?.readyState!=="open")return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},r=(0,y.now)(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,o=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=o<s&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&l<s&&r-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||p)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%2e3===0){let d=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(d).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:y.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=d}else{let d=this.element.currentTime*1e3;this.videoBufferManager?.maintain(d),this.audioBufferManager?.maintain(d),i.position=d}this.tracer.log("stallIntervalCallback",(0,y.flattenObject)(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,y.interval)(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:y.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,y.assertNonNullable)(this.element),(0,y.assertNonNullable)(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),De(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,y.isNullable)(this.element)||(0,y.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,y.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,y.isNonNullable)(this.element)&&(0,y.isNonNullable)(this.source)&&(0,y.isNonNullable)(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}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.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=(0,y.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.error$.subscribe(e("error")))}isManualDecreasePlaybackInLive(){if(!this.element||!this.isLive$.getValue())return!1;let e=1-this.element.playbackRate;return Number(e.toFixed(2))>Number(this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup.toFixed(2))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){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};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let o of u.gaps)u.playingRepresentation$.getValue()===o.representation&&o.from-n<=r&&o.to+n>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?s.push(1/0):s.push(o.to));if(s.length){let u=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,i={...i,gapEnds:s,jumpTo:u,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,y.flattenObject)(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var Pn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Rn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=i??this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var _S=`attribute vec2 a_vertex;
|
|
125
125
|
attribute vec2 a_texel;
|
|
126
126
|
|
|
127
127
|
varying vec2 v_texel;
|
|
@@ -132,7 +132,7 @@ void main(void) {
|
|
|
132
132
|
// save texel vector to pass to fragment shader
|
|
133
133
|
v_texel = a_texel;
|
|
134
134
|
}
|
|
135
|
-
`;var
|
|
135
|
+
`;var OS=`#ifdef GL_ES
|
|
136
136
|
precision highp float;
|
|
137
137
|
precision highp int;
|
|
138
138
|
#else
|
|
@@ -175,6 +175,6 @@ void main(void) {
|
|
|
175
175
|
// sample using new coordinates
|
|
176
176
|
gl_FragColor = texture2D(u_texture, tc);
|
|
177
177
|
}
|
|
178
|
-
`;var gr=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 kn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Pn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(DS,this.gl.VERTEX_SHADER),i=this.createShader(CS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,p=t+r;return[s,n,o,u,l,c,d,p]}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}};var pe=require("@vkontakte/videoplayer-shared");var Rn="stalls_manager_metrics",Pl="stalls_manager_abr_params",BS="stalls_manager_default_tuning_abr_params",Rl=class{constructor(){this.isSeeked$=new pe.ValueSubject(!1);this.isBuffering$=new pe.ValueSubject(!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 pe.Subscription;this.severeStallOccurred$=new pe.ValueSubject(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(Pl):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,pe.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,pe.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(BS)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(Pl),this.setStoredData(BS,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Rn,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((o,u)=>o+u.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,o)=>n+o.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Rn,[]),this.setStoredData(Pl,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:o,stallsMetricsHistoryLength:u}=this.tuning,l=n*Math.min(t/(o*u),1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){return JSON.parse(pe.safeStorage.get(e)??t)}setStoredData(e,t){pe.safeStorage.set(e,JSON.stringify(t))}removeStoredData(e){pe.safeStorage.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Rn,"[]"),r=t/e,s=i.length?Ht(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Rn,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((0,pe.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,pe.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,pe.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if((0,pe.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=(0,pe.now)(),d=r&&this.currentStallsCount>=r,p=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||p)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,pe.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&u>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,pe.now)()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},Ln=Rl;var Ge=require("@vkontakte/videoplayer-shared"),$n=class{constructor(){this.subscription=new Ge.Subscription;this.pipSize$=new Ge.ValueSubject(void 0);this.videoSize$=new Ge.ValueSubject(void 0);this.elementSize$=new Ge.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Ge.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,Ge.observeElementSize)(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((0,Ge.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Ge.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var ki=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new ee("stopped");this.observableVideo=null;this.droppedFramesManager=new nr;this.stallsManager=new Ln;this.elementSizeManager=new $n;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ri;this.audioTrackSwitchHistory=new ri;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.hostname$.next(void 0),this.videoState.setState("stopped"),V(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"),V(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&V(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"&&V(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&V(this.params.desiredState.playbackState,"paused");return;default:return(0,G.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new gr(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 ot(e.source.url),this.params=e,this.video=Ue(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(Me(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 An({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,G.isNullable)(this.observableVideo)&&(this.observableVideo=je(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:G.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,G.filter)(l=>!!l.length),(0,G.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,G.map)(l=>l.to.state!=="none"),(0,G.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,G.filter)(G.isNonNullable),(0,G.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,G.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(kt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(ut(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),V(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),V(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if((0,G.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push(yl(h));let m=[];for(let g of h.representations){let y=ES(g);m.push(y),this.audioTracksMap.set(y,{stream:h,representation:g})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push(Tl(p));let h=[];for(let m of p.representations){let g=IS({...m,streamId:p.id});g&&(h.push(g),this.videoTracksMap.set(g,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=xS(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add((0,G.merge)(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$,(0,G.fromEvent)(this.video,"progress")).pipe((0,G.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,VS.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=[...this.videoTracksMap.keys()].find(y=>this.videoTracksMap.get(y)?.representation.id===p.id);(0,G.isNonNullable)(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")await this.player.initRepresentations(p.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",p.id),h){let y=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,y)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,G.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(Tl(p))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,G.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:p}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===p.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(yl(p))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}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 o=t.playbackState.stateChangeStarted$.pipe((0,G.map)(({to:l})=>l==="ready"),(0,G.filterChanged)());this.subscription.add((0,G.merge)(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,G.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add((0,G.merge)(o,this.player.state$.stateChangeEnded$,(0,G.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=(0,G.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,G.observableFrom)(["init"])).pipe((0,G.debounce)(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ea:Zr,t=this.params.tuning.useNewAutoSelectVideoTrack?nn:sn,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:an,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:x})=>x===o),c=s.currentVideoTrack$.getValue(),d=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!d)return;let p=[...this.videoStreamsMap.keys()].find(({id:x})=>x===d.id),h=p&&this.videoStreamsMap.get(p);if(!h)return;let m=Pe(this.video.buffered,this.video.currentTime*1e3),g;this.player.isActiveLive$.getValue()?g=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?g=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:g=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let y=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,T=Math.min(m/Math.min(g,y||1/0),1),k=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),I=[...this.audioStreamsMap.keys()].find(({id:x})=>x===k?.id)??this.audioStreamsMap.keys().next().value,$=0;if(I){if(l&&!n){let x=e(l,h,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);$=Math.max($,x?.bitrate??-1/0)}if(c){let x=e(c,h,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);$=Math.max($,x?.bitrate??-1/0)}}let M=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:$,forwardBufferHealth:T,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),_=n?M??l:l??M,Y=I&&t(_,h,this.audioStreamsMap.get(I)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:T,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),D=this.videoTracksMap.get(_)?.representation,O=Y&&this.audioTracksMap.get(Y)?.representation;if(D&&O)return[D,O];if(D&&!O&&this.audioTracksMap.size===0)return[D,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:G.ErrorCategory.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),qe(this.video),this.tracer.end()}};var Na=class extends ki{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)}};var le=require("@vkontakte/videoplayer-shared");var Ua=class extends ki{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new le.ValueSubject(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe((0,le.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,le.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,le.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,le.filter)(o=>(0,le.isNonNullable)(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add((0,le.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,le.merge)(i.playbackRateState$,new le.ValueSubject(1))}).pipe((0,le.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||(0,le.isNullable)(l)||(e=o-l)})).add((0,le.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,le.merge)(i.playbackRateState$,new le.ValueSubject(1))}).pipe((0,le.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||(0,le.isNullable)(o)||(0,le.isNullable)(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=wS(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var W=require("@vkontakte/videoplayer-shared");var Vl=K(oa(),1);var S=require("@vkontakte/videoplayer-shared");var Vn=K(st(),1),Sr=K(Pt(),1),_n=K(oa(),1);var QS=K(Hs(),1);var ui=require("@vkontakte/videoplayer-shared");var YR=18,_S=!1;try{_S=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=YR}catch(a){console.error(a)}var Ll=class{constructor(e){this.bufferFull$=new ui.Subject;this.error$=new ui.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:ui.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};_S&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=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:ui.ErrorCategory.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:(0,ui.assertNever)(t)}}},OS=Ll;var A=require("@vkontakte/videoplayer-shared");var $l=K(Pt(),1);var Mn=require("@vkontakte/videoplayer-shared"),FS=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let o=(s?ii(s):void 0)??(0,Mn.videoSizeToQuality)({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},NS=({id:a,bitrate:e})=>({id:a,bitrate:e}),US=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),qS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Ml=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,$l.default)(i.split("."),0),isDefault:r}),Dl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,$l.default)(r.split("."),0)}),Cl=a=>"url"in a,tt=a=>a.type==="template";var HS=a=>{a.sort((t,i)=>t.from-i.from);let e=[a[0]];for(let t=1;t<a.length;t++){let{from:i,to:r}=a[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(a[t])}return e},Pi=(a,e)=>{for(let t of a)if(e(t))return t;return null},jS=a=>{let e=!1,t=(0,Mn.throttleFn)(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};var Bn=require("@vkontakte/videoplayer-shared");var Dn=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var Cn=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Bn.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,Bn.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!Q(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Dn(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],n=t[i],o=t[i+1];if(n>r||o<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var qa=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new A.ValueSubject(0);this.currentLowLatencySegmentLength$=new A.ValueSubject(0);this.currentSegmentLength$=new A.ValueSubject(0);this.onLastSegment$=new A.ValueSubject(!1);this.fullyBuffered$=new A.ValueSubject(!1);this.playingRepresentation$=new A.ValueSubject(void 0);this.playingRepresentationInit$=new A.ValueSubject(void 0);this.error$=new A.Subject;this.gaps=[];this.subscription=new A.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new oe;this.switchAbortController=new oe;this.destroyAbortController=new oe;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=(0,A.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,A.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new OS(this.sourceBuffer),this.sourceBufferBufferedDiff=new Cn(this.mediaSource,this.sourceBuffer),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,A.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:A.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Q(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,cr(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Pe(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,A.assertNonNullable)(i,"No init buffer for starting representation"),(0,A.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,A.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,A.isNullable)(s)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(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=(0,A.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!Q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,A.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,A.isNullable)(s)||(0,A.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,A.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,A.isNonNullable)(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=(0,A.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,_n.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!tt(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,A.assertNonNullable)(r);let s=this.segments.get(i);(0,A.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,A.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!Q(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new oe,(0,A.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,A.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if((0,A.isNullable)(o)||(0,A.isNullable)(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),(0,A.assertNonNullable)(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();(0,A.isNonNullable)(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(){!(0,A.isNullable)(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 oe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,A.isNullable)(e)||(0,A.isNullable)(this.downloadingRepresentationId)||(0,A.isNullable)(this.playingRepresentationId)||(0,A.isNullable)(this.sourceBuffer)||!Q(this.mediaSource,this.sourceBuffer)||(0,A.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,A.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);(0,A.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Pe(this.sourceBuffer.buffered,e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&cr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=Pe(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(p=>{this.handleAsyncError(p,"pruneBuffer")});return}let u=null;if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Vn.default)(u,r))c="high";else{let d=(0,Sr.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u?.length&&Pe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Sr.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Pe(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;(0,A.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,_n.default)(e?.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,_n.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!tt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],o=(0,Sr.default)(n,-1)?.time.to??0,u=r?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);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;(0,A.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!tt(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),l=St(r.segmentTemplateUrl,{segmentTime:u});s.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(s=>s.time.from<=e&&s.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&&$t&&$t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&$t&&$t(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),s=e.findIndex(({status:p,time:{from:h,to:m}},g)=>{let y=h<=i&&m>=i,T=h>i||y||g===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),I=this.preloadOnly&&h<=i+k||r<k&&m-h>=k||m<=i+k;return(p==="none"||p==="partially_ejected"&&T&&I&&this.sourceBuffer&&Q(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,m)))&&T&&I});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,o=0,u=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let p=s;p<n.length&&(o<=c||u<=d);p++){let h=n[p];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"){tt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await(0,A.abortable)(o,async function*(){let c=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=(0,A.now)(),!c)return;let d=new DataView(c),p=Mt(t.mime);if(!isFinite(r.segment.time.to)){let g=t.segmentReference.timescale;r.segment.time.to=p.getChunkEndTime(d,g)}u&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Dt(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())tt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,A.abortable)(n,async function*(){let u=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),(0,A.fromEvent)(window,"online").pipe((0,A.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=(0,A.now)(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Dt(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(tt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Sr.default)(e,0).byte.from,to:(0,Sr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)(),await this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!tt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:A.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Vn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!Q(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!Q(this.mediaSource,this.sourceBuffer))return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){if(u.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=u,c=l.byte.from-i,d=l.byte.to-i,p=d-c+1,h=c<r,m=d<=r;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),y=u.loadedBytes===p?g:Mt(o.mime).parseFeedableSegmentChunk(g);y?.byteLength&&(l.status="partially_fed",u.feedingBytes+=y.byteLength,await this.sourceBufferTaskQueue.append(y,s)&&!s.aborted?(u.fedBytes+=y.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!((0,A.isNullable)(this.sourceBuffer)||!Q(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(De(this.sourceBuffer.buffered,e.segment.time.from,100)&&De(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:A.ErrorCategory.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",Cl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=lr(()=>(0,QS.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?(0,A.abortable)(this.destroyAbortController.signal,async function*(){let o=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mt(e.mime),r)).then(o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&tt(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),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:A.ErrorCategory.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,A.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=o=>{if(s>=t)return;r.push({...o.time});let u=Cl(o)?o.size??0:o.byte.to-o.byte.from;s+=u};for(let o of this.segments.values())for(let u of o){let l=u.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=u.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&u.status==="fed"&&n(u)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let u=this.sourceBuffer.buffered.start(o)*1e3,l=this.sourceBuffer.buffered.end(o)*1e3,c=0;for(let d of this.segments.values())for(let p of d)(0,Vn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(u)&&Math.round(p.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let d={time:{from:u,to:l},url:"",status:"none"};n(d)}}if(r.length&&i){let o=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let u of this.segments.values())for(let l of u)l.time.from>=e+o&&l.status==="fed"&&n(l)}return r.length?(r=HS(r),(await Promise.all(r.map(u=>this.sourceBufferTaskQueue.remove(u.from,u.to)))).reduce((u,l)=>u||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getBufferedTo(){return!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length?null:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}getForwardBufferDuration(e=this.getCurrentPosition()){return!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,A.isNullable)(e)?0:Pe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let n=Math.round(s.from),o=Math.round(s.to);for(let u=0;u<i.length;u++)if(n>=Math.round(i.start(u)*1e3)&&o<=Math.round(i.end(u)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,o=i.end(s)*1e3;if(!(o<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&o>=t.time.to){r=void 0;break}o>t.time.from&&o<t.time.to&&(r.from=o),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Q(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=lr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:A.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,A.isNullable)(this.sourceBuffer)||!Q(this.mediaSource,this.sourceBuffer)||(0,A.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Dn(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=!1,l=0;for(let c=0;c<e.length;c+=2){let d=e[c],p=e[c+1];u||(u=d-t<=n&&p+t>=o),(n>=d&&n<p-t||o>d+t&&o<=p)&&(l+=1)}u||(l===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:A.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var J=require("@vkontakte/videoplayer-shared");var Fn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new J.ValueSubject(void 0);this.lastConnectionReused$=new J.ValueSubject(void 0);this.lastRequestFirstBytes$=new J.ValueSubject(void 0);this.recoverableError$=new J.Subject;this.error$=new J.Subject;this.abortAllController=new oe;this.subscription=new J.SubscriptionRemovable;this.fetchManifest=(0,J.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ni(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=bn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(On);return r?(t.log("success",(0,J.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,J.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,J.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=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 P=new URL(l,location.href);P.searchParams.append("bytes",`${i.from}-${i.to}`),l=P.toString();break}default:(0,J.assertNever)(t)}this.requestQuic&&(l=ni(l));let p=this.abortAllController.signal,h;if(n){let P=new oe;if(h=(0,J.merge)((0,J.fromEvent)(this.abortAllController.signal,"abort"),(0,J.fromEvent)(n,"abort")).subscribe(()=>{try{P.abort()}catch(R){On(R)}}),this.subscription.add(h),this.abortAllController.signal.aborted||n.aborted)try{P.abort()}catch(R){On(R)}p=P.signal}let m=(0,J.now)();d.log("startRequest",(0,J.flattenObject)({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let g=yield this.doFetch(l,{priority:s,headers:c,signal:p}),y=(0,J.now)();if(!g)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(h),null;if(this.throughputEstimator?.addRawRtt(y-m),!g.ok||!g.body){this.unsubscribeAbortSubscription(h);let P=`Fetch error ${g.status}: ${g.statusText}`;return d.error("error",{message:P}),d.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){this.unsubscribeAbortSubscription(h);let P=(0,J.now)(),R={requestStartedAt:m,requestEndedAt:P,duration:P-m};return d.log("endRequest",(0,J.flattenObject)(R)),d.end(),g.arrayBuffer()}let T=g.body;if(o){let P;[T,P]=g.body.tee(),this.throughputEstimator?.trackStream(P,u)}let k=T.getReader(),I,$=parseInt(g.headers.get("content-length")??"",10);Number.isFinite($)&&(I=$),!I&&i&&(I=i.to-i.from+1);let M=0,_=I?new Uint8Array(I):new Uint8Array(0),Y=!1,D=P=>{this.unsubscribeAbortSubscription(h),Y=!0,On(P)},O=(0,J.abortable)(p,async function*({done:P,value:R}){if(M===0&&this.lastRequestFirstBytes$.next((0,J.now)()-m),p.aborted){this.unsubscribeAbortSubscription(h);return}if(!P&&R){if(I)_.set(R,M),M+=R.byteLength;else{let B=new Uint8Array(_.length+R.length);B.set(_),B.set(R,_.length),_=B,M+=R.byteLength}r?.(new DataView(_.buffer),M),yield k?.read().then(O,D)}}.bind(this));yield k?.read().then(O,D),this.unsubscribeAbortSubscription(h);let x=(0,J.now)(),F={failed:Y,requestStartedAt:m,requestEndedAt:x,duration:x-m};return Y?(d.error("endRequest",(0,J.flattenObject)(F)),d.end(),null):(d.log("endRequest",(0,J.flattenObject)(F)),d.end(),_.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,J.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,r-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(u)g=new DataView(d,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let y=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(d),segments:y}}.bind(this));this.fetchTemplateRepresentation=(0,J.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=mn(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:(0,J.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await lt(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:J.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:J.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:J.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:J.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:J.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},On=a=>{if(!Dt(a))throw a};var Nn=require("@vkontakte/videoplayer-shared");var Ha=class a{constructor(e,t){this.currentRepresentation$=new Nn.ValueSubject(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(!(0,Nn.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,o=r.segments[s-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=a.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=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&tt(t.segmentReference))}};var JR=["progress","play","seeked","stalled","waiting"],ZR=["timeupdate","progress","loadeddata","playing","seeked"];var Un=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new S.Subscription;this.representationSubscription=new S.Subscription;this.state$=new ee("none");this.currentVideoRepresentation$=new S.ValueSubject(void 0);this.currentVideoRepresentationInit$=new S.ValueSubject(void 0);this.currentAudioRepresentation$=new S.ValueSubject(void 0);this.currentVideoSegmentLength$=new S.ValueSubject(0);this.currentAudioSegmentLength$=new S.ValueSubject(0);this.error$=new S.Subject;this.lastConnectionType$=new S.ValueSubject(void 0);this.lastConnectionReused$=new S.ValueSubject(void 0);this.lastRequestFirstBytes$=new S.ValueSubject(void 0);this.currentLiveTextRepresentation$=new S.ValueSubject(null);this.isLive$=new S.ValueSubject(!1);this.isActiveLive$=new S.ValueSubject(!1);this.isLowLatency$=new S.ValueSubject(!1);this.liveDuration$=new S.ValueSubject(0);this.liveSeekableDuration$=new S.ValueSubject(0);this.liveAvailabilityStartTime$=new S.ValueSubject(0);this.liveStreamStatus$=new S.ValueSubject(void 0);this.bufferLength$=new S.ValueSubject(0);this.liveLatency$=new S.ValueSubject(void 0);this.liveLoadBufferLength$=new S.ValueSubject(0);this.livePositionFromPlayer$=new S.ValueSubject(0);this.currentStallDuration$=new S.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new S.ValueSubject(0);this.fetcherRecoverableError$=new S.Subject;this.fetcherError$=new S.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new S.Subject;this.gapWatchdogActive=!1;this.destroyController=new oe;this.initManifest=(0,S.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ye(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:S.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,S.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:S.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=pn(e??"",this.manifestUrlString)}catch(n){let o=dn(e)??{id:"ManifestParsing",category:S.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&Je()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:o,streamIsUnpublished:u,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((o-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let d="active";l||(d=u?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(d)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:p})=>i(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=wn(l);if(c&&(r[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);j.display.isHDR&&d&&p?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,S.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,S.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,S.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,S.assertNonNullable)(this.manifest),(0,S.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new S.Subscription,this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add((0,S.fromEvent)(p,"error").pipe((0,S.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Ys():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ir())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new qa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],(0,S.isNonNullable)(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new qa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ha.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ha(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,S.merge)(...ZR.map(p=>(0,S.fromEvent)(this.element,p))).pipe((0,S.map)(p=>this.element?Pe(this.element.buffered,this.element.currentTime*1e3):0),(0,S.filterChanged)(),(0,S.tap)(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,S.merge)((0,S.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,S.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,S.now)())),this.subscription.add((0,S.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,S.interval)(1e3).subscribe(h=>{let m=ei(this.manifestUrlString,2);this.manifestUrlString=ye(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,S.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,S.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,S.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,S.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||br(this.element,1)})),this.representationSubscription.add((0,S.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,S.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,S.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,S.filter)(({isLive:h})=>h),(0,S.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,S.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let y=ei(this.manifestUrlString,2);return(h/2+m+g+y)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,S.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let y=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,k=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,I=h-y;if(this.isManualDecreasePlaybackInLive())return;let $=1;Math.abs(I)>T&&($=1+Math.sign(I)*k),br(this.element,$)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let g=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(T=>T.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add((0,S.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,S.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,y=ei(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,$=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,M=isFinite(h)?h:m,_=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),Y=T<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(Y);let D="none";if(_?D="active_low_latency":this.isLowLatency$.getValue()&&Y?(this.bufferManagers.forEach(O=>O.proceedLowLatencyLive()),D="active_low_latency"):y!==0&&M<k?D="live_forward_buffering":M<k+$&&(D="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),D==="live_forward_buffering"||D==="live_with_target_offset"){let O=p-(k+I),x=this.normolizeLiveOffset(Math.trunc(y+O/g)),F=Math.abs(x-y),P=0;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?P=y:x>0&&F>this.tuning.dashCmafLive.offsetCalculationError&&(P=x),this.manifestUrlString=ye(this.manifestUrlString,P,2)}(D==="live_with_target_offset"||D==="live_forward_buffering")&&(p=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:S.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,S.merge)(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe((0,S.map)(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=(0,S.merge)(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe((0,S.map)(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=(0,S.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,S.filterChanged)(),(0,S.map)(({allBuffersFull:p,someBufferEnded:h})=>p&&h),(0,S.filter)(p=>p));if(this.representationSubscription.add((0,S.merge)(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:S.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add((0,S.merge)(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{p&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:S.ErrorCategory.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 p=[this.manifest.duration??0,...(0,Vl.default)((0,Vl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),tt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&(0,S.isNonNullable)(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=(0,S.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:S.ErrorCategory.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.fetcher=new Fn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=jt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){(0,S.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,S.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ye(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(){(0,S.assertNonNullable)(this.element),this.state$.setState("running");let e=(0,S.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,S.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,S.merge)(...JR.map(t=>(0,S.fromEvent)(this.element,t)),(0,S.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:S.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,S.fromEvent)(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((0,S.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&De(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},s=(0,S.now)(),n=100,o=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(o);let u=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,c=this.audioBufferManager?.getForwardBufferDuration()??0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&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(m=>{this.error$.next({id:"stallIntervalCallback",category:S.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),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",(0,S.flattenObject)(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,S.interval)(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:S.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,S.assertNonNullable)(this.element),(0,S.assertNonNullable)(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),De(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,S.isNullable)(this.element)||(0,S.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,S.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,S.isNonNullable)(this.element)&&(0,S.isNonNullable)(this.source)&&(0,S.isNonNullable)(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}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.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=(0,S.getTraceSubscriptionMethod)(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 s=this.element.currentTime*1e3,n=null,o=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let u of this.bufferManagers)for(let l of u.gaps)(l.persistent||u.playingRepresentation$.getValue()===l.representation)&&l.from-o<=s&&l.to+o>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let u=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,u===1/0?this.forceEnded$.next():(this.element.currentTime=u/1e3,this.tracer.log("jumpGap",(0,S.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:u,resultCurrentTime:this.element.currentTime})))}}};var We=require("@vkontakte/videoplayer-shared"),qn=class{constructor(){this.subscription=new We.Subscription;this.pipSize$=new We.ValueSubject(void 0);this.videoSize$=new We.ValueSubject(void 0);this.elementSize$=new We.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=We.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,We.observeElementSize)(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((0,We.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,We.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Ri=class{constructor(e){this.subscription=new W.Subscription;this.videoState=new ee("stopped");this.observableVideo=null;this.droppedFramesManager=new nr;this.stallsManager=new Ln;this.elementSizeManager=new qn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ri;this.audioTrackSwitchHistory=new ri;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.hostname$.next(void 0),this.videoState.setState("stopped"),V(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"),V(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&V(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"&&V(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&V(this.params.desiredState.playbackState,"paused");return;default:return(0,W.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new gr(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 ot(e.source.url),this.params=e,this.video=Ue(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(Me(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 Un({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,W.isNullable)(this.observableVideo)&&(this.observableVideo=je(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:W.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,o)=>this.subscription.add(n.subscribe(o,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,W.filter)(d=>!!d.length),(0,W.once)()).subscribe(d=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,W.map)(d=>d.to.state!=="none"),(0,W.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,W.filter)(W.isNonNullable),(0,W.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,W.map)(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(kt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(ut(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),V(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),V(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let p=this.player.getStreams();if((0,W.assertNonNullable)(p,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of p.audio){m.push(Ml(g));let y=[];for(let T of g.representations){let k=NS(T);y.push(k),this.audioTracksMap.set(k,{stream:g,representation:T})}this.audioStreamsMap.set(g,y)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of p.video){h.push(Dl(m));let g=[];for(let y of m.representations){let T=FS({...y,streamId:m.id});T&&(g.push(T),this.videoTracksMap.set(T,{stream:m,representation:y}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(h);for(let m of p.text)for(let g of m.representations){let y=US(m,g);this.textTracksMap.set(y,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:o}=this.params.tuning.dash,u=o&&jS(o)||null;this.subscription.add((0,W.merge)(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$,(0,W.fromEvent)(this.video,"progress")).pipe((0,W.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),p=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||p||d==="running"&&u&&!u())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:m}=this.selectedRepresentations;if(!h)return;let g=Pi(this.videoTracksMap.keys(),T=>this.videoTracksMap.get(T)?.representation.id===h.id);(0,W.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let y=this.params.desiredState.autoVideoTrackLimits.getTransition();if(y&&this.params.output.autoVideoTrackLimits$.next(y.to),d==="manifest_ready")await this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let T=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,T)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,W.filterChanged)()).subscribe(d=>{let p=Pi(this.videoTracksMap.entries(),([,{representation:y}])=>y.id===d);if(!p){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=p,g=this.params.desiredState.videoStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.videoStream.setState(g.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Dl(m))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,W.filterChanged)()).subscribe(d=>{let p=Pi(this.audioTracksMap.entries(),([,{representation:y}])=>y.id===d);if(!p){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=p,g=this.params.desiredState.audioStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.audioStream.setState(g.to),e.currentAudioStream$.next(Ml(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}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((0,W.map)(({to:d})=>d==="ready"),(0,W.filterChanged)());this.subscription.add((0,W.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,W.observableFrom)(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,W.merge)(l,this.player.state$.stateChangeEnded$,(0,W.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=(0,W.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,W.observableFrom)(["init"])).pipe((0,W.debounce)(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ea:Zr,t=this.params.tuning.useNewAutoSelectVideoTrack?nn:sn,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:an,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),o=r.videoTrack.getState()?.id,u=Pi(this.videoTracksMap.keys(),D=>D.id===o),l=s.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(u&&this.videoTracksMap.get(u)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let d=Pi(this.videoStreamsMap.keys(),D=>D.id===c.id),p=d&&this.videoStreamsMap.get(d);if(!p)return;let h=Pe(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,y=Math.min(h/Math.min(m,g||1/0),1),T=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),k=T?.id&&Pi(this.audioStreamsMap.keys(),D=>D.id===T.id)||this.audioStreamsMap.keys().next().value,I=0;if(k){if(u&&!n){let D=e(u,p,this.audioStreamsMap.get(k)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,D?.bitrate??-1/0)}if(l){let D=e(l,p,this.audioStreamsMap.get(k)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);I=Math.max(I,D?.bitrate??-1/0)}}let $=u;(n||!$)&&($=i(p,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:I,forwardBufferHealth:y,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 M=k&&t($,p,this.audioStreamsMap.get(k)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:y,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),_=this.videoTracksMap.get($)?.representation,Y=M&&this.audioTracksMap.get(M)?.representation;_&&Y?(this.selectedRepresentations.video=_,this.selectedRepresentations.audio=Y):_&&!Y&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=_,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:W.ErrorCategory.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),qe(this.video),this.tracer.end()}};var ja=class extends Ri{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)}};var ce=require("@vkontakte/videoplayer-shared");var Qa=class extends Ri{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new ce.ValueSubject(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe((0,ce.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,ce.combine)({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ce.map)(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,ce.filter)(o=>(0,ce.isNonNullable)(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add((0,ce.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ce.merge)(i.playbackRateState$,new ce.ValueSubject(1))}).pipe((0,ce.filter)(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||(0,ce.isNullable)(l)||(e=o-l)})).add((0,ce.combine)({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ce.merge)(i.playbackRateState$,new ce.ValueSubject(1))}).pipe((0,ce.filterChanged)((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||(0,ce.isNullable)(o)||(0,ce.isNullable)(u))return;let p=-1*(u-o-e);t.position$.next(Math.min(p,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=qS(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var WS="X-Playback-Duration",_l=async a=>{let e=await lt(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(WS)?parseInt(e.headers.get(WS),10):void 0};var ie=require("@vkontakte/videoplayer-shared");var Fl=K(tu(),1);var Hn=require("@vkontakte/videoplayer-shared");var tL=a=>{let e=null;if(a.QUALITY&&(e=ii(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,Hn.videoSizeToQuality)({width:t,height:i})}return e??null},iL=(a,e)=>{let t=a.split(`
|
|
179
|
-
`),i=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],
|
|
180
|
-
`),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if((0,it.isNonNullable)(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 oe;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:it.ErrorCategory.WTF,thrown:t,message:e})}};var Ga=class{constructor(e){this.subscription=new ie.Subscription;this.videoState=new ee("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ie.ValueSubject([]);this.liveOffset=new Ii;this.manifestStartTime$=new ie.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),V(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(r?.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"?V(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),V(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"&&V(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else r?.to==="paused"&&(V(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,ie.assertNever)(t)}};this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ie.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,r)=>jn(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 Qn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ot(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ie.ErrorCategory.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:ie.ErrorCategory.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(Me(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ie.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;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:ie.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=je(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(He(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),s(ut(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),V(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),V(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((0,ie.filterChanged)(),(0,ie.map)(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ie.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Me(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add((0,ie.combine)({startTime:this.manifestStartTime$.pipe((0,ie.filter)(ie.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe((0,ie.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,ie.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ie.observableFrom)(["init"])).pipe((0,ie.debounce)(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),qe(this.video)}prepare(){let e=this.selectManifest();if((0,ie.isNullable)(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,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ye(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),_l(n).then(o=>{if(!(0,ie.isNullable)(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();((0,ie.isNullable)(u)||!isFinite(u))&<(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,n).toString();_l(d).then(p=>{(0,ie.isNullable)(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),V(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ie.ErrorCategory.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=ye(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}};var ne=require("@vkontakte/videoplayer-shared");var Wa=class{constructor(e){this.subscription=new ne.Subscription;this.videoState=new ee("stopped");this.manifests$=new ne.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),V(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?V(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),V(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"&&V(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&V(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,ne.assertNever)(t)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ne.VideoQuality.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(Me(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),jn(ye(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:ne.ErrorCategory.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(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:ne.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:o})},r=je(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,ne.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(kt(this.video,t.isLooped,i)),this.subscription.add(He(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),V(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),V(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(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ne.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Me(m.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe((0,ne.map)(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!j.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add((0,ne.merge)((0,ne.fromEvent)(o,"addtrack"),(0,ne.fromEvent)(o,"removetrack"),(0,ne.fromEvent)(o,"change"),(0,ne.observableFrom)(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=(0,ne.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ne.observableFrom)(["init"])).pipe((0,ne.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),qe(this.video)}prepare(){let e=this.selectManifest();if((0,ne.isNullable)(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:s,min:n}=t?.to??i??{};for(let[o,u]of[[s,"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(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ne.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var YS=K(ji(),1),Nl=K(er(),1),KS=K(Pt(),1);var he=require("@vkontakte/videoplayer-shared");var za=class{constructor(e){this.subscription=new he.Subscription;this.videoState=new ee("stopped");this.trackUrls={};this.textTracksManager=new ot;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),V(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?V(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),V(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"&&V(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&V(this.params.desiredState.playbackState,"paused");return;default:return(0,he.assertNever)(e)}};this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),(0,YS.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Nl.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:he.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:o})},r=je(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,he.map)(o=>o.to)),this.params.output.playbackState$),this.subscription.add(kt(this.video,t.isLooped,i)),this.subscription.add(He(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),s(ut(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),V(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),V(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&&(0,he.isNonNullable)(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 c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,he.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,he.observableFrom)(["init"])).pipe((0,he.debounce)(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),qe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,he.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,he.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ni(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Me(t))}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:he.ErrorCategory.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 c=Rt(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(c)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,Nl.default)(this.trackUrls).map(l=>l.track);if(!r||!s||rr(e,n[0].quality,(0,KS.default)(n,-1)?.quality)){i();return}let o=e.max?(0,he.isLowerOrEqual)(r,e.max):!0,u=e.min?(0,he.isHigherOrEqual)(r,e.min):!0;o&&u||i(e)}};var fe=require("@vkontakte/videoplayer-shared");var JS=require("@vkontakte/videoplayer-shared"),XS=["stun:videostun.mycdn.me:80"],aL=1e3,sL=3,Ul=()=>null,Gn=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=Ul;this.externalStopCallback=Ul;this.externalErrorCallback=Ul;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:XS}]};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:JS.ErrorCategory.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),aL)}normalizeOptions(e={}){let t={stunServerList:XS,maxRetryNumber:sL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ya=class{constructor(e){this.videoState=new ee("stopped");this.maxSeekBackTime$=new fe.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),V(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),V(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"&&V(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&V(this.params.desiredState.playbackState,"paused");return;default:return(0,fe.assertNever)(e)}};this.subscription=new fe.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ue(e.container,e.tuning),this.liveStreamClient=new Gn(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),qe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:fe.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,fe.merge)(this.videoState.stateChangeStarted$.pipe((0,fe.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,fe.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=je(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(ut(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{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(He(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(0,fe.assertNever)(n.to)}},i)).add((0,fe.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,fe.observableFrom)(["init"])).pipe((0,fe.debounce)(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(Me(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:fe.VideoQuality.INVARIANT}),this.video.srcObject=e,V(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:fe.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),V(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fe.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ka=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var E=require("@vkontakte/videoplayer-shared");var Qt=require("@vkontakte/videoplayer-shared"),ZS=a=>new Qt.Observable(e=>{let t=new Qt.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Qt.map)(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Qt.map)(({type:l})=>l!==void 0)),n=new Qt.Subject,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var ct=require("@vkontakte/videoplayer-shared");function ev(){return new(window.AudioContext||window.webkitAudioContext)}var vr=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new oe;this.subscriptions=new ct.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,ct.filter)(s=>!!s.type),(0,ct.once)()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){j.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,ct.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,ct.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,ct.once)()).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=ev();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:a.errorId,category:ct.ErrorCategory.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var nL={chunkDuration:5e3,maxParallelRequests:5},Xa=class{constructor(e){this.current$=new E.ValueSubject({type:void 0});this.providerError$=new E.Subject;this.noAvailableProvidersError$=new E.Subject;this.volumeMultiplierError$=new E.Subject;this.providerOutput={position$:new E.ValueSubject(0),duration$:new E.ValueSubject(1/0),volume$:new E.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new E.ValueSubject([]),currentVideoStream$:new E.ValueSubject(void 0),availableVideoTracks$:new E.ValueSubject([]),currentVideoTrack$:new E.ValueSubject(void 0),availableAudioStreams$:new E.ValueSubject([]),currentAudioStream$:new E.ValueSubject(void 0),availableAudioTracks$:new E.ValueSubject([]),currentVideoSegmentLength$:new E.ValueSubject(0),currentAudioSegmentLength$:new E.ValueSubject(0),isAudioAvailable$:new E.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new E.ValueSubject(!1),autoVideoTrackLimits$:new E.ValueSubject(void 0),currentBuffer$:new E.ValueSubject(void 0),isBuffering$:new E.ValueSubject(!0),error$:new E.Subject,fetcherError$:new E.Subject,fetcherRecoverableError$:new E.Subject,warning$:new E.Subject,willSeekEvent$:new E.Subject,soundProhibitedEvent$:new E.Subject,seekedEvent$:new E.Subject,loopedEvent$:new E.Subject,endedEvent$:new E.Subject,firstBytesEvent$:new E.Subject,loadedMetadataEvent$:new E.Subject,firstFrameEvent$:new E.Subject,canplay$:new E.Subject,isLive$:new E.ValueSubject(void 0),isLiveEnded$:new E.ValueSubject(null),isLowLatency$:new E.ValueSubject(!1),canChangePlaybackSpeed$:new E.ValueSubject(!0),liveTime$:new E.ValueSubject(void 0),liveBufferTime$:new E.ValueSubject(void 0),liveLatency$:new E.ValueSubject(void 0),severeStallOccurred$:new E.Subject,availableTextTracks$:new E.ValueSubject([]),currentTextTrack$:new E.ValueSubject(void 0),hostname$:new E.ValueSubject(void 0),httpConnectionType$:new E.ValueSubject(void 0),httpConnectionReused$:new E.ValueSubject(void 0),inPiP$:new E.ValueSubject(!1),inFullscreen$:new E.ValueSubject(!1),element$:new E.ValueSubject(void 0),elementVisible$:new E.ValueSubject(!0),availableSources$:new E.ValueSubject(void 0),is3DVideo$:new E.ValueSubject(!1),playbackState$:new E.ValueSubject(""),getCurrentTime$:new E.ValueSubject(null)};this.subscription=new E.Subscription;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=PS([...LS(this.params.tuning),...RS(this.params.tuning)],this.params.tuning).filter(l=>(0,E.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,ql.default)(r,l)),...t.filter(l=>(0,ql.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,E.flattenObject)(s)),this.screenFormatsIterator=new Ka(s);let n=[...wl(!0),...wl(!1)];this.chromecastFormatsIterator=new Ka(n.filter(l=>(0,E.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&vr.isSupported()&&(this.volumeMultiplierManager=new vr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){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((0,E.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:E.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,E.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,E.assertNonNullable)(u),this.params.tuning.useNewDashProvider?new ja({...o,source:u,sourceHls:l}):new Na({...o,source:u,sourceHls:l})}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),this.params.tuning.useNewDashProvider?new Qa({...o,source:u}):new Ua({...o,source:u})}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Wa({...o,source:u})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Ga({...o,source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new za({...o,source:u})}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Pb({...o,source:u,config:{...nL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(u),new Ya({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(0,E.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,E.assertNonNullable)(o),new Kr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,E.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,E.assertNever)(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(0,E.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,iv.default)((0,tv.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new E.Subscription,t=!1,i=0;return e.add((0,E.merge)(this.providerOutput.error$.pipe((0,E.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),ZS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,E.map)(r=>({id:`ProviderHangup:${r}`,category:E.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,E.filter)(({to:s})=>s==="playing"),(0,E.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===E.ErrorCategory.NETWORK,u=r.category===E.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",(0,E.flattenObject)(n)):this.tracer.error("providerError",(0,E.flattenObject)(n))})),e}};var z=require("@vkontakte/videoplayer-shared");var oL=5e3,rv="one_video_throughput",av="one_video_rtt",Ja=window.navigator.connection,sv=()=>{let a=Ja?.downlink;if((0,z.isNonNullable)(a)&&a!==10)return a*1e3},nv=()=>{let a=Ja?.rtt;if((0,z.isNonNullable)(a)&&a!==3e3)return a},ov=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Hl=class a{constructor(e){this.subscription=new z.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(rv)||(e.useBrowserEstimation?sv():void 0)||oL,i=a.load(av)??(e.useBrowserEstimation?nv():void 0)??0;if(this.throughput$=new z.ValueSubject(t),this.rtt$=new z.ValueSubject(i),this.rttAdjustedThroughput$=new z.ValueSubject(ov(t,i,e.rttPenaltyRequestSize)),this.throughput=jt.getSmoothedValue(t,-1,e),this.rtt=jt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=sv();n&&this.throughput.next(n);let o=nv();(0,z.isNonNullable)(o)&&this.rtt.next(o)};Ja&&"onchange"in Ja&&this.subscription.add((0,z.fromEvent)(Ja,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{z.safeStorage.set(rv,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{z.safeStorage.set(av,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,z.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,z.map)(({throughput:r,rtt:s})=>ov(r,s,e.rttPenaltyRequestSize)),(0,z.filter)(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,z.now)(),r=new z.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,z.fromEvent)(e,"progress").pipe((0,z.once)()).subscribe(s=>{t=s.loaded,i=(0,z.now)()}));break;case 1:case 0:r.add((0,z.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,z.now)()}));break}r.add((0,z.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=(0,z.now)(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,z.now)(),n=0,o=(0,z.now)(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(r,(0,z.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=(0,z.now)();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=(0,z.now)()}else n+=d.byteLength;o=(0,z.now)()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,z.now)()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,z.now)()-o,this.concurrentDownloads.size),n=0,o=(0,z.now)());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=z.safeStorage.get(e);if((0,z.isNonNullable)(t))return parseInt(t,10)??void 0}},uv=Hl;var Li=require("@vkontakte/videoplayer-shared"),lv={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Li.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Li.VideoQuality.Q_720P,trafficSavingLimit:Li.VideoQuality.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Li.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},cv=a=>({...(0,Li.fillWithDefault)(a,lv),configName:[...a.configName??[],...lv.configName]});var f=require("@vkontakte/videoplayer-shared");var Gt=require("@vkontakte/videoplayer-shared"),jl=({seekState:a,position$:e})=>(0,Gt.merge)(a.stateChangeEnded$.pipe((0,Gt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,Gt.filter)(Gt.isNonNullable)),e.pipe((0,Gt.filter)(()=>a.getState().state==="none")));var dv=require("@vkontakte/videoplayer-shared"),pv=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,dv.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Wn=require("@vkontakte/videoplayer-shared"),hv=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,Wn.filter)(r=>r.length>0),(0,Wn.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var Za=class{constructor(e={configName:[]},t=f.TracerFactory.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new f.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new ee("stopped"),seekState:new ee({state:"none"}),volume:new ee({volume:1,muted:!1}),videoTrack:new ee(void 0),videoStream:new ee(void 0),audioStream:new ee(void 0),autoVideoTrackSwitching:new ee(!0),autoVideoTrackLimits:new ee({}),isLooped:new ee(!1),isLowLatency:new ee(!1),playbackRate:new ee(1),externalTextTracks:new ee([]),internalTextTracks:new ee([]),currentTextTrack:new ee(void 0),textTrackCuesSettings:new ee({}),cameraOrientation:new ee({x:0,y:0})};this.info={playbackState$:new f.ValueSubject(void 0),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),predefinedQualityLimitType$:new f.ValueSubject("unknown"),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),isLiveEnded$:new f.ValueSubject(null),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willReady$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,fetcherRecoverableError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject,fetcherError$:new f.Subject,severeStallOccured$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:db,getCurrentTime$:new f.ValueSubject(null)};if(this.initLogs(),this.tuning=cv(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ms({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new uv(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let g=typeof m;return(0,fv.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:f.ErrorCategory.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...n}=e;this.tracer.log("initVideo",(0,f.flattenObject)(n)),this.domContainer=pv(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Xa({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?j.isInited$.pipe((0,f.filter)(s=>!!s),(0,f.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{hv(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>e),(0,f.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Xu(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>(0,f.isInvariantQuality)(u)?1:(0,f.isInvariantQuality)(l)?-1:(0,f.isHigher)(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,f.filter)(n=>(0,f.isNonNullable)(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe((0,f.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:jl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(jl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe((0,f.once)(),(0,f.map)(n=>n??(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Rt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),cb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>lb(t)),this.providerContainer.current$.subscribe(({type:t})=>Jr("provider",t)),e.duration$.subscribe(t=>Jr("duration",t)),e.availableVideoTracks$.pipe((0,f.filter)(t=>!!t.length),(0,f.once)()).subscribe(t=>Jr("tracks",t)),this.events.fatalError$.subscribe(new _e("fatalError")),this.events.managedError$.subscribe(new _e("managedError")),e.position$.subscribe(new _e("position")),e.currentVideoTrack$.pipe((0,f.map)(t=>t?.quality)).subscribe(new _e("quality")),this.info.currentBuffer$.subscribe(new _e("buffer")),e.isBuffering$.subscribe(new _e("isBuffering"))].forEach(t=>this.subscription.add(t)),Jr("codecs",j.video.supportedCodecs)}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,f.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})};this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!aa()}};var Ct=require("@vkontakte/videoplayer-shared"),uL=`@vkontakte/videoplayer-core@${Kn}`;
|
|
178
|
+
`;var Sr=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 Pn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Rn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(_S,this.gl.VERTEX_SHADER),i=this.createShader(OS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,u=e+i,o=t-r,l=e+i,c=t+r,p=e-i,d=t+r;return[s,n,u,o,l,c,p,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}};var he=require("@vkontakte/videoplayer-shared");var Ln="stalls_manager_metrics",Ml="stalls_manager_abr_params",FS="stalls_manager_default_tuning_abr_params",Dl=class{constructor(){this.isSeeked$=new he.ValueSubject(!1);this.isBuffering$=new he.ValueSubject(!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 he.Subscription;this.severeStallOccurred$=new he.ValueSubject(!1)}init(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.tuning=e.tuning,this.abrParams=e.abrParams,this.resetStoredAbrParamsIfNeeded(),this.subscribe(e)}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}get abrTuningParams(){let e=this.tuning.enabled?this.getStoredData(Ml):{};return{...this.abrParams,...e}}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=(0,he.now)(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe(),this.currentStallDuration$.getValue()!==0&&this.updateStallData();let e=((0,he.now)()-this.providerStartWatchingTimestamp-this.sumStallsDuration)/1e3,t=this.sumStallsDuration;this.addStallInfoToHistory(e,t),this.updateStoredAbrParams()}resetStoredAbrParamsIfNeeded(){let{bitrateFactorAtEmptyBuffer:e,bitrateFactorAtFullBuffer:t,containerSizeFactor:i}={...this.getStoredData(FS)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(Ml),this.setStoredData(FS,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Ln,"[]");if(!this.tuning.enabled||t.length<this.tuning.stallsMetricsHistoryLength)return;let i=t.reduce((s,n)=>s+n.tvt,0);if(this.tuning.useTotalStallsDurationPerTvt){let n=t.reduce((u,o)=>u+o.stallsDuration,0)/i;e.push(this.calculateOptimalAbrParams(n,i))}if(this.tuning.useAverageStallsDurationPerTvt){let s=t.reduce((n,u)=>n+u.stallsDurationPerTvt,0)/t.length;e.push(this.calculateOptimalAbrParams(s,i))}this.tuning.useEmaStallsDurationPerTvt&&e.push(this.calculateOptimalAbrParams(t[t.length-1].stallsDurationPerTvtSmoothed,i));let r={bitrateFactorAtEmptyBuffer:Math.max(...e.map(s=>s.bitrateFactorAtEmptyBuffer)),bitrateFactorAtFullBuffer:Math.max(...e.map(s=>s.bitrateFactorAtFullBuffer)),containerSizeFactor:Math.min(...e.map(s=>s.containerSizeFactor))};this.setStoredData(Ln,[]),this.setStoredData(Ml,r)}calculateOptimalAbrParams(e,t){let{targetStallsDurationPerTvt:i,deviationStallsDurationPerTvt:r,criticalStallsDurationPerTvt:s,abrAdjustingSpeed:n,significantTvt:u,stallsMetricsHistoryLength:o}=this.tuning,l=n*Math.min(t/(u*o),1),c=this.abrTuningParams;return e<i-r?c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(c={bitrateFactorAtEmptyBuffer:Math.min(c.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(c.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(c.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(c={bitrateFactorAtEmptyBuffer:Math.max(c.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(c.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(c.containerSizeFactor,this.abrParams.containerSizeFactor)}),c}getStoredData(e,t="{}"){return JSON.parse(he.safeStorage.get(e)??t)}setStoredData(e,t){he.safeStorage.set(e,JSON.stringify(t))}removeStoredData(e){he.safeStorage.remove(e)}addStallInfoToHistory(e,t){if(e<this.tuning.minTvtToBeCounted||e>this.tuning.maxTvtToBeCounted||e*1e3<t)return;let i=this.getStoredData(Ln,"[]"),r=t/e,s=i.length?Ht(i[i.length-1].stallsDurationPerTvtSmoothed,t/e,this.tuning.emaAlpha):r,n={tvt:e,stallsDuration:t,stallsDurationPerTvt:r,stallsDurationPerTvtSmoothed:s};i.push(n),i.length>this.tuning.stallsMetricsHistoryLength&&i.shift(),this.setStoredData(Ln,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((0,he.once)()).subscribe(t=>this.providerStartWatchingTimestamp=(0,he.now)())),this.subscription.add(this.currentStallDuration$.pipe((0,he.filterChanged)()).subscribe(t=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.tuning;if((0,he.isNullable)(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let u=this.rtt$.getValue(),o=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=(0,he.now)(),p=r&&this.currentStallsCount>=r,d=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&c-l>=i+u&&t>=i;(p||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,(0,he.isNonNullable)(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),!t&&(0,he.now)()-this.providerStartWatchingTimestamp>this.lastStallDuration&&(this.updateStallData(),this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s)),this.lastStallDuration=t}))}},$n=Dl;var Ge=require("@vkontakte/videoplayer-shared"),Mn=class{constructor(){this.subscription=new Ge.Subscription;this.pipSize$=new Ge.ValueSubject(void 0);this.videoSize$=new Ge.ValueSubject(void 0);this.elementSize$=new Ge.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=Ge.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,Ge.observeElementSize)(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((0,Ge.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,Ge.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Pi=class{constructor(e){this.subscription=new W.Subscription;this.videoState=new Z("stopped");this.observableVideo=null;this.droppedFramesManager=new ur;this.stallsManager=new $n;this.elementSizeManager=new Mn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ri;this.audioTrackSwitchHistory=new ri;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.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&B(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,W.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Sr(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 ot(e.source.url),this.params=e,this.video=Ue(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(Me(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 kn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,W.isNullable)(this.observableVideo)&&(this.observableVideo=je(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:W.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,W.filter)(l=>!!l.length),(0,W.once)()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,W.map)(l=>l.to.state!=="none"),(0,W.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,W.filter)(W.isNonNullable),(0,W.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,W.map)(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Pt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(ut(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if((0,W.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let d=[];for(let h of c.audio){d.push(xl(h));let m=[];for(let g of h.representations){let S=PS(g);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:g})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(d)}let p=[];for(let d of c.video){p.push(wl(d));let h=[];for(let m of d.representations){let g=kS({...m,streamId:d.id});g&&(h.push(g),this.videoTracksMap.set(g,{stream:d,representation:m}))}this.videoStreamsMap.set(d,h)}this.params.output.availableVideoStreams$.next(p);for(let d of c.text)for(let h of d.representations){let m=RS(d,h);this.textTracksMap.set(m,{stream:d,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add((0,W.merge)(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$,(0,W.fromEvent)(this.video,"progress")).pipe((0,W.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,NS.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[d,h]=p,m=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===d.id);(0,W.isNonNullable)(m)&&(this.stallsManager.lastVideoTrackSelected=m);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),l==="manifest_ready")await this.player.initRepresentations(d.id,h?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",d.id),h){let S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,S)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,W.filterChanged)()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:g}])=>g.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:d}]=c,h=this.params.desiredState.videoStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.videoStream.setState(h.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(wl(d));let m=this.player.calculateDurationFromSegments();m&&this.params.output.duration$.next(m/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,W.filterChanged)()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:d}]=c,h=this.params.desiredState.audioStream.getTransition();h&&h.to&&h.to.id===d.id&&this.params.desiredState.audioStream.setState(h.to),e.currentAudioStream$.next(xl(d))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{if(l?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}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 u=t.playbackState.stateChangeStarted$.pipe((0,W.map)(({to:l})=>l==="ready"),(0,W.filterChanged)());this.subscription.add((0,W.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,W.observableFrom)(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add((0,W.merge)(u,this.player.state$.stateChangeEnded$,(0,W.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let o=(0,W.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,W.observableFrom)(["init"])).pipe((0,W.debounce)(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ea:Zr,t=this.params.tuning.useNewAutoSelectVideoTrack?sn:an,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:rn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,l=[...this.videoTracksMap.keys()].find(({id:w})=>w===u),c=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(l&&this.videoTracksMap.get(l)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let d=[...this.videoStreamsMap.keys()].find(({id:w})=>w===p.id),h=d&&this.videoStreamsMap.get(d);if(!h)return;let m=Pe(this.video.buffered,this.video.currentTime*1e3),g;this.player.isActiveLive$.getValue()?g=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?g=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:g=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let S=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,T=Math.min(m/Math.min(g,S||1/0),1),k=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),x=[...this.audioStreamsMap.keys()].find(({id:w})=>w===k?.id)??this.audioStreamsMap.keys().next().value,L=0;if(x){if(l&&!n){let w=e(l,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);L=Math.max(L,w?.bitrate??-1/0)}if(c){let w=e(c,h,this.audioStreamsMap.get(x)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);L=Math.max(L,w?.bitrate??-1/0)}}let C=i(h,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.stallsManager.abrTuningParams,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:L,forwardBufferHealth:T,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),V=n?C??l:l??C,O=x&&t(V,h,this.audioStreamsMap.get(x)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:T,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),D=this.videoTracksMap.get(V)?.representation,_=O&&this.audioTracksMap.get(O)?.representation;if(D&&_)return[D,_];if(D&&!_&&this.audioTracksMap.size===0)return[D,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:W.ErrorCategory.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),qe(this.video),this.tracer.end()}};var Fa=class extends Pi{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)}};var ce=require("@vkontakte/videoplayer-shared");var Na=class extends Pi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new ce.ValueSubject(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,ce.filterChanged)()).subscribe(o=>{let l=i.position$.getValue(),c=i.volume$.getValue(),p=!c.volume||c.muted;!o&&!l&&p?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe((0,ce.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,ce.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,ce.map)(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,ce.filter)(o=>(0,ce.isNonNullable)(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add((0,ce.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,ce.merge)(r.playbackRateState$,new ce.ValueSubject(1))}).pipe((0,ce.filter)(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;p||l<1-d||this.video.paused||(0,ce.isNullable)(c)||(t=o-c)})).add((0,ce.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,ce.merge)(r.playbackRateState$,new ce.ValueSubject(1))}).pipe((0,ce.filterChanged)((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:c})=>{let p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&c>=1-d||(0,ce.isNullable)(o)||(0,ce.isNullable)(l))return;let h=-1*(l-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=LS(o);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 z=require("@vkontakte/videoplayer-shared");var Nl=Q(oa(),1);var v=require("@vkontakte/videoplayer-shared");var _n=Q(st(),1),Li=Q(gt(),1),On=Q(oa(),1);var YS=Q(qs(),1);var ui=require("@vkontakte/videoplayer-shared");var ZR=18,US=!1;try{US=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=ZR}catch(a){console.error(a)}var Cl=class{constructor(e){this.bufferFull$=new ui.Subject;this.error$=new ui.Subject;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:ui.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:e})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};US&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=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:ui.ErrorCategory.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:(0,ui.assertNever)(t)}}},qS=Cl;var P=require("@vkontakte/videoplayer-shared");var Bl=Q(gt(),1);var Dn=require("@vkontakte/videoplayer-shared"),HS=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?ii(s):void 0)??(0,Dn.videoSizeToQuality)({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},jS=({id:a,bitrate:e})=>({id:a,bitrate:e}),QS=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),GS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Vl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Bl.default)(i.split("."),0),isDefault:r}),_l=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Bl.default)(r.split("."),0)}),Ol=a=>"url"in a,tt=a=>a.type==="template";var WS=a=>{a.sort((t,i)=>t.from-i.from);let e=[a[0]];for(let t=1;t<a.length;t++){let{from:i,to:r}=a[t],s=e[e.length-1];s.to>=i?s.to=Math.max(s.to,r):e.push(a[t])}return e},Ri=(a,e)=>{for(let t of a)if(e(t))return t;return null},zS=a=>{let e=!1,t=(0,Dn.throttleFn)(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};var Vn=require("@vkontakte/videoplayer-shared");var Cn=a=>{let e=[];for(let t=0;t<a.length;t++){let i=Math.floor(a.start(t)*1e3),r=Math.ceil(a.end(t)*1e3);e.push(i,r)}return e};var Bn=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Vn.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,Vn.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!G(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=Cn(this.sourceBuffer.buffered);this.prevRanges=t,this.isRangesRemoved(e,t)&&(this.lastUpdateTs=Date.now())}isRangesRemoved(e,t){if(e.length!==t.length)return!0;for(let i=0;i<e.length;i+=2){let r=e[i],s=e[i+1],n=t[i],u=t[i+1];if(n>r||u<s)return!0}return!1}wasUpdated(){let{lastCallTs:e,lastUpdateTs:t}=this;return this.lastCallTs=Date.now(),e<=t}destroy(){this.subscription.unsubscribe()}};var Ua=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new P.ValueSubject(0);this.currentLowLatencySegmentLength$=new P.ValueSubject(0);this.currentSegmentLength$=new P.ValueSubject(0);this.onLastSegment$=new P.ValueSubject(!1);this.fullyBuffered$=new P.ValueSubject(!1);this.playingRepresentation$=new P.ValueSubject(void 0);this.playingRepresentationInit$=new P.ValueSubject(void 0);this.error$=new P.Subject;this.gaps=[];this.subscription=new P.Subscription;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ue;this.switchAbortController=new ue;this.destroyAbortController=new ue;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=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,P.assertNonNullable)(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new qS(this.sourceBuffer),this.sourceBufferBufferedDiff=new Bn(this.mediaSource,this.sourceBuffer),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:P.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!G(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,pr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=Pe(this.sourceBuffer.buffered,u),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<c).catch(p=>{this.handleAsyncError(p,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);(0,P.assertNonNullable)(i,"No init buffer for starting representation"),(0,P.assertNonNullable)(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,P.isNullable)(s)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();(0,P.isNonNullable)(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=(0,P.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,P.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,P.isNullable)(s)||(0,P.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,P.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();(0,P.isNonNullable)(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=(0,P.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,On.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(d=>d.id===o);l&&this.representations.set(o,l);let c=this.representations.get(o);if(!c||!tt(c.segmentReference))return;let p=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,p)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,r=this.representations.get(i);(0,P.assertNonNullable)(r);let s=this.segments.get(i);(0,P.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,P.assertNonNullable)(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let u=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),u&&(yield this.sourceBufferTaskQueue.remove(u.from*1e3,u.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=r,this.tuning=s,this.compatibilityMode=o,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=u,this.isLive=!!l?.live,this.baseUrls=l?.baseUrls??[],this.initData=new Map(i.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!G(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ue,(0,P.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,P.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if((0,P.isNullable)(u)||(0,P.isNullable)(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),(0,P.assertNonNullable)(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(u,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let o=this.getCurrentPosition();(0,P.isNonNullable)(o)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(o,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}warmUpMediaSource(){!(0,P.isNullable)(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 ue,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if((0,P.isNullable)(e)||(0,P.isNullable)(this.downloadingRepresentationId)||(0,P.isNullable)(this.playingRepresentationId)||(0,P.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||(0,P.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,P.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);(0,P.isNonNullable)(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next(r?.time.to-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Pe(this.sourceBuffer.buffered,e),p=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=p)}if(isFinite(this.bufferLimit)&&pr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=Pe(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p).catch(d=>{this.handleAsyncError(d,"pruneBuffer")});return}let o=null;if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,_n.default)(o,r))c="high";else{let p=(0,Li.default)(o,0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c).catch(p=>{this.handleAsyncError(p,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o?.length&&Pe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Li.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-Pe(this.sourceBuffer.buffered,e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r,persistent:!0}),i=s.time.to;(0,P.isNonNullable)(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration,persistent:!0})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,On.default)(e?.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i?.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){let t=(0,On.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!tt(i.segmentReference))return;let r=i.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(i.id)??[],u=(0,Li.default)(n,-1)?.time.to??0,o=r?.findIndex(l=>u>=l.time.from+s&&u<=l.time.to+s);if(o===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,l)}else{let l=r.slice(o+1);this.segments.set(i.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;(0,P.assertNonNullable)(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!tt(r))return;let s=this.segments.get(i.id);if(!s)continue;let n=s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),l=vt(r.segmentTemplateUrl,{segmentTime:o});s.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(s=>s.time.from<=e&&s.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&&$t&&$t(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&$t&&$t(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),s=e.findIndex(({status:d,time:{from:h,to:m}},g)=>{let S=h<=i&&m>=i,T=h>i||S||g===0&&i===0,k=Math.min(this.forwardBufferTarget,this.bufferLimit),x=this.preloadOnly&&h<=i+k||r<k&&m-h>=k||m<=i+k;return(d==="none"||d==="partially_ejected"&&T&&x&&this.sourceBuffer&&G(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,m)))&&T&&x});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],c=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,p=this.preloadOnly?this.forwardBufferTarget:0;for(let d=s;d<n.length&&(u<=c||o<=p);d++){let h=n[d];if(u+=h.byte.to+1-h.byte.from,o+=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"){tt(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await(0,P.abortable)(u,async function*(){let c=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(p=>setTimeout(p,c))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:u,onProgress:o,priority:i,isLowLatency:this.isActiveLowLatency(),bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation});if(this.lastDataObtainedTimestampMs=(0,P.now)(),!c)return;let p=new DataView(c),d=Mt(t.mime);if(!isFinite(r.segment.time.to)){let g=t.segmentReference.timescale;r.segment.time.to=d.getChunkEndTime(p,g)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(p,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=d.getServerLatencyTimestamps(p);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Dt(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())tt(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let o of e)o.status="downloading",this.activeSegments.add({segment:o,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:s,signal:n,onProgress:u}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await(0,P.abortable)(n,async function*(){let o=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),(0,P.fromEvent)(window,"online").pipe((0,P.once)()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:r,onProgress:u,signal:n,priority:i,bufferOptimisation:this.tuning.dash.fetcherBufferOptimisation}),this.lastDataObtainedTimestampMs=(0,P.now)(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Dt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(tt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Li.default)(e,0).byte.from,to:(0,Li.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)(),await this.onSomeByteRangesDataLoaded({dataView:u,loaded:o,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!tt(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)();let p=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(p)}catch(p){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:p})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,_n.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let n=this.representations.get(t);if(n)for(let u of this.activeSegments){let{segment:o}=u;if(u.representationId===t){if(s.aborted){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),c=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(o.status="partially_fed",u.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),u.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!G(this.mediaSource,this.sourceBuffer))return;let u=this.representations.get(t);if(u)for(let o of this.activeSegments){if(o.representationId!==t)continue;if(s.aborted){await n();continue}let{segment:l}=o,c=l.byte.from-i,p=l.byte.to-i,d=p-c+1,h=c<r,m=p<=r;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,d);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(o,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(o.loadedBytes=Math.min(d,r-c),o.loadedBytes>o.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+o.feedingBytes,o.loadedBytes-o.feedingBytes),S=o.loadedBytes===d?g:Mt(u.mime).parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",o.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(o.fedBytes+=S.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!((0,P.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer))){!this.isLive&&j.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(De(this.sourceBuffer.buffered,e.segment.time.from,100)&&De(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:P.ErrorCategory.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",Ol(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values()){if(i.id===t)continue;let r=this.segments.get(i.id);if(r)for(let s of r)s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none")}this.isActiveLowLatency()&&this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,e.segment)}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=dr(()=>(0,YS.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?(0,P.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(o=>setTimeout(o,u))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Mt(e.mime),r)).then(u=>{if(!u)return;let{init:o,dataView:l,segments:c}=u,p=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,p);let d=c;this.isLive&&tt(e.segmentReference)&&(d=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,d),o&&this.parsedInitData.set(e.id,o)}).then(()=>this.failedDownloads=0,u=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:P.ErrorCategory.WTF,message:"loadInit threw",thrown:u})});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||!G(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,P.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=u=>{if(s>=t)return;r.push({...u.time});let o=Ol(u)?u.size??0:u.byte.to-u.byte.from;s+=o};for(let u of this.segments.values())for(let o of u){let l=o.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&o.status==="fed"&&n(o)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let o=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let d of p)(0,_n.default)(["none","partially_ejected"],d.status)&&Math.round(d.time.from)<=Math.round(o)&&Math.round(d.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let p={time:{from:o,to:l},url:"",status:"none"};n(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let o of this.segments.values())for(let l of o)l.time.from>=e+u&&l.status==="fed"&&n(l)}return r.length?(r=WS(r),(await Promise.all(r.map(o=>this.sourceBufferTaskQueue.remove(o.from,o.to)))).reduce((o,l)=>o||l,!1)):!1}async abortBuffer(){if(!this.sourceBuffer||!G(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||!G(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||!G(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||!G(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,P.isNullable)(e)?0:Pe(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.tuning.useRefactoredSearchGap&&(this.gaps=this.gaps.filter(s=>{if(s.persistent)return!0;let n=Math.round(s.from),u=Math.round(s.to);for(let o=0;o<i.length;o++)if(n>=Math.round(i.start(o)*1e3)&&u<=Math.round(i.end(o)*1e3))return!1;return!0}));let r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let s=0;s<i.length;s++){let n=i.start(s)*1e3,u=i.end(s)*1e3;if(!(u<=t.time.from||n>=t.time.to)){if(n<=t.time.from&&u>=t.time.to){r=void 0;break}u>t.time.from&&u<t.time.to&&(r.from=u),n<t.time.to&&n>t.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!G(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>r.persistent||this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=dr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||!G(this.mediaSource,this.sourceBuffer)||(0,P.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=Cn(this.sourceBuffer.buffered),t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),u=Math.ceil(r.time.to),o=!1,l=0;for(let c=0;c<e.length;c+=2){let p=e[c],d=e[c+1];o||(o=p-t<=n&&d+t>=u),(n>=p&&n<d-t||u>p+t&&u<=d)&&(l+=1)}o||(l===1?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:P.ErrorCategory.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}calculateDurationFromSegments(){if(!this.playingRepresentationId)return 0;let e=this.segments.get(this.playingRepresentationId);return(e?(0,Li.default)(e,-1)?.time.to:0)||0}};var X=require("@vkontakte/videoplayer-shared");var Nn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new X.ValueSubject(void 0);this.lastConnectionReused$=new X.ValueSubject(void 0);this.lastRequestFirstBytes$=new X.ValueSubject(void 0);this.recoverableError$=new X.Subject;this.error$=new X.Subject;this.abortAllController=new ue;this.subscription=new X.SubscriptionRemovable;this.fetchManifest=(0,X.abortable)(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=ni(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=bn(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Fn);return r?(t.log("success",(0,X.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,X.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,X.abortable)(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:u=!0,isLowLatency:o=!1,bufferOptimisation:l=!1}={}){let c=e,p=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{p.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let E=new URL(c,location.href);E.searchParams.append("bytes",`${i.from}-${i.to}`),c=E.toString();break}default:(0,X.assertNever)(t)}this.requestQuic&&(c=ni(c));let h=this.abortAllController.signal,m;if(n){let E=new ue;if(m=(0,X.merge)((0,X.fromEvent)(this.abortAllController.signal,"abort"),(0,X.fromEvent)(n,"abort")).subscribe(()=>{try{E.abort()}catch(R){Fn(R)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(R){Fn(R)}h=E.signal}let g=(0,X.now)();d.log("startRequest",(0,X.flattenObject)({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:g}));let S=yield this.doFetch(c,{priority:s,headers:p,signal:h}),T=(0,X.now)();if(!S)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(T-g),!S.ok||!S.body){this.unsubscribeAbortSubscription(m);let E=`Fetch error ${S.status}: ${S.statusText}`;return d.error("error",{message:E}),d.end(),Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`))}if(this.onHeadersReceived(S.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let E=(0,X.now)(),R={requestStartedAt:g,requestEndedAt:E,duration:E-g};return d.log("endRequest",(0,X.flattenObject)(R)),d.end(),S.arrayBuffer()}let k=S.body;if(u){let E;[k,E]=S.body.tee(),this.throughputEstimator?.trackStream(E,o)}let x=k.getReader(),L,C=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(C)&&(L=C),!L&&i&&(L=i.to-i.from+1);let V=0,O=L?new Uint8Array(L):new Uint8Array(0),D=!1,_=E=>{this.unsubscribeAbortSubscription(m),D=!0,Fn(E)},w=(0,X.abortable)(h,async function*({done:E,value:R}){if(V===0&&this.lastRequestFirstBytes$.next((0,X.now)()-g),h.aborted){this.unsubscribeAbortSubscription(m);return}if(!E&&R){if(l&&L)O.set(R,V),V+=R.byteLength;else{let oe=new Uint8Array(O.length+R.length);oe.set(O),oe.set(R,O.length),O=oe,V+=R.byteLength}r?.(new DataView(O.buffer),V),yield x?.read().then(w,_)}}.bind(this));yield x?.read().then(w,_),this.unsubscribeAbortSubscription(m);let ee=(0,X.now)(),F={failed:D,requestStartedAt:g,requestEndedAt:ee,duration:ee-g};return D?(d.error("endRequest",(0,X.flattenObject)(F)),d.end(),null):(d.log("endRequest",(0,X.flattenObject)(F)),d.end(),O.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,u=s,o=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(c,s))),n=Math.min(n,0);let p=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!p)return null;let d=new DataView(p,r-n,s-n+1);if(!t.validateData(d))throw new Error("Invalid media file");let h=t.parseInit(d),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let g;if(o)g=new DataView(p,m.from-n,m.to-m.from+1);else{let T=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!T)return null;g=new DataView(T)}let S=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(p),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,X.abortable)(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=mn(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:(0,X.assertNever)(r)}}destroy(){this.abortAllController.abort(),this.tracer.end(),this.subscription.unsubscribe()}async doFetch(e,t){let i=await lt(e,t);if(i.ok)return i;let r=await i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:X.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:X.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:X.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:X.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:X.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Fn=a=>{if(!Dt(a))throw a};var Un=require("@vkontakte/videoplayer-shared");var qa=class a{constructor(e,t){this.currentRepresentation$=new Un.ValueSubject(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(!(0,Un.isNullable)(e))for(let t of this.representations)for(let i of t){let r=i.segmentReference,s=r.segments.length,n=r.segments[0].time.from,u=r.segments[s-1].time.to;if(e<n||e>u)continue;let o=r.segments.find(l=>l.time.from<=e&&l.time.to>=e);!o||this.currentSegment?.time.from===o.time.from&&this.currentSegment.time.to===o.time.to||(this.currentSegment=o,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(o.url,r.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>a.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&tt(t.segmentReference))}};var iL=["progress","play","seeked","stalled","waiting"],rL=["timeupdate","progress","loadeddata","playing","seeked"];var qn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new v.Subscription;this.representationSubscription=new v.Subscription;this.state$=new Z("none");this.currentVideoRepresentation$=new v.ValueSubject(void 0);this.currentVideoRepresentationInit$=new v.ValueSubject(void 0);this.currentAudioRepresentation$=new v.ValueSubject(void 0);this.currentVideoSegmentLength$=new v.ValueSubject(0);this.currentAudioSegmentLength$=new v.ValueSubject(0);this.error$=new v.Subject;this.lastConnectionType$=new v.ValueSubject(void 0);this.lastConnectionReused$=new v.ValueSubject(void 0);this.lastRequestFirstBytes$=new v.ValueSubject(void 0);this.currentLiveTextRepresentation$=new v.ValueSubject(null);this.isLive$=new v.ValueSubject(!1);this.isActiveLive$=new v.ValueSubject(!1);this.isLowLatency$=new v.ValueSubject(!1);this.liveDuration$=new v.ValueSubject(0);this.liveSeekableDuration$=new v.ValueSubject(0);this.liveAvailabilityStartTime$=new v.ValueSubject(0);this.liveStreamStatus$=new v.ValueSubject(void 0);this.bufferLength$=new v.ValueSubject(0);this.liveLatency$=new v.ValueSubject(void 0);this.liveLoadBufferLength$=new v.ValueSubject(0);this.livePositionFromPlayer$=new v.ValueSubject(0);this.currentStallDuration$=new v.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new v.ValueSubject(0);this.fetcherRecoverableError$=new v.Subject;this.fetcherError$=new v.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new v.Subject;this.gapWatchdogActive=!1;this.destroyController=new ue;this.initManifest=(0,v.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ye(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:v.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,v.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:v.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=pn(e??"",this.manifestUrlString)}catch(n){let u=cn(e)??{id:"ManifestParsing",category:v.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(u)}if(!t)return null;let i=(n,u,o)=>!!(this.element?.canPlayType?.(u)&&Je()?.isTypeSupported?.(`${u}; codecs="${o}"`)||n==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:n,latestSegmentPublishTime:u,streamIsUnpublished:o,streamIsAlive:l}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((u-n)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";l||(p=o?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let o=t.streams[n].filter(({mime:p,codecs:d})=>i(n,p,d)),l=new Set(o.map(({codecs:p})=>p)),c=An(l);if(c&&(r[n]=o.filter(({codecs:p})=>p.startsWith(c))),n==="video"){let p=this.tuning.preferHDR,d=r.video.some(m=>m.hdr),h=r.video.some(m=>!m.hdr);j.display.isHDR&&p&&d?r.video=r.video.filter(m=>m.hdr):h&&(r.video=r.video.filter(m=>!m.hdr))}}let s={...t,streams:r};return this.tracer.log("updateManifestEnd",(0,v.flattenObject)(s)),s}.bind(this));this.initRepresentations=(0,v.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,v.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,v.assertNonNullable)(this.manifest),(0,v.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.representationSubscription=new v.Subscription,this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add((0,v.fromEvent)(d,"error").pipe((0,v.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:v.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Gs():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&rr())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},u=this.manifest.streams.video.reduce((d,h)=>[...d,...h.representations],[]);if(this.videoBufferManager=new Ua("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],(0,v.isNonNullable)(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Ua("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}qa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new qa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,v.merge)(...rL.map(d=>(0,v.fromEvent)(this.element,d))).pipe((0,v.map)(d=>this.element?Pe(this.element.buffered,this.element.currentTime*1e3):0),(0,v.filterChanged)(),(0,v.tap)(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,v.merge)((0,v.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,v.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,v.now)())),this.subscription.add((0,v.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,v.interval)(1e3).subscribe(h=>{let m=ei(this.manifestUrlString,2);this.manifestUrlString=ye(this.manifestUrlString,m+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add((0,v.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,v.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,v.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||gr(this.element,1)})),this.representationSubscription.add((0,v.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,v.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:g})=>m&&g&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,v.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,v.filter)(({isLive:h})=>h),(0,v.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,v.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let S=ei(this.manifestUrlString,2);return(h/2+m+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,v.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,T=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,k=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,x=h-S;if(this.isManualDecreasePlaybackInLive())return;let L=1;Math.abs(x)>T&&(L=1+Math.sign(x)*k),gr(this.element,L)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let g=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(T=>T.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add((0,v.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,v.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,S=ei(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,L=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,C=isFinite(h)?h:m,V=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=T<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let D="none";if(V?D="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),D="active_low_latency"):S!==0&&C<k?D="live_forward_buffering":C<k+L&&(D="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),D==="live_forward_buffering"||D==="live_with_target_offset"){let _=d-(k+x),w=this.normolizeLiveOffset(Math.trunc(S+_/g)),ee=Math.abs(w-S),F=0;!h||ee<=this.tuning.dashCmafLive.offsetCalculationError?F=S:w>0&&ee>this.tuning.dashCmafLive.offsetCalculationError&&(F=w),this.manifestUrlString=ye(this.manifestUrlString,F,2)}(D==="live_with_target_offset"||D==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:v.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,v.merge)(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe((0,v.map)(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=(0,v.merge)(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe((0,v.map)(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),p=(0,v.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,v.filterChanged)(),(0,v.map)(({allBuffersFull:d,someBufferEnded:h})=>d&&h),(0,v.filter)(d=>d));if(this.representationSubscription.add((0,v.merge)(this.forceEnded$,p).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:v.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add((0,v.merge)(...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:v.ErrorCategory.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,Nl.default)((0,Nl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),tt(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3}this.audioBufferManager&&(0,v.isNonNullable)(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=(0,v.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:v.ErrorCategory.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.fetcher=new Nn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=jt.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){(0,v.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,v.now)()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ye(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(){(0,v.assertNonNullable)(this.element),this.state$.setState("running");let e=(0,v.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,v.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,v.merge)(...iL.map(t=>(0,v.fromEvent)(this.element,t)),(0,v.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:v.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,v.fromEvent)(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((0,v.fromEvent)(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===HTMLMediaElement.HAVE_CURRENT_DATA&&!this.element.seeking&&De(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},s=(0,v.now)(),n=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,c=this.audioBufferManager?.getForwardBufferDuration()??0,p=l<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&c<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((p||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(m=>{this.error$.next({id:"stallIntervalCallback",category:v.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:m})}),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",(0,v.flattenObject)(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,v.interval)(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:v.ErrorCategory.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r?.switchToWithPreviousAbort(t,i):r?.switchTo(t,i):r?.switchToOld(t,i)}async seek(e,t){(0,v.assertNonNullable)(this.element),(0,v.assertNonNullable)(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),De(this.element.buffered,i)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),!((0,v.isNullable)(this.element)||(0,v.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,v.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,v.isNonNullable)(this.element)&&(0,v.isNonNullable)(this.source)&&(0,v.isNonNullable)(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}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.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=(0,v.getTraceSubscriptionMethod)(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 s=this.element.currentTime*1e3,n=null,u=this.element.readyState===HTMLMediaElement.HAVE_METADATA?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(l.persistent||o.playingRepresentation$.getValue()===l.representation)&&l.from-u<=s&&l.to+u>s&&(this.element.duration*1e3-l.to<this.tuning.endGapTolerance?n=1/0:(n===null||l.to>n)&&(n=l.to));if(n!==null){let o=n+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,this.tracer.log("jumpGap",(0,v.flattenObject)({isJumpGapAfterSeekLive:i,isActiveLowLatency:t,initialCurrentTime:r,jumpTo:o,resultCurrentTime:this.element.currentTime})))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var We=require("@vkontakte/videoplayer-shared"),Hn=class{constructor(){this.subscription=new We.Subscription;this.pipSize$=new We.ValueSubject(void 0);this.videoSize$=new We.ValueSubject(void 0);this.elementSize$=new We.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=We.noop}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add((0,We.observeElementSize)(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((0,We.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,We.map)(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var $i=class{constructor(e){this.subscription=new z.Subscription;this.videoState=new Z("stopped");this.observableVideo=null;this.droppedFramesManager=new ur;this.stallsManager=new $n;this.elementSizeManager=new Hn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ri;this.audioTrackSwitchHistory=new ri;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.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&B(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():i?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,z.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Sr(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 ot(e.source.url),this.params=e,this.video=Ue(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(Me(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 qn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,z.isNullable)(this.observableVideo)&&(this.observableVideo=je(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:z.ErrorCategory.WTF,message:`${i} internal logic error`,thrown:n})},s=(n,u)=>this.subscription.add(n.subscribe(u,r));return{output:e,desiredState:t,observableVideo:this.observableVideo,genericErrorListener:r,connect:s}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe((0,z.filter)(p=>!!p.length),(0,z.once)()).subscribe(p=>{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:p})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe((0,z.map)(p=>p.to.state!=="none"),(0,z.filterChanged)());this.stallsManager.init({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$,videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,tuning:this.params.tuning.stallsManager,abrParams:this.params.tuning.autoTrackSelection,isBuffering$:i.isBuffering$,looped$:i.looped$,playing$:i.playing$}),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe((0,z.filter)(z.isNonNullable),(0,z.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,z.map)(p=>p.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(Pt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(nt(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(ut(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:p})=>{if(p==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if((0,z.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let g of d.audio){m.push(Vl(g));let S=[];for(let T of g.representations){let k=jS(T);S.push(k),this.audioTracksMap.set(k,{stream:g,representation:T})}this.audioStreamsMap.set(g,S)}this.params.output.availableAudioStreams$.next(m)}let h=[];for(let m of d.video){h.push(_l(m));let g=[];for(let S of m.representations){let T=HS({...S,streamId:m.id});T&&(g.push(T),this.videoTracksMap.set(T,{stream:m,representation:S}))}this.videoStreamsMap.set(m,g)}this.params.output.availableVideoStreams$.next(h);for(let m of d.text)for(let g of m.representations){let S=QS(m,g);this.textTracksMap.set(S,{stream:m,representation:g})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else p==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&&zS(u)||null;this.subscription.add((0,z.merge)(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$,(0,z.fromEvent)(this.video,"progress")).pipe((0,z.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let p=this.player.state$.getState(),d=this.player.state$.getTransition();if(p!=="manifest_ready"&&p!=="running"||d||p==="running"&&o&&!o())return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState()),this.selectVideoAudioRepresentations();let{video:h,audio:m}=this.selectedRepresentations;if(!h)return;let g=Ri(this.videoTracksMap.keys(),T=>this.videoTracksMap.get(T)?.representation.id===h.id);(0,z.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.to),p==="manifest_ready")await this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",h.id),m){let T=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,T)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:p})=>{this.scene3D&&p&&this.scene3D.pointCameraTo(p.x,p.y)})),this.subscription.add(this.elementSizeManager.subscribe(p=>{this.scene3D&&p&&this.scene3D.setViewportSize(p.width,p.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe((0,z.filterChanged)()).subscribe(p=>{let d=Ri(this.videoTracksMap.entries(),([,{representation:T}])=>T.id===p);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=d,g=this.params.desiredState.videoStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.videoStream.setState(g.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(_l(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,z.filterChanged)()).subscribe(p=>{let d=Ri(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===p);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=d,g=this.params.desiredState.audioStream.getTransition();g&&g.to&&g.to.id===m.id&&this.params.desiredState.audioStream.setState(g.to),e.currentAudioStream$.next(Vl(m))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(p=>{if(p?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(p),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((0,z.map)(({to:p})=>p==="ready"),(0,z.filterChanged)());this.subscription.add((0,z.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,z.observableFrom)(["init"])).subscribe(()=>{let p=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:p?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add((0,z.merge)(l,this.player.state$.stateChangeEnded$,(0,z.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=(0,z.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,z.observableFrom)(["init"])).pipe((0,z.debounce)(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ea:Zr,t=this.params.tuning.useNewAutoSelectVideoTrack?sn:an,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:rn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=Ri(this.videoTracksMap.keys(),D=>D.id===u),l=s.currentVideoTrack$.getValue(),c=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!c)return;let p=Ri(this.videoStreamsMap.keys(),D=>D.id===c.id),d=p&&this.videoStreamsMap.get(p);if(!d)return;let h=Pe(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let g=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,g||1/0),1),T=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),k=T?.id&&Ri(this.audioStreamsMap.keys(),D=>D.id===T.id)||this.audioStreamsMap.keys().next().value,x=0;if(k){if(o&&!n){let D=e(o,d,this.audioStreamsMap.get(k)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,D?.bitrate??-1/0)}if(l){let D=e(l,d,this.audioStreamsMap.get(k)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,D?.bitrate??-1/0)}}let L=o;(n||!L)&&(L=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:x,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 C=k&&t(L,d,this.audioStreamsMap.get(k)??[],{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}),V=this.videoTracksMap.get(L)?.representation,O=C&&this.audioTracksMap.get(C)?.representation;V&&O?(this.selectedRepresentations.video=V,this.selectedRepresentations.audio=O):V&&!O&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=V,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:z.ErrorCategory.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),qe(this.video),this.tracer.end()}};var Ha=class extends $i{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)}};var de=require("@vkontakte/videoplayer-shared");var ja=class extends $i{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=!1,t=-1,{output:i,observableVideo:r,desiredState:s,connect:n}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canPlayLiveTailBuffer$.next(!0),n(r.timeUpdate$,i.liveBufferTime$),n(this.player.liveSeekableDuration$,i.duration$),n(this.player.liveLatency$,i.liveLatency$);let u=new de.ValueSubject(1);n(r.playbackRateState$,u),this.params.tuning.dashCmafLive.catchupLiveForMutedInactiveTab&&this.subscription.add(i.elementVisible$.pipe((0,de.filterChanged)()).subscribe(o=>{let l=i.position$.getValue(),c=i.volume$.getValue(),p=!c.volume||c.muted;!o&&!l&&p?e=!0:o&&e&&(this.seek(0),e=!1)})),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(s.isLowLatency.stateChangeEnded$.pipe((0,de.map)(o=>o.to)).subscribe(this.player.isLowLatency$)).add((0,de.combine)({liveBufferTime:i.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe((0,de.map)(({liveBufferTime:o,liveAvailabilityStartTime:l})=>o&&l?o+l:void 0)).subscribe(i.liveTime$)).add(this.player.liveStreamStatus$.pipe((0,de.filter)(o=>(0,de.isNonNullable)(o))).subscribe(o=>i.isLiveEnded$.next(o!=="active"&&i.position$.getValue()===0))).add((0,de.combine)({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:(0,de.merge)(r.playbackRateState$,new de.ValueSubject(1))}).pipe((0,de.filter)(({liveStreamStatus:o,liveDuration:l})=>o==="active"&&!!l)).subscribe(({liveDuration:o,playbackRate:l})=>{let c=i.liveBufferTime$.getValue(),p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;p||l<1-d||this.video.paused||(0,de.isNullable)(c)||(t=o-c)})).add((0,de.combine)({time:i.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:(0,de.merge)(r.playbackRateState$,new de.ValueSubject(1))}).pipe((0,de.filterChanged)((o,l)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===l.liveDuration:o.time===l.time)).subscribe(({time:o,liveDuration:l,playbackRate:c})=>{let p=i.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!p&&!this.video.paused&&c>=1-d||(0,de.isNullable)(o)||(0,de.isNullable)(l))return;let h=-1*(l-o-t);i.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let l=GS(o);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 XS="X-Playback-Duration",Ul=async a=>{let e=await lt(a),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(XS)?parseInt(e.headers.get(XS),10):void 0};var ie=require("@vkontakte/videoplayer-shared");var Hl=Q(iu(),1);var jn=require("@vkontakte/videoplayer-shared");var sL=a=>{let e=null;if(a.QUALITY&&(e=ii(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=(0,jn.videoSizeToQuality)({width:t,height:i})}return e??null},nL=(a,e)=>{let t=a.split(`
|
|
179
|
+
`),i=[],r=[];for(let s=0;s<t.length;s++){let n=t[s],u=n.match(/^#EXT-X-STREAM-INF:(.+)/),o=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!o)){if(u){let l=(0,Hl.default)(u[1].split(",").map(S=>S.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,p=sL(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,m;if(l.RESOLUTION){let[S,T]=l.RESOLUTION.split("x").map(k=>parseInt(k,10));S&&T&&(m={width:S,height:T})}let g=new URL(t[++s],e).toString();p&&i.push({id:c,quality:p,url:g,bandwidth:d,size:m,fps:h})}if(o){let l=(0,Hl.default)(o[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),p=l.LANGUAGE,d=l.NAME;c&&p&&r.push({type:"internal",id:p,label:d,language:p,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},oL=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),ql=0,JS=async(a,e=a,t,i)=>{let s=await(await lt(a,i)).text();ql+=1;try{let{qualityManifests:n,textTracks:u}=nL(s,e);return{qualityManifests:n,textTracks:u}}catch{if(ql<=t.manifestRetryMaxCount)return await oL((0,jn.getExponentialDelay)(ql-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),JS(a,e,t)}return{qualityManifests:[],textTracks:[]}},Qn=JS;var it=require("@vkontakte/videoplayer-shared");var Gn=class{constructor(e,t,i,r,s){this.subscription=new it.Subscription;this.abortControllers={destroy:new ue,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new it.ValueSubject(null);this.getCurrentTime$=new it.ValueSubject(null);this.error$=new it.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe((0,it.throttle)(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 lt(r,{signal:this.abortControllers.destroy.signal})).text(),u=this.parsePlaylist(n,r);return{textTrack:i,playlist:u}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
|
|
180
|
+
`),s=0;for(let n=0;n<r.length;++n){let u=r[n];switch(!0){case u.startsWith("#EXTINF:"):{let o=r[++n],l=new URL(o,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let p=new Date(i.vkStartTime).valueOf(),d=new Date(i.programDateTime).valueOf();i.segmentStartTime=d-p}break}case u.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",u));break;case u.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",u));break;case u.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",u));break;case u.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let o=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",u);i.programDateTime=o;let l=new Date(o);l.setMilliseconds(0),s=l.valueOf();break}case u.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",u);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((0,it.isNonNullable)(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 ue;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:it.ErrorCategory.WTF,thrown:t,message:e})}};var Qa=class{constructor(e){this.subscription=new ie.Subscription;this.videoState=new Z("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new ie.ValueSubject([]);this.liveOffset=new Ii;this.manifestStartTime$=new ie.ValueSubject(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||u){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.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"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else r?.to==="paused"&&(B(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,ie.assertNever)(t)}};this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ie.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,r)=>Qn(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 Gn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new ot(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:r})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:ie.ErrorCategory.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:ie.ErrorCategory.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(Me(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new ie.ValueSubject(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsLiveProvider",category:ie.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=je(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(He(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),s(ut(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(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(u=>{u&&this.params.output.availableTextTracks$.next(u)})),this.subscription.add(this.maxSeekBackTime$.pipe((0,ie.filterChanged)(),(0,ie.map)(u=>-u/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ie.isNonNullable)(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let d=this.manifests$.getValue().find(h=>h.id===p);d&&(this.params.output.currentVideoTrack$.next(d),this.params.output.hostname$.next(Me(d.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u&&u.state==="requested"&&this.seek(u.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{let u=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(u||void 0)},i)),this.subscription.add((0,ie.combine)({startTime:this.manifestStartTime$.pipe((0,ie.filter)(ie.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:u,currentTime:o})=>this.params.output.liveTime$.next(u+o*1e3),i)),this.subscription.add(this.manifests$.pipe((0,ie.map)(u=>u.map(({id:o,quality:l,size:c,bandwidth:p,fps:d})=>({id:o,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,ie.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ie.observableFrom)(["init"])).pipe((0,ie.debounce)(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),qe(this.video)}prepare(){let e=this.selectManifest();if((0,ie.isNullable)(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:u,min:o}=t?.to??i??{};for(let[l,c]of[[u,"mq"],[o,"lq"]]){let p=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ye(r.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Ul(n).then(u=>{if(!(0,ie.isNullable)(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();((0,ie.isNullable)(o)||!isFinite(o))&<(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let p=new URL(c,n).toString();Ul(p).then(d=>{(0,ie.isNullable)(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ie.ErrorCategory.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=ye(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}};var ne=require("@vkontakte/videoplayer-shared");var Ga=class{constructor(e){this.subscription=new ne.Subscription;this.videoState=new Z("stopped");this.manifests$=new ne.ValueSubject([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||u){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:p}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:p*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?B(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return(0,ne.assertNever)(t)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ne.VideoQuality.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(Me(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Qn(ye(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:ne.ErrorCategory.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(),s=r?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let u=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(o=>o.id===u)}subscribe(){let{output:e,desiredState:t}=this.params,i=u=>{e.error$.next({id:"HlsProvider",category:ne.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:u})},r=je(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,ne.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Pt(this.video,t.isLooped,i)),this.subscription.add(He(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(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 u=this.params.desiredState.seekState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ne.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(g=>g.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(Me(m.url)))}let p=this.params.desiredState.playbackRate.getState(),d=this.params.output.element$.getValue()?.playbackRate;if(p!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(p),h.playbackRate=p)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u.state==="requested"&&this.seek(u.position)},i))),this.subscription.add(this.manifests$.pipe((0,ne.map)(u=>u.map(({id:o,quality:l,size:c,bandwidth:p,fps:d})=>({id:o,quality:l,size:c,fps:d,bitrate:p})))).subscribe(this.params.output.availableVideoTracks$,i)),!j.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add((0,ne.merge)((0,ne.fromEvent)(u,"addtrack"),(0,ne.fromEvent)(u,"removetrack"),(0,ne.fromEvent)(u,"change"),(0,ne.observableFrom)(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=(0,ne.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ne.observableFrom)(["init"])).pipe((0,ne.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),qe(this.video)}prepare(){let e=this.selectManifest();if((0,ne.isNullable)(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:s,min:n}=t?.to??i??{};for(let[u,o]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(u||""));o&&u&&r.searchParams.set(o,l)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ne.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var ZS=Q(Gi(),1),jl=Q(ar(),1),ev=Q(gt(),1);var fe=require("@vkontakte/videoplayer-shared");var Wa=class{constructor(e){this.subscription=new fe.Subscription;this.videoState=new Z("stopped");this.trackUrls={};this.textTracksManager=new ot;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:o}=this.video;this.prepare(),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:o*1e3,forcePrecise:!0});return}switch(i?.to!=="paused"&&u.state==="requested"&&this.seek(u.position),e){case"ready":t==="ready"?B(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,fe.assertNever)(e)}};this.params=e,this.video=Ue(e.container,e.tuning),this.params.output.element$.next(this.video),(0,ZS.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,jl.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=u=>{e.error$.next({id:"MpegProvider",category:fe.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:u})},r=je(this.video);this.subscription.add(()=>r.destroy());let s=(u,o)=>this.subscription.add(u.subscribe(o,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe((0,fe.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Pt(this.video,t.isLooped,i)),this.subscription.add(He(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),s(ut(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),B(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let u=this.params.desiredState.videoTrack.getTransition();if(u&&(0,fe.isNonNullable)(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);let o=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(o!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(o),c.playbackRate=o)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=(0,fe.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,fe.observableFrom)(["init"])).pipe((0,fe.debounce)(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),qe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;(0,fe.assertNonNullable)(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];(0,fe.assertNonNullable)(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ni(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Me(t))}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fe.ErrorCategory.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 c=Rt(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(c)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,jl.default)(this.trackUrls).map(l=>l.track);if(!r||!s||sr(e,n[0].quality,(0,ev.default)(n,-1)?.quality)){i();return}let u=e.max?(0,fe.isLowerOrEqual)(r,e.max):!0,o=e.min?(0,fe.isHigherOrEqual)(r,e.min):!0;u&&o||i(e)}};var me=require("@vkontakte/videoplayer-shared");var iv=require("@vkontakte/videoplayer-shared"),tv=["stun:videostun.mycdn.me:80"],uL=1e3,lL=3,Ql=()=>null,Wn=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=Ql;this.externalStopCallback=Ql;this.externalErrorCallback=Ql;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:tv}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:iv.ErrorCategory.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),uL)}normalizeOptions(e={}){let t={stunServerList:tv,maxRetryNumber:lL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var za=class{constructor(e){this.videoState=new Z("stopped");this.maxSeekBackTime$=new me.ValueSubject(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),B(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&B(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&B(this.params.desiredState.playbackState,"paused");return;default:return(0,me.assertNever)(e)}};this.subscription=new me.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ue(e.container,e.tuning),this.liveStreamClient=new Wn(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),qe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:me.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add((0,me.merge)(this.videoState.stateChangeStarted$.pipe((0,me.map)(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,me.map)(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:u})=>{this.log({message:`[videoState change] ${u}: ${JSON.stringify(n)}`})}));let r=je(this.video);this.subscription.add(()=>r.destroy());let s=(n,u)=>this.subscription.add(n.subscribe(u,i));s(r.timeUpdate$,e.liveTime$),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(ut(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{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(He(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(0,me.assertNever)(n.to)}},i)).add((0,me.merge)(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,(0,me.observableFrom)(["init"])).pipe((0,me.debounce)(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(Me(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:me.VideoQuality.INVARIANT}),this.video.srcObject=e,B(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:me.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Qe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),B(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:me.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ya=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};var I=require("@vkontakte/videoplayer-shared");var Qt=require("@vkontakte/videoplayer-shared"),rv=a=>new Qt.Observable(e=>{let t=new Qt.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Qt.map)(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe((0,Qt.map)(({type:l})=>l!==void 0)),n=new Qt.Subject,u=0,o="unknown";return t.add(i.subscribe(l=>{u&&window.clearTimeout(u),o=l,u=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(u),o="unknown",u=0})),t.add(s.subscribe(l=>{u&&(window.clearTimeout(u),u=0,l&&(u=window.setTimeout(()=>n.next(o),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(u),t.unsubscribe()}});var ct=require("@vkontakte/videoplayer-shared");function av(){return new(window.AudioContext||window.webkitAudioContext)}var vr=class a{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ue;this.subscriptions=new ct.Subscription;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe((0,ct.filter)(s=>!!s.type),(0,ct.once)()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){j.browser.isSafari&&e!=="MPEG"||this.subscriptions.add((0,ct.combine)({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe((0,ct.filter)(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),(0,ct.once)()).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=av();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(await i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!0}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){this.volumeMultiplierError$.next({id:a.errorId,category:ct.ErrorCategory.VIDEO_PIPELINE,message:e?.message??`${a.errorId} exception`,thrown:e})}};var cL={chunkDuration:5e3,maxParallelRequests:5},Ka=class{constructor(e){this.current$=new I.ValueSubject({type:void 0});this.providerError$=new I.Subject;this.noAvailableProvidersError$=new I.Subject;this.volumeMultiplierError$=new I.Subject;this.providerOutput={position$:new I.ValueSubject(0),duration$:new I.ValueSubject(1/0),volume$:new I.ValueSubject({muted:!1,volume:1}),availableVideoStreams$:new I.ValueSubject([]),currentVideoStream$:new I.ValueSubject(void 0),availableVideoTracks$:new I.ValueSubject([]),currentVideoTrack$:new I.ValueSubject(void 0),availableAudioStreams$:new I.ValueSubject([]),currentAudioStream$:new I.ValueSubject(void 0),availableAudioTracks$:new I.ValueSubject([]),currentVideoSegmentLength$:new I.ValueSubject(0),currentAudioSegmentLength$:new I.ValueSubject(0),isAudioAvailable$:new I.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new I.ValueSubject(!1),autoVideoTrackLimits$:new I.ValueSubject(void 0),currentBuffer$:new I.ValueSubject(void 0),isBuffering$:new I.ValueSubject(!0),error$:new I.Subject,fetcherError$:new I.Subject,fetcherRecoverableError$:new I.Subject,warning$:new I.Subject,willSeekEvent$:new I.Subject,soundProhibitedEvent$:new I.Subject,seekedEvent$:new I.Subject,loopedEvent$:new I.Subject,endedEvent$:new I.Subject,firstBytesEvent$:new I.Subject,loadedMetadataEvent$:new I.Subject,firstFrameEvent$:new I.Subject,canplay$:new I.Subject,isLive$:new I.ValueSubject(void 0),isLiveEnded$:new I.ValueSubject(null),canPlayLiveTailBuffer$:new I.ValueSubject(!1),isLowLatency$:new I.ValueSubject(!1),canChangePlaybackSpeed$:new I.ValueSubject(!0),liveTime$:new I.ValueSubject(void 0),liveBufferTime$:new I.ValueSubject(void 0),liveLatency$:new I.ValueSubject(void 0),severeStallOccurred$:new I.Subject,availableTextTracks$:new I.ValueSubject([]),currentTextTrack$:new I.ValueSubject(void 0),hostname$:new I.ValueSubject(void 0),httpConnectionType$:new I.ValueSubject(void 0),httpConnectionReused$:new I.ValueSubject(void 0),inPiP$:new I.ValueSubject(!1),inFullscreen$:new I.ValueSubject(!1),element$:new I.ValueSubject(void 0),elementVisible$:new I.ValueSubject(!0),availableSources$:new I.ValueSubject(void 0),is3DVideo$:new I.ValueSubject(!1),playbackState$:new I.ValueSubject(""),getCurrentTime$:new I.ValueSubject(null)};this.subscription=new I.Subscription;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=Qu([...CS(this.params.tuning),...DS(this.params.tuning)],this.params.tuning).filter(l=>(0,I.isNonNullable)(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Gl.default)(r,l)),...t.filter(l=>(0,Gl.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,I.flattenObject)(s)),this.screenFormatsIterator=new Ya(s);let n=[...Rl(!0),...Rl(!1)];this.chromecastFormatsIterator=new Ya(n.filter(l=>(0,I.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&vr.isSupported()&&(this.volumeMultiplierManager=new vr(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}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((0,I.isNullable)(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:I.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return(0,I.assertNever)(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,u={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return(0,I.assertNonNullable)(o),this.params.tuning.useNewDashProvider?new Ha({...u,source:o,sourceHls:l}):new Fa({...u,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),this.params.tuning.useNewDashProvider?new ja({...u,source:o}):new Na({...u,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new Ga({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new Qa({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new Wa({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new $b({...u,source:o,config:{...cL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new za({container:i,source:o,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(0,I.assertNever)(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,u=this.params.dependencies.chromecastInitializer.connection$.getValue();return(0,I.assertNonNullable)(u),new Kr({connection:u,meta:s,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return(0,I.assertNever)(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return(0,I.assertNever)(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(0,I.assertNever)(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return(0,nv.default)((0,sv.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new I.Subscription,t=!1,i=0;return e.add((0,I.merge)(this.providerOutput.error$.pipe((0,I.filter)(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),rv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe((0,I.map)(r=>({id:`ProviderHangup:${r}`,category:I.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe((0,I.filter)(({to:s})=>s==="playing"),(0,I.once)()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let u=r.category===I.ErrorCategory.NETWORK,o=r.category===I.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!o,p=l&&!o&&(u&&t||!c);n={...n,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:p,canReinitProvider:c},c?(i++,this.reinitProvider()):p?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s??"SCREEN"))}r.traceAsLog?this.tracer.log("providerInfo",(0,I.flattenObject)(n)):this.tracer.error("providerError",(0,I.flattenObject)(n))})),e}};var Y=require("@vkontakte/videoplayer-shared");var dL=5e3,ov="one_video_throughput",uv="one_video_rtt",Xa=window.navigator.connection,lv=()=>{let a=Xa?.downlink;if((0,Y.isNonNullable)(a)&&a!==10)return a*1e3},cv=()=>{let a=Xa?.rtt;if((0,Y.isNonNullable)(a)&&a!==3e3)return a},dv=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Wl=class a{constructor(e){this.subscription=new Y.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(ov)||(e.useBrowserEstimation?lv():void 0)||dL,i=a.load(uv)??(e.useBrowserEstimation?cv():void 0)??0;if(this.throughput$=new Y.ValueSubject(t),this.rtt$=new Y.ValueSubject(i),this.rttAdjustedThroughput$=new Y.ValueSubject(dv(t,i,e.rttPenaltyRequestSize)),this.throughput=jt.getSmoothedValue(t,-1,e),this.rtt=jt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=lv();n&&this.throughput.next(n);let u=cv();(0,Y.isNonNullable)(u)&&this.rtt.next(u)};Xa&&"onchange"in Xa&&this.subscription.add((0,Y.fromEvent)(Xa,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{Y.safeStorage.set(ov,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{Y.safeStorage.set(uv,r.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add((0,Y.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,Y.map)(({throughput:r,rtt:s})=>dv(r,s,e.rttPenaltyRequestSize)),(0,Y.filter)(r=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(r-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=(0,Y.now)(),r=new Y.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,Y.fromEvent)(e,"progress").pipe((0,Y.once)()).subscribe(s=>{t=s.loaded,i=(0,Y.now)()}));break;case 1:case 0:r.add((0,Y.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,Y.now)()}));break}r.add((0,Y.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,u=(0,Y.now)(),o=n-t,l=u-i;this.addRawSpeed(o,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=(0,Y.now)(),n=0,u=(0,Y.now)(),o=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:p})=>{if(c)!t&&this.addRawSpeed(r,(0,Y.now)()-s,1),this.concurrentDownloads.delete(e);else if(p){if(t){let d=(0,Y.now)();if(d-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||d-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=u-s;m&&this.addRawSpeed(n,m,1,t),n=p.byteLength,s=(0,Y.now)()}else n+=p.byteLength;u=(0,Y.now)()}else r+=p.byteLength,n+=p.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,Y.now)()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,Y.now)()-u,this.concurrentDownloads.size),n=0,u=(0,Y.now)());await i?.read().then(l,o)}};this.concurrentDownloads.add(e),i?.read().then(l,o)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Y.safeStorage.get(e);if((0,Y.isNonNullable)(t))return parseInt(t,10)??void 0}},pv=Wl;var Mi=require("@vkontakte/videoplayer-shared"),hv={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{maxBitrateFactorAtEmptyBuffer:4,bitrateFactorAtEmptyBuffer:2.8,minBitrateFactorAtEmptyBuffer:1.5,bitrateAudioFactorAtEmptyBuffer:10,maxBitrateFactorAtFullBuffer:3,bitrateFactorAtFullBuffer:2,minBitrateFactorAtFullBuffer:1,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,maxContainerSizeFactor:2,containerSizeFactor:1.3,minContainerSizeFactor:1,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Mi.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Mi.VideoQuality.Q_720P,trafficSavingLimit:Mi.VideoQuality.Q_480P},stallsManager:{enabled:!1,stallDurationNoDataBeforeQualityDecrease:500,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!0,stallsMetricsHistoryLength:5,maxPossibleStallDuration:3e4,minTvtToBeCounted:5,maxTvtToBeCounted:10800,significantTvt:600,targetStallsDurationPerTvt:1,deviationStallsDurationPerTvt:.5,criticalStallsDurationPerTvt:6,abrAdjustingSpeed:.1,emaAlpha:.6,useTotalStallsDurationPerTvt:!0,useAverageStallsDurationPerTvt:!0,useEmaStallsDurationPerTvt:!0},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Mi.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,catchupLiveForMutedInactiveTab:!0,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},fv=a=>({...(0,Mi.fillWithDefault)(a,hv),configName:[...a.configName??[],...hv.configName]});var f=require("@vkontakte/videoplayer-shared");var Gt=require("@vkontakte/videoplayer-shared"),zl=({seekState:a,position$:e})=>(0,Gt.merge)(a.stateChangeEnded$.pipe((0,Gt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,Gt.filter)(Gt.isNonNullable)),e.pipe((0,Gt.filter)(()=>a.getState().state==="none")));var mv=require("@vkontakte/videoplayer-shared"),bv=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,mv.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var zn=require("@vkontakte/videoplayer-shared"),gv=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,zn.filter)(r=>r.length>0),(0,zn.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var Ja=class{constructor(e={configName:[]},t=f.TracerFactory.createRootTracer(!1)){this.subscription=new f.Subscription;this.logger=new f.Logger;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new f.ValueSubject(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new f.ValueSubject(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new Z("stopped"),seekState:new Z({state:"none"}),volume:new Z({volume:1,muted:!1}),videoTrack:new Z(void 0),videoStream:new Z(void 0),audioStream:new Z(void 0),autoVideoTrackSwitching:new Z(!0),autoVideoTrackLimits:new Z({}),isLooped:new Z(!1),isLowLatency:new Z(!1),playbackRate:new Z(1),externalTextTracks:new Z([]),internalTextTracks:new Z([]),currentTextTrack:new Z(void 0),textTrackCuesSettings:new Z({}),cameraOrientation:new Z({x:0,y:0})};this.info={playbackState$:new f.ValueSubject(void 0),position$:new f.ValueSubject(0),duration$:new f.ValueSubject(1/0),muted$:new f.ValueSubject(!1),volume$:new f.ValueSubject(1),availableVideoStreams$:new f.ValueSubject([]),currentVideoStream$:new f.ValueSubject(void 0),availableQualities$:new f.ValueSubject([]),availableQualitiesFps$:new f.ValueSubject({}),currentQuality$:new f.ValueSubject(void 0),isAutoQualityEnabled$:new f.ValueSubject(!0),autoQualityLimitingAvailable$:new f.ValueSubject(!1),autoQualityLimits$:new f.ValueSubject({}),predefinedQualityLimitType$:new f.ValueSubject("unknown"),availableAudioStreams$:new f.ValueSubject([]),currentAudioStream$:new f.ValueSubject(void 0),availableAudioTracks$:new f.ValueSubject([]),isAudioAvailable$:new f.ValueSubject(!0),currentPlaybackRate$:new f.ValueSubject(1),currentBuffer$:new f.ValueSubject({start:0,end:0}),isBuffering$:new f.ValueSubject(!0),isStalled$:new f.ValueSubject(!1),isEnded$:new f.ValueSubject(!1),isLooped$:new f.ValueSubject(!1),isLive$:new f.ValueSubject(void 0),isLiveEnded$:new f.ValueSubject(null),canPlayLiveTailBuffer$:new f.ValueSubject(!1),canChangePlaybackSpeed$:new f.ValueSubject(void 0),atLiveEdge$:new f.ValueSubject(void 0),atLiveDurationEdge$:new f.ValueSubject(void 0),liveTime$:new f.ValueSubject(void 0),liveBufferTime$:new f.ValueSubject(void 0),liveLatency$:new f.ValueSubject(void 0),currentFormat$:new f.ValueSubject(void 0),availableTextTracks$:new f.ValueSubject([]),currentTextTrack$:new f.ValueSubject(void 0),throughputEstimation$:new f.ValueSubject(void 0),rttEstimation$:new f.ValueSubject(void 0),videoBitrate$:new f.ValueSubject(void 0),hostname$:new f.ValueSubject(void 0),httpConnectionType$:new f.ValueSubject(void 0),httpConnectionReused$:new f.ValueSubject(void 0),surface$:new f.ValueSubject("none"),chromecastState$:new f.ValueSubject("NOT_AVAILABLE"),chromecastDeviceName$:new f.ValueSubject(void 0),intrinsicVideoSize$:new f.ValueSubject(void 0),availableSources$:new f.ValueSubject(void 0),is3DVideo$:new f.ValueSubject(!1),currentVideoSegmentLength$:new f.ValueSubject(0),currentAudioSegmentLength$:new f.ValueSubject(0)};this.events={inited$:new f.Subject,ready$:new f.Subject,started$:new f.Subject,playing$:new f.Subject,paused$:new f.Subject,stopped$:new f.Subject,willReady$:new f.Subject,willStart$:new f.Subject,willResume$:new f.Subject,willPause$:new f.Subject,willStop$:new f.Subject,willDestruct$:new f.Subject,watchCoverageRecord$:new f.Subject,watchCoverageLive$:new f.Subject,managedError$:new f.Subject,fatalError$:new f.Subject,fetcherRecoverableError$:new f.Subject,ended$:new f.Subject,looped$:new f.Subject,seeked$:new f.Subject,willSeek$:new f.Subject,autoplaySoundProhibited$:new f.Subject,firstBytes$:new f.Subject,loadedMetadata$:new f.Subject,firstFrame$:new f.Subject,canplay$:new f.Subject,log$:new f.Subject,fetcherError$:new f.Subject,severeStallOccured$:new f.Subject};this.experimental={element$:new f.ValueSubject(void 0),tuningConfigName$:new f.ValueSubject([]),enableDebugTelemetry$:new f.ValueSubject(!1),dumpTelemetry:fb,getCurrentTime$:new f.ValueSubject(null)};if(this.initLogs(),this.tuning=fv(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new fs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new pv(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.InternalsExposure("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...u)=>{try{return n.apply(i,u)}catch(o){let l=u.map(d=>JSON.stringify(d,(h,m)=>{let g=typeof m;return(0,Sv.default)(["number","string","boolean"],g)?m:m===null?null:`<${g}>`})),c=`Player.${String(r)}`,p=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:f.ErrorCategory.WTF,message:p,thrown:o}),o}}}})}initVideo(e){this.config=e,this.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),this.setMuted(this.tuning.isAudioDisabled);let t=()=>{let{container:s,...n}=e;this.tracer.log("initVideo",(0,f.flattenObject)(n)),this.domContainer=bv(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ka({sources:e.sources,meta:e.meta??{},failoverHosts:e.failoverHosts??[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?j.isInited$.pipe((0,f.filter)(s=>!!s),(0,f.once)()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),(0,f.fromEvent)(document,"visibilitychange").pipe((0,f.once)()).subscribe(r)):r(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),this.internalsExposure?.destroy()}prepare(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.desiredState.volume,s=i.getTransition()?.to.muted??this.info.muted$.getValue(),n=t??(this.tuning.isAudioDisabled||s);this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e,t=!1){return this.subscription.add(this.playerInited.pipe((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.desiredState.volume,r=this.tuning.isAudioDisabled&&!t||e,n=i.getTransition()?.to.volume??this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:r,volume:n,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(r):i.startTransitionTo({volume:n,muted:r})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",(0,f.flattenObject)(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{if(this.info.predefinedQualityLimitType$.getValue()===e)return this;let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{(0,f.assertNonNullable)(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",(0,f.flattenObject)(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t})))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{gv(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe((0,f.filter)(t=>!!t),(0,f.once)()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe((0,f.filter)(i=>!!i),(0,f.once)()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>e),(0,f.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe((0,f.filter)(e=>!!e),(0,f.once)()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if((0,f.isNullable)(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return(0,f.isNonNullable)(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){let e=this.providerContainer?.current$.getValue();if(e?.provider?.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add((0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe((0,f.map)(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(tl(e,t,i))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.filter)(({from:e})=>e==="stopped"),(0,f.once)()).subscribe(()=>{this.initedAt=(0,f.now)(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"ready":this.events.willReady$.next();break;case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",(0,f.flattenObject)(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:f.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe((0,f.once)()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",(0,f.flattenObject)(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe((0,f.map)(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe((0,f.map)(n=>n.destination),(0,f.filterChanged)()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add((0,f.combine)({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe((0,f.map)(({availableVideoTracks:n,currentVideoStream:u})=>n.filter(o=>u?u.id===o.streamId:!0).map(({quality:o})=>o).sort((o,l)=>(0,f.isInvariantQuality)(o)?1:(0,f.isInvariantQuality)(l)?-1:(0,f.isHigher)(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let u={};for(let o of n)o.fps&&(u[o.quality]=o.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe((0,f.filterChanged)()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe((0,f.filter)(n=>(0,f.isNonNullable)(n))).subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe((0,f.filterChanged)((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe((0,f.filterChanged)((n,u)=>Math.round(n)===Math.round(u))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe((0,f.filterChanged)()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe((0,f.filterChanged)()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe((0,f.map)(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe((0,f.tap)(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).add(e.providerOutput.canPlayLiveTailBuffer$.subscribe(this.info.canPlayLiveTailBuffer$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add((0,f.combine)({hasLiveOffsetByPaused:(0,f.merge)(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe((0,f.map)(n=>n.to),(0,f.filterChanged)(),(0,f.map)(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:u})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(u));return}this.hasLiveOffsetByPaused.next(!1)})).add((0,f.combine)({atLiveEdge:(0,f.combine)({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe((0,f.map)(({isLive:n,position:u,isLowLatency:o})=>{let l=this.getActiveLiveDelay(o);return n&&Math.abs(u)<l/1e3}),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe((0,f.map)(({atLiveEdge:n,hasPausedTimeoutCase:u})=>n&&!u)).subscribe(this.info.atLiveEdge$)).add((0,f.combine)({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe((0,f.map)(({isLive:n,position:u,duration:o})=>n&&(Math.abs(o)-Math.abs(u))*1e3<this.tuning.live.activeLiveDelay),(0,f.filterChanged)(),(0,f.tap)(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.muted),(0,f.filterChanged)()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe((0,f.map)(n=>n.volume),(0,f.filterChanged)()).subscribe(this.info.volume$)).add(zl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add((0,f.merge)(e.providerOutput.endedEvent$.pipe((0,f.mapTo)(!0)),e.providerOutput.seekedEvent$.pipe((0,f.mapTo)(!1))).pipe((0,f.filterChanged)()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe((0,f.map)(n=>({id:n?`No${n}`:"NoProviders",category:f.ErrorCategory.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe((0,f.once)(),(0,f.map)(n=>n??(0,f.now)()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe((0,f.once)(),(0,f.map)(()=>(0,f.now)()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new f.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new f.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.filter)(({to:n})=>n==="playing"),(0,f.once)()).subscribe(()=>i.next(!1)));let r=0,s=(0,f.merge)(e.providerOutput.isBuffering$,t,i).pipe((0,f.map)(()=>{let n=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return n&&!u}),(0,f.filterChanged)());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add((0,f.merge)(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:u?.videoWidth,height:u?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add((0,f.merge)(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),u=e.providerOutput.inFullscreen$.getValue(),o=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),p;c==="CONNECTED"?p="second_screen":o?l?n?p="pip":u?p="fullscreen":p="inline":p="invisible":p="none",this.info.surface$.getValue()!==p&&this.info.surface$.next(p)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe((0,f.map)(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new f.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe((0,f.filterChanged)((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe((0,f.filter)(i=>i.length>0),(0,f.once)()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.info.currentQuality$.getValue();i&&(t=e.find(({quality:r})=>r===i),t||this.setAutoQuality(!0)),t||(t=Rt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add((0,f.merge)(this.desiredState.videoTrack.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe((0,f.map)(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe((0,f.map)(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;(0,f.assertNonNullable)(this.providerContainer),(0,f.assertNonNullable)(e),hb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>pb(t)),this.providerContainer.current$.subscribe(({type:t})=>Jr("provider",t)),e.duration$.subscribe(t=>Jr("duration",t)),e.availableVideoTracks$.pipe((0,f.filter)(t=>!!t.length),(0,f.once)()).subscribe(t=>Jr("tracks",t)),this.events.fatalError$.subscribe(new _e("fatalError")),this.events.managedError$.subscribe(new _e("managedError")),e.position$.subscribe(new _e("position")),e.currentVideoTrack$.pipe((0,f.map)(t=>t?.quality)).subscribe(new _e("quality")),this.info.currentBuffer$.subscribe(new _e("buffer")),e.isBuffering$.subscribe(new _e("isBuffering"))].forEach(t=>this.subscription.add(t)),Jr("codecs",j.video.supportedCodecs)}initTracerSubscription(){let e=(0,f.getTraceSubscriptionMethod)(this.tracer.log.bind(this.tracer)),t=(0,f.getTraceSubscriptionMethod)(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe((0,f.filterChanged)()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add((0,f.combine)({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe((0,f.filter)(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),(0,f.filterChanged)((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe((0,f.filter)(i=>i>0),(0,f.filterChanged)()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add((0,f.combine)({currentBuffer:this.info.currentBuffer$.pipe((0,f.filter)(i=>i.end>0),(0,f.filterChanged)((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe((0,f.filterChanged)())}).pipe((0,f.throttle)(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe((0,f.filterChanged)()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe((0,f.filterChanged)()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe((0,f.filterChanged)()).subscribe(e("canChangePlaybackSpeed"))).add((0,f.combine)({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe((0,f.filter)(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),(0,f.throttle)(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe((0,f.filterChanged)()).subscribe(e("muted"))).add(this.info.volume$.pipe((0,f.filterChanged)()).subscribe(e("volume"))).add(this.info.isEnded$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add((0,f.combine)({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe((0,f.filter)(({throughputEstimation:i,rtt:r})=>!!i&&!!r),(0,f.throttle)(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe((0,f.filterChanged)(),(0,f.filter)(i=>i===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e?.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:f.ErrorCategory.DOM,message:String(r)})})};this.subscription.add((0,f.merge)((0,f.fromEvent)(document,"visibilitychange"),(0,f.fromEvent)(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",(0,f.flattenObject)({quality:t,availableTracks:(0,f.flattenObject)(e),track:(0,f.flattenObject)(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!aa()}};var Ct=require("@vkontakte/videoplayer-shared"),pL=`@vkontakte/videoplayer-core@${Xn}`;
|