@vkontakte/videoplayer-core 2.0.140-dev.4c27f703.0 → 2.0.140-dev.7b3cdcf7.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 +39 -39
- package/es2015.esm.js +43 -43
- package/es2018.cjs.js +38 -38
- package/es2018.esm.js +35 -35
- package/es2024.cjs.js +47 -47
- package/es2024.esm.js +44 -44
- package/esnext.cjs.js +47 -47
- package/esnext.esm.js +44 -44
- package/evergreen.esm.js +48 -48
- package/package.json +2 -2
- package/types/player/Player.d.ts +2 -1
- package/types/providers/DashProvider/baseDashProvider.d.ts +1 -0
- package/types/providers/DashProvider/lib/buffer.d.ts +11 -0
- package/types/providers/DashProvider/lib/player.d.ts +1 -0
- package/types/providers/DashProviderNew/lib/buffer.d.ts +2 -0
- package/types/providers/DashProviderNew/lib/player.d.ts +1 -0
- package/types/providers/HlsProvider/index.d.ts +1 -0
- package/types/utils/playerOptions.d.ts +3 -0
- package/types/utils/qualityLimits.d.ts +0 -1
- package/types/utils/tuningConfig.d.ts +6 -1
package/es2024.cjs.js
CHANGED
|
@@ -1,127 +1,127 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.140-dev.
|
|
3
|
-
* Tue,
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.140-dev.7b3cdcf7.0
|
|
3
|
+
* Tue, 09 Sep 2025 14:28:38 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-140/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Lv=Object.create;var ls=Object.defineProperty;var $v=Object.getOwnPropertyDescriptor;var Mv=Object.getOwnPropertyNames;var Dv=Object.getPrototypeOf,Cv=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Bv=(a,e)=>{for(var t in e)ls(a,t,{get:e[t],enumerable:!0})},tc=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Mv(e))!Cv.call(a,r)&&r!==t&&ls(a,r,{get:()=>e[r],enumerable:!(i=$v(e,r))||i.enumerable});return a};var H=(a,e,t)=>(t=a!=null?Lv(Dv(a)):{},tc(e||!a||!a.__esModule?ls(t,"default",{value:a,enumerable:!0}):t,a)),Vv=a=>tc(ls({},"__esModule",{value:!0}),a);var Se=b((to,ic)=>{"use strict";var kr=function(a){return a&&a.Math===Math&&a};ic.exports=kr(typeof globalThis=="object"&&globalThis)||kr(typeof window=="object"&&window)||kr(typeof self=="object"&&self)||kr(typeof global=="object"&&global)||kr(typeof to=="object"&&to)||function(){return this}()||Function("return this")()});var we=b((PL,rc)=>{"use strict";rc.exports=function(a){try{return!!a()}catch{return!0}}});var Rr=b((kL,ac)=>{"use strict";var _v=we();ac.exports=!_v(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var io=b((RL,uc)=>{"use strict";var Ov=Rr(),oc=Function.prototype,sc=oc.apply,nc=oc.call;uc.exports=typeof Reflect=="object"&&Reflect.apply||(Ov?nc.bind(sc):function(){return nc.apply(sc,arguments)})});var Ae=b((LL,dc)=>{"use strict";var lc=Rr(),cc=Function.prototype,ro=cc.call,Fv=lc&&cc.bind.bind(ro,ro);dc.exports=lc?Fv:function(a){return function(){return ro.apply(a,arguments)}}});var pi=b(($L,hc)=>{"use strict";var pc=Ae(),Nv=pc({}.toString),qv=pc("".slice);hc.exports=function(a){return qv(Nv(a),8,-1)}});var ao=b((ML,fc)=>{"use strict";var Uv=pi(),Hv=Ae();fc.exports=function(a){if(Uv(a)==="Function")return Hv(a)}});var ve=b((DL,mc)=>{"use strict";var so=typeof document=="object"&&document.all;mc.exports=typeof so>"u"&&so!==void 0?function(a){return typeof a=="function"||a===so}:function(a){return typeof a=="function"}});var Ke=b((CL,bc)=>{"use strict";var jv=we();bc.exports=!jv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Xe=b((BL,gc)=>{"use strict";var Qv=Rr(),ps=Function.prototype.call;gc.exports=Qv?ps.bind(ps):function(){return ps.apply(ps,arguments)}});var no=b(yc=>{"use strict";var Sc={}.propertyIsEnumerable,vc=Object.getOwnPropertyDescriptor,Wv=vc&&!Sc.call({1:2},1);yc.f=Wv?function(e){var t=vc(this,e);return!!t&&t.enumerable}:Sc});var Lr=b((_L,Tc)=>{"use strict";Tc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Ec=b((OL,Ic)=>{"use strict";var Gv=Ae(),zv=we(),Yv=pi(),oo=Object,Kv=Gv("".split);Ic.exports=zv(function(){return!oo("z").propertyIsEnumerable(0)})?function(a){return Yv(a)==="String"?Kv(a,""):oo(a)}:oo});var $r=b((FL,xc)=>{"use strict";xc.exports=function(a){return a==null}});var Xt=b((NL,wc)=>{"use strict";var Xv=$r(),Jv=TypeError;wc.exports=function(a){if(Xv(a))throw new Jv("Can't call method on "+a);return a}});var hi=b((qL,Ac)=>{"use strict";var Zv=Ec(),ey=Xt();Ac.exports=function(a){return Zv(ey(a))}});var qe=b((UL,Pc)=>{"use strict";var ty=ve();Pc.exports=function(a){return typeof a=="object"?a!==null:ty(a)}});var fi=b((HL,kc)=>{"use strict";kc.exports={}});var Vt=b((jL,Lc)=>{"use strict";var uo=fi(),lo=Se(),iy=ve(),Rc=function(a){return iy(a)?a:void 0};Lc.exports=function(a,e){return arguments.length<2?Rc(uo[a])||Rc(lo[a]):uo[a]&&uo[a][e]||lo[a]&&lo[a][e]}});var Mr=b((QL,$c)=>{"use strict";var ry=Ae();$c.exports=ry({}.isPrototypeOf)});var mi=b((WL,Cc)=>{"use strict";var ay=Se(),Mc=ay.navigator,Dc=Mc&&Mc.userAgent;Cc.exports=Dc?String(Dc):""});var po=b((GL,Nc)=>{"use strict";var Fc=Se(),co=mi(),Bc=Fc.process,Vc=Fc.Deno,_c=Bc&&Bc.versions||Vc&&Vc.version,Oc=_c&&_c.v8,ht,hs;Oc&&(ht=Oc.split("."),hs=ht[0]>0&&ht[0]<4?1:+(ht[0]+ht[1]));!hs&&co&&(ht=co.match(/Edge\/(\d+)/),(!ht||ht[1]>=74)&&(ht=co.match(/Chrome\/(\d+)/),ht&&(hs=+ht[1])));Nc.exports=hs});var ho=b((zL,Uc)=>{"use strict";var qc=po(),sy=we(),ny=Se(),oy=ny.String;Uc.exports=!!Object.getOwnPropertySymbols&&!sy(function(){var a=Symbol("symbol detection");return!oy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&qc&&qc<41})});var fo=b((YL,Hc)=>{"use strict";var uy=ho();Hc.exports=uy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var mo=b((KL,jc)=>{"use strict";var ly=Vt(),cy=ve(),dy=Mr(),py=fo(),hy=Object;jc.exports=py?function(a){return typeof a=="symbol"}:function(a){var e=ly("Symbol");return cy(e)&&dy(e.prototype,hy(a))}});var Dr=b((XL,Qc)=>{"use strict";var fy=String;Qc.exports=function(a){try{return fy(a)}catch{return"Object"}}});var wt=b((JL,Wc)=>{"use strict";var my=ve(),by=Dr(),gy=TypeError;Wc.exports=function(a){if(my(a))return a;throw new gy(by(a)+" is not a function")}});var Cr=b((ZL,Gc)=>{"use strict";var Sy=wt(),vy=$r();Gc.exports=function(a,e){var t=a[e];return vy(t)?void 0:Sy(t)}});var Yc=b((e$,zc)=>{"use strict";var bo=Xe(),go=ve(),So=qe(),yy=TypeError;zc.exports=function(a,e){var t,i;if(e==="string"&&go(t=a.toString)&&!So(i=bo(t,a))||go(t=a.valueOf)&&!So(i=bo(t,a))||e!=="string"&&go(t=a.toString)&&!So(i=bo(t,a)))return i;throw new yy("Can't convert object to primitive value")}});var ft=b((t$,Kc)=>{"use strict";Kc.exports=!0});var Zc=b((i$,Jc)=>{"use strict";var Xc=Se(),Ty=Object.defineProperty;Jc.exports=function(a,e){try{Ty(Xc,a,{value:e,configurable:!0,writable:!0})}catch{Xc[a]=e}return e}});var Br=b((r$,id)=>{"use strict";var Iy=ft(),Ey=Se(),xy=Zc(),ed="__core-js_shared__",td=id.exports=Ey[ed]||xy(ed,{});(td.versions||(td.versions=[])).push({version:"3.43.0",mode:Iy?"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 vo=b((a$,ad)=>{"use strict";var rd=Br();ad.exports=function(a,e){return rd[a]||(rd[a]=e||{})}});var Ni=b((s$,sd)=>{"use strict";var wy=Xt(),Ay=Object;sd.exports=function(a){return Ay(wy(a))}});var mt=b((n$,nd)=>{"use strict";var Py=Ae(),ky=Ni(),Ry=Py({}.hasOwnProperty);nd.exports=Object.hasOwn||function(e,t){return Ry(ky(e),t)}});var yo=b((o$,od)=>{"use strict";var Ly=Ae(),$y=0,My=Math.random(),Dy=Ly(1.1.toString);od.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+Dy(++$y+My,36)}});var $e=b((u$,ld)=>{"use strict";var Cy=Se(),By=vo(),ud=mt(),Vy=yo(),_y=ho(),Oy=fo(),qi=Cy.Symbol,To=By("wks"),Fy=Oy?qi.for||qi:qi&&qi.withoutSetter||Vy;ld.exports=function(a){return ud(To,a)||(To[a]=_y&&ud(qi,a)?qi[a]:Fy("Symbol."+a)),To[a]}});var hd=b((l$,pd)=>{"use strict";var Ny=Xe(),cd=qe(),dd=mo(),qy=Cr(),Uy=Yc(),Hy=$e(),jy=TypeError,Qy=Hy("toPrimitive");pd.exports=function(a,e){if(!cd(a)||dd(a))return a;var t=qy(a,Qy),i;if(t){if(e===void 0&&(e="default"),i=Ny(t,a,e),!cd(i)||dd(i))return i;throw new jy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Uy(a,e)}});var Io=b((c$,fd)=>{"use strict";var Wy=hd(),Gy=mo();fd.exports=function(a){var e=Wy(a,"string");return Gy(e)?e:e+""}});var fs=b((d$,bd)=>{"use strict";var zy=Se(),md=qe(),Eo=zy.document,Yy=md(Eo)&&md(Eo.createElement);bd.exports=function(a){return Yy?Eo.createElement(a):{}}});var xo=b((p$,gd)=>{"use strict";var Ky=Ke(),Xy=we(),Jy=fs();gd.exports=!Ky&&!Xy(function(){return Object.defineProperty(Jy("div"),"a",{get:function(){return 7}}).a!==7})});var yd=b(vd=>{"use strict";var Zy=Ke(),eT=Xe(),tT=no(),iT=Lr(),rT=hi(),aT=Io(),sT=mt(),nT=xo(),Sd=Object.getOwnPropertyDescriptor;vd.f=Zy?Sd:function(e,t){if(e=rT(e),t=aT(t),nT)try{return Sd(e,t)}catch{}if(sT(e,t))return iT(!eT(tT.f,e,t),e[t])}});var wo=b((f$,Td)=>{"use strict";var oT=we(),uT=ve(),lT=/#|\.prototype\./,Vr=function(a,e){var t=dT[cT(a)];return t===hT?!0:t===pT?!1:uT(e)?oT(e):!!e},cT=Vr.normalize=function(a){return String(a).replace(lT,".").toLowerCase()},dT=Vr.data={},pT=Vr.NATIVE="N",hT=Vr.POLYFILL="P";Td.exports=Vr});var Ui=b((m$,Ed)=>{"use strict";var Id=ao(),fT=wt(),mT=Rr(),bT=Id(Id.bind);Ed.exports=function(a,e){return fT(a),e===void 0?a:mT?bT(a,e):function(){return a.apply(e,arguments)}}});var Ao=b((b$,xd)=>{"use strict";var gT=Ke(),ST=we();xd.exports=gT&&ST(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var At=b((g$,wd)=>{"use strict";var vT=qe(),yT=String,TT=TypeError;wd.exports=function(a){if(vT(a))return a;throw new TT(yT(a)+" is not an object")}});var bi=b(Pd=>{"use strict";var IT=Ke(),ET=xo(),xT=Ao(),ms=At(),Ad=Io(),wT=TypeError,Po=Object.defineProperty,AT=Object.getOwnPropertyDescriptor,ko="enumerable",Ro="configurable",Lo="writable";Pd.f=IT?xT?function(e,t,i){if(ms(e),t=Ad(t),ms(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Lo in i&&!i[Lo]){var r=AT(e,t);r&&r[Lo]&&(e[t]=i.value,i={configurable:Ro in i?i[Ro]:r[Ro],enumerable:ko in i?i[ko]:r[ko],writable:!1})}return Po(e,t,i)}:Po:function(e,t,i){if(ms(e),t=Ad(t),ms(i),ET)try{return Po(e,t,i)}catch{}if("get"in i||"set"in i)throw new wT("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Hi=b((v$,kd)=>{"use strict";var PT=Ke(),kT=bi(),RT=Lr();kd.exports=PT?function(a,e,t){return kT.f(a,e,RT(1,t))}:function(a,e,t){return a[e]=t,a}});var Te=b((y$,Ld)=>{"use strict";var _r=Se(),LT=io(),$T=ao(),MT=ve(),DT=yd().f,CT=wo(),ji=fi(),BT=Ui(),Qi=Hi(),Rd=mt();Br();var VT=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 LT(a,this,arguments)};return e.prototype=a.prototype,e};Ld.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?_r:r?_r[t]:_r[t]&&_r[t].prototype,u=i?ji:ji[t]||Qi(ji,t,{})[t],o=u.prototype,l,c,p,d,h,m,g,v,S;for(d in e)l=CT(i?d:t+(r?".":"#")+d,a.forced),c=!l&&n&&Rd(n,d),m=u[d],c&&(a.dontCallGetSet?(S=DT(n,d),g=S&&S.value):g=n[d]),h=c&&g?g:e[d],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?v=BT(h,_r):a.wrap&&c?v=VT(h):s&&MT(h)?v=$T(h):v=h,(a.sham||h&&h.sham||m&&m.sham)&&Qi(v,"sham",!0),Qi(u,d,v),s&&(p=t+"Prototype",Rd(ji,p)||Qi(ji,p,{}),Qi(ji[p],d,h),a.real&&o&&(l||!o[d])&&Qi(o,d,h)))}});var bs=b((T$,Md)=>{"use strict";var _T=vo(),OT=yo(),$d=_T("keys");Md.exports=function(a){return $d[a]||($d[a]=OT(a))}});var Cd=b((I$,Dd)=>{"use strict";var FT=we();Dd.exports=!FT(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var gs=b((E$,Vd)=>{"use strict";var NT=mt(),qT=ve(),UT=Ni(),HT=bs(),jT=Cd(),Bd=HT("IE_PROTO"),$o=Object,QT=$o.prototype;Vd.exports=jT?$o.getPrototypeOf:function(a){var e=UT(a);if(NT(e,Bd))return e[Bd];var t=e.constructor;return qT(t)&&e instanceof t?t.prototype:e instanceof $o?QT:null}});var Od=b((x$,_d)=>{"use strict";var WT=Math.ceil,GT=Math.floor;_d.exports=Math.trunc||function(e){var t=+e;return(t>0?GT:WT)(t)}});var Or=b((w$,Fd)=>{"use strict";var zT=Od();Fd.exports=function(a){var e=+a;return e!==e||e===0?0:zT(e)}});var qd=b((A$,Nd)=>{"use strict";var YT=Or(),KT=Math.max,XT=Math.min;Nd.exports=function(a,e){var t=YT(a);return t<0?KT(t+e,0):XT(t,e)}});var Mo=b((P$,Ud)=>{"use strict";var JT=Or(),ZT=Math.min;Ud.exports=function(a){var e=JT(a);return e>0?ZT(e,9007199254740991):0}});var Wi=b((k$,Hd)=>{"use strict";var eI=Mo();Hd.exports=function(a){return eI(a.length)}});var Do=b((R$,Qd)=>{"use strict";var tI=hi(),iI=qd(),rI=Wi(),jd=function(a){return function(e,t,i){var r=tI(e),s=rI(r);if(s===0)return!a&&-1;var n=iI(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}};Qd.exports={includes:jd(!0),indexOf:jd(!1)}});var Ss=b((L$,Wd)=>{"use strict";Wd.exports={}});var Yd=b(($$,zd)=>{"use strict";var aI=Ae(),Co=mt(),sI=hi(),nI=Do().indexOf,oI=Ss(),Gd=aI([].push);zd.exports=function(a,e){var t=sI(a),i=0,r=[],s;for(s in t)!Co(oI,s)&&Co(t,s)&&Gd(r,s);for(;e.length>i;)Co(t,s=e[i++])&&(~nI(r,s)||Gd(r,s));return r}});var Bo=b((M$,Kd)=>{"use strict";Kd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Vo=b((D$,Xd)=>{"use strict";var uI=Yd(),lI=Bo();Xd.exports=Object.keys||function(e){return uI(e,lI)}});var _o=b((C$,ip)=>{"use strict";var Zd=Ke(),cI=we(),ep=Ae(),dI=gs(),pI=Vo(),hI=hi(),fI=no().f,tp=ep(fI),mI=ep([].push),bI=Zd&&cI(function(){var a=Object.create(null);return a[2]=2,!tp(a,2)}),Jd=function(a){return function(e){for(var t=hI(e),i=pI(t),r=bI&&dI(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!Zd||(r?o in t:tp(t,o)))&&mI(u,a?[o,t[o]]:t[o]);return u}};ip.exports={entries:Jd(!0),values:Jd(!1)}});var rp=b(()=>{"use strict";var gI=Te(),SI=_o().values;gI({target:"Object",stat:!0},{values:function(e){return SI(e)}})});var sp=b((_$,ap)=>{"use strict";rp();var vI=fi();ap.exports=vI.Object.values});var op=b((O$,np)=>{"use strict";var yI=sp();np.exports=yI});var gi=b((F$,up)=>{"use strict";var TI=op();up.exports=TI});var Fr=b((N$,lp)=>{"use strict";lp.exports=function(){}});var cp=b(()=>{"use strict";var II=Te(),EI=Do().includes,xI=we(),wI=Fr(),AI=xI(function(){return!Array(1).includes()});II({target:"Array",proto:!0,forced:AI},{includes:function(e){return EI(this,e,arguments.length>1?arguments[1]:void 0)}});wI("includes")});var Jt=b((H$,dp)=>{"use strict";var PI=Vt();dp.exports=PI});var hp=b((j$,pp)=>{"use strict";cp();var kI=Jt();pp.exports=kI("Array","includes")});var mp=b((Q$,fp)=>{"use strict";var RI=hp();fp.exports=RI});var _e=b((W$,bp)=>{"use strict";var LI=mp();bp.exports=LI});var Sp=b(()=>{"use strict";var MI=Te(),DI=_o().entries;MI({target:"Object",stat:!0},{entries:function(e){return DI(e)}})});var yp=b((sM,vp)=>{"use strict";Sp();var CI=fi();vp.exports=CI.Object.entries});var Ip=b((nM,Tp)=>{"use strict";var BI=yp();Tp.exports=BI});var Gi=b((oM,Ep)=>{"use strict";var VI=Ip();Ep.exports=VI});var Si=b((uM,xp)=>{"use strict";xp.exports={}});var Pp=b((lM,Ap)=>{"use strict";var _I=Se(),OI=ve(),wp=_I.WeakMap;Ap.exports=OI(wp)&&/native code/.test(String(wp))});var qo=b((cM,Lp)=>{"use strict";var FI=Pp(),Rp=Se(),NI=qe(),qI=Hi(),Oo=mt(),Fo=Br(),UI=bs(),HI=Ss(),kp="Object already initialized",No=Rp.TypeError,jI=Rp.WeakMap,ys,Nr,Ts,QI=function(a){return Ts(a)?Nr(a):ys(a,{})},WI=function(a){return function(e){var t;if(!NI(e)||(t=Nr(e)).type!==a)throw new No("Incompatible receiver, "+a+" required");return t}};FI||Fo.state?(bt=Fo.state||(Fo.state=new jI),bt.get=bt.get,bt.has=bt.has,bt.set=bt.set,ys=function(a,e){if(bt.has(a))throw new No(kp);return e.facade=a,bt.set(a,e),e},Nr=function(a){return bt.get(a)||{}},Ts=function(a){return bt.has(a)}):(vi=UI("state"),HI[vi]=!0,ys=function(a,e){if(Oo(a,vi))throw new No(kp);return e.facade=a,qI(a,vi,e),e},Nr=function(a){return Oo(a,vi)?a[vi]:{}},Ts=function(a){return Oo(a,vi)});var bt,vi;Lp.exports={set:ys,get:Nr,has:Ts,enforce:QI,getterFor:WI}});var jo=b((dM,Mp)=>{"use strict";var Uo=Ke(),GI=mt(),$p=Function.prototype,zI=Uo&&Object.getOwnPropertyDescriptor,Ho=GI($p,"name"),YI=Ho&&function(){}.name==="something",KI=Ho&&(!Uo||Uo&&zI($p,"name").configurable);Mp.exports={EXISTS:Ho,PROPER:YI,CONFIGURABLE:KI}});var Cp=b(Dp=>{"use strict";var XI=Ke(),JI=Ao(),ZI=bi(),eE=At(),tE=hi(),iE=Vo();Dp.f=XI&&!JI?Object.defineProperties:function(e,t){eE(e);for(var i=tE(t),r=iE(t),s=r.length,n=0,u;s>n;)ZI.f(e,u=r[n++],i[u]);return e}});var Qo=b((hM,Bp)=>{"use strict";var rE=Vt();Bp.exports=rE("document","documentElement")});var Yo=b((fM,Up)=>{"use strict";var aE=At(),sE=Cp(),Vp=Bo(),nE=Ss(),oE=Qo(),uE=fs(),lE=bs(),_p=">",Op="<",Go="prototype",zo="script",Np=lE("IE_PROTO"),Wo=function(){},qp=function(a){return Op+zo+_p+a+Op+"/"+zo+_p},Fp=function(a){a.write(qp("")),a.close();var e=a.parentWindow.Object;return a=null,e},cE=function(){var a=uE("iframe"),e="java"+zo+":",t;return a.style.display="none",oE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(qp("document.F=Object")),t.close(),t.F},Is,Es=function(){try{Is=new ActiveXObject("htmlfile")}catch{}Es=typeof document<"u"?document.domain&&Is?Fp(Is):cE():Fp(Is);for(var a=Vp.length;a--;)delete Es[Go][Vp[a]];return Es()};nE[Np]=!0;Up.exports=Object.create||function(e,t){var i;return e!==null?(Wo[Go]=aE(e),i=new Wo,Wo[Go]=null,i[Np]=e):i=Es(),t===void 0?i:sE.f(i,t)}});var zi=b((mM,Hp)=>{"use strict";var dE=Hi();Hp.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:dE(a,e,t),a}});var Zo=b((bM,Wp)=>{"use strict";var pE=we(),hE=ve(),fE=qe(),mE=Yo(),jp=gs(),bE=zi(),gE=$e(),SE=ft(),Jo=gE("iterator"),Qp=!1,_t,Ko,Xo;[].keys&&(Xo=[].keys(),"next"in Xo?(Ko=jp(jp(Xo)),Ko!==Object.prototype&&(_t=Ko)):Qp=!0);var vE=!fE(_t)||pE(function(){var a={};return _t[Jo].call(a)!==a});vE?_t={}:SE&&(_t=mE(_t));hE(_t[Jo])||bE(_t,Jo,function(){return this});Wp.exports={IteratorPrototype:_t,BUGGY_SAFARI_ITERATORS:Qp}});var xs=b((gM,zp)=>{"use strict";var yE=$e(),TE=yE("toStringTag"),Gp={};Gp[TE]="z";zp.exports=String(Gp)==="[object z]"});var qr=b((SM,Yp)=>{"use strict";var IE=xs(),EE=ve(),ws=pi(),xE=$e(),wE=xE("toStringTag"),AE=Object,PE=ws(function(){return arguments}())==="Arguments",kE=function(a,e){try{return a[e]}catch{}};Yp.exports=IE?ws:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=kE(e=AE(a),wE))=="string"?t:PE?ws(e):(i=ws(e))==="Object"&&EE(e.callee)?"Arguments":i}});var Xp=b((vM,Kp)=>{"use strict";var RE=xs(),LE=qr();Kp.exports=RE?{}.toString:function(){return"[object "+LE(this)+"]"}});var Ur=b((yM,Zp)=>{"use strict";var $E=xs(),ME=bi().f,DE=Hi(),CE=mt(),BE=Xp(),VE=$e(),Jp=VE("toStringTag");Zp.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(CE(r,Jp)||ME(r,Jp,{configurable:!0,value:e}),i&&!$E&&DE(r,"toString",BE))}});var th=b((TM,eh)=>{"use strict";var _E=Zo().IteratorPrototype,OE=Yo(),FE=Lr(),NE=Ur(),qE=Si(),UE=function(){return this};eh.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=OE(_E,{next:FE(+!i,t)}),NE(a,r,!1,!0),qE[r]=UE,a}});var rh=b((IM,ih)=>{"use strict";var HE=Ae(),jE=wt();ih.exports=function(a,e,t){try{return HE(jE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var sh=b((EM,ah)=>{"use strict";var QE=qe();ah.exports=function(a){return QE(a)||a===null}});var oh=b((xM,nh)=>{"use strict";var WE=sh(),GE=String,zE=TypeError;nh.exports=function(a){if(WE(a))return a;throw new zE("Can't set "+GE(a)+" as a prototype")}});var eu=b((wM,uh)=>{"use strict";var YE=rh(),KE=qe(),XE=Xt(),JE=oh();uh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=YE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return XE(r),JE(s),KE(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var vh=b((AM,Sh)=>{"use strict";var ZE=Te(),ex=Xe(),As=ft(),bh=jo(),tx=ve(),ix=th(),lh=gs(),ch=eu(),rx=Ur(),ax=Hi(),tu=zi(),sx=$e(),dh=Si(),gh=Zo(),nx=bh.PROPER,ox=bh.CONFIGURABLE,ph=gh.IteratorPrototype,Ps=gh.BUGGY_SAFARI_ITERATORS,Hr=sx("iterator"),hh="keys",jr="values",fh="entries",mh=function(){return this};Sh.exports=function(a,e,t,i,r,s,n){ix(t,e,i);var u=function(S){if(S===r&&d)return d;if(!Ps&&S&&S in c)return c[S];switch(S){case hh:return function(){return new t(this,S)};case jr:return function(){return new t(this,S)};case fh:return function(){return new t(this,S)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,c=a.prototype,p=c[Hr]||c["@@iterator"]||r&&c[r],d=!Ps&&p||u(r),h=e==="Array"&&c.entries||p,m,g,v;if(h&&(m=lh(h.call(new a)),m!==Object.prototype&&m.next&&(!As&&lh(m)!==ph&&(ch?ch(m,ph):tx(m[Hr])||tu(m,Hr,mh)),rx(m,o,!0,!0),As&&(dh[o]=mh))),nx&&r===jr&&p&&p.name!==jr&&(!As&&ox?ax(c,"name",jr):(l=!0,d=function(){return ex(p,this)})),r)if(g={values:u(jr),keys:s?d:u(hh),entries:u(fh)},n)for(v in g)(Ps||l||!(v in c))&&tu(c,v,g[v]);else ZE({target:e,proto:!0,forced:Ps||l},g);return(!As||n)&&c[Hr]!==d&&tu(c,Hr,d,{name:r}),dh[e]=d,g}});var Th=b((PM,yh)=>{"use strict";yh.exports=function(a,e){return{value:a,done:e}}});var ru=b((kM,Ah)=>{"use strict";var ux=hi(),iu=Fr(),Ih=Si(),xh=qo(),lx=bi().f,cx=vh(),ks=Th(),dx=ft(),px=Ke(),wh="Array Iterator",hx=xh.set,fx=xh.getterFor(wh);Ah.exports=cx(Array,"Array",function(a,e){hx(this,{type:wh,target:ux(a),index:0,kind:e})},function(){var a=fx(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 Eh=Ih.Arguments=Ih.Array;iu("keys");iu("values");iu("entries");if(!dx&&px&&Eh.name!=="values")try{lx(Eh,"name",{value:"values"})}catch{}});var kh=b((RM,Ph)=>{"use strict";var mx=$e(),bx=Si(),gx=mx("iterator"),Sx=Array.prototype;Ph.exports=function(a){return a!==void 0&&(bx.Array===a||Sx[gx]===a)}});var au=b((LM,Lh)=>{"use strict";var vx=qr(),Rh=Cr(),yx=$r(),Tx=Si(),Ix=$e(),Ex=Ix("iterator");Lh.exports=function(a){if(!yx(a))return Rh(a,Ex)||Rh(a,"@@iterator")||Tx[vx(a)]}});var Mh=b(($M,$h)=>{"use strict";var xx=Xe(),wx=wt(),Ax=At(),Px=Dr(),kx=au(),Rx=TypeError;$h.exports=function(a,e){var t=arguments.length<2?kx(a):e;if(wx(t))return Ax(xx(t,a));throw new Rx(Px(a)+" is not iterable")}});var Bh=b((MM,Ch)=>{"use strict";var Lx=Xe(),Dh=At(),$x=Cr();Ch.exports=function(a,e,t){var i,r;Dh(a);try{if(i=$x(a,"return"),!i){if(e==="throw")throw t;return t}i=Lx(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Dh(i),t}});var Ls=b((DM,Fh)=>{"use strict";var Mx=Ui(),Dx=Xe(),Cx=At(),Bx=Dr(),Vx=kh(),_x=Wi(),Vh=Mr(),Ox=Mh(),Fx=au(),_h=Bh(),Nx=TypeError,Rs=function(a,e){this.stopped=a,this.result=e},Oh=Rs.prototype;Fh.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=Mx(e,i),l,c,p,d,h,m,g,v=function(A){return l&&_h(l,"normal"),new Rs(!0,A)},S=function(A){return r?(Cx(A),u?o(A[0],A[1],v):o(A[0],A[1])):u?o(A,v):o(A)};if(s)l=a.iterator;else if(n)l=a;else{if(c=Fx(a),!c)throw new Nx(Bx(a)+" is not iterable");if(Vx(c)){for(p=0,d=_x(a);d>p;p++)if(h=S(a[p]),h&&Vh(Oh,h))return h;return new Rs(!1)}l=Ox(a,c)}for(m=s?a.next:l.next;!(g=Dx(m,l)).done;){try{h=S(g.value)}catch(A){_h(l,"throw",A)}if(typeof h=="object"&&h&&Vh(Oh,h))return h}return new Rs(!1)}});var qh=b((CM,Nh)=>{"use strict";var qx=Ke(),Ux=bi(),Hx=Lr();Nh.exports=function(a,e,t){qx?Ux.f(a,e,Hx(0,t)):a[e]=t}});var Uh=b(()=>{"use strict";var jx=Te(),Qx=Ls(),Wx=qh();jx({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Qx(e,function(i,r){Wx(t,i,r)},{AS_ENTRIES:!0}),t}})});var jh=b((_M,Hh)=>{"use strict";ru();Uh();var Gx=fi();Hh.exports=Gx.Object.fromEntries});var Wh=b((OM,Qh)=>{"use strict";Qh.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 zh=b(()=>{"use strict";ru();var zx=Wh(),Yx=Se(),Kx=Ur(),Gh=Si();for($s in zx)Kx(Yx[$s],$s),Gh[$s]=Gh.Array;var $s});var Kh=b((qM,Yh)=>{"use strict";var Xx=jh();zh();Yh.exports=Xx});var su=b((UM,Xh)=>{"use strict";var Jx=Kh();Xh.exports=Jx});var Jh=b(()=>{"use strict"});var nu=b((QM,Zh)=>{"use strict";var Qr=Se(),Zx=mi(),ew=pi(),Ms=function(a){return Zx.slice(0,a.length)===a};Zh.exports=function(){return Ms("Bun/")?"BUN":Ms("Cloudflare-Workers")?"CLOUDFLARE":Ms("Deno/")?"DENO":Ms("Node.js/")?"NODE":Qr.Bun&&typeof Bun.version=="string"?"BUN":Qr.Deno&&typeof Deno.version=="object"?"DENO":ew(Qr.process)==="process"?"NODE":Qr.window&&Qr.document?"BROWSER":"REST"}()});var Ds=b((WM,ef)=>{"use strict";var tw=nu();ef.exports=tw==="NODE"});var rf=b((GM,tf)=>{"use strict";var iw=bi();tf.exports=function(a,e,t){return iw.f(a,e,t)}});var nf=b((zM,sf)=>{"use strict";var rw=Vt(),aw=rf(),sw=$e(),nw=Ke(),af=sw("species");sf.exports=function(a){var e=rw(a);nw&&e&&!e[af]&&aw(e,af,{configurable:!0,get:function(){return this}})}});var uf=b((YM,of)=>{"use strict";var ow=Mr(),uw=TypeError;of.exports=function(a,e){if(ow(e,a))return a;throw new uw("Incorrect invocation")}});var uu=b((KM,lf)=>{"use strict";var lw=Ae(),cw=ve(),ou=Br(),dw=lw(Function.toString);cw(ou.inspectSource)||(ou.inspectSource=function(a){return dw(a)});lf.exports=ou.inspectSource});var cu=b((XM,ff)=>{"use strict";var pw=Ae(),hw=we(),cf=ve(),fw=qr(),mw=Vt(),bw=uu(),df=function(){},pf=mw("Reflect","construct"),lu=/^\s*(?:class|function)\b/,gw=pw(lu.exec),Sw=!lu.test(df),Wr=function(e){if(!cf(e))return!1;try{return pf(df,[],e),!0}catch{return!1}},hf=function(e){if(!cf(e))return!1;switch(fw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Sw||!!gw(lu,bw(e))}catch{return!0}};hf.sham=!0;ff.exports=!pf||hw(function(){var a;return Wr(Wr.call)||!Wr(Object)||!Wr(function(){a=!0})||a})?hf:Wr});var bf=b((JM,mf)=>{"use strict";var vw=cu(),yw=Dr(),Tw=TypeError;mf.exports=function(a){if(vw(a))return a;throw new Tw(yw(a)+" is not a constructor")}});var du=b((ZM,Sf)=>{"use strict";var gf=At(),Iw=bf(),Ew=$r(),xw=$e(),ww=xw("species");Sf.exports=function(a,e){var t=gf(a).constructor,i;return t===void 0||Ew(i=gf(t)[ww])?e:Iw(i)}});var yf=b((eD,vf)=>{"use strict";var Aw=Ae();vf.exports=Aw([].slice)});var If=b((tD,Tf)=>{"use strict";var Pw=TypeError;Tf.exports=function(a,e){if(a<e)throw new Pw("Not enough arguments");return a}});var pu=b((iD,Ef)=>{"use strict";var kw=mi();Ef.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(kw)});var Tu=b((rD,Mf)=>{"use strict";var Je=Se(),Rw=io(),Lw=Ui(),xf=ve(),$w=mt(),$f=we(),wf=Qo(),Mw=yf(),Af=fs(),Dw=If(),Cw=pu(),Bw=Ds(),Su=Je.setImmediate,vu=Je.clearImmediate,Vw=Je.process,hu=Je.Dispatch,_w=Je.Function,Pf=Je.MessageChannel,Ow=Je.String,fu=0,Gr={},kf="onreadystatechange",zr,yi,mu,bu;$f(function(){zr=Je.location});var yu=function(a){if($w(Gr,a)){var e=Gr[a];delete Gr[a],e()}},gu=function(a){return function(){yu(a)}},Rf=function(a){yu(a.data)},Lf=function(a){Je.postMessage(Ow(a),zr.protocol+"//"+zr.host)};(!Su||!vu)&&(Su=function(e){Dw(arguments.length,1);var t=xf(e)?e:_w(e),i=Mw(arguments,1);return Gr[++fu]=function(){Rw(t,void 0,i)},yi(fu),fu},vu=function(e){delete Gr[e]},Bw?yi=function(a){Vw.nextTick(gu(a))}:hu&&hu.now?yi=function(a){hu.now(gu(a))}:Pf&&!Cw?(mu=new Pf,bu=mu.port2,mu.port1.onmessage=Rf,yi=Lw(bu.postMessage,bu)):Je.addEventListener&&xf(Je.postMessage)&&!Je.importScripts&&zr&&zr.protocol!=="file:"&&!$f(Lf)?(yi=Lf,Je.addEventListener("message",Rf,!1)):kf in Af("script")?yi=function(a){wf.appendChild(Af("script"))[kf]=function(){wf.removeChild(this),yu(a)}}:yi=function(a){setTimeout(gu(a),0)});Mf.exports={set:Su,clear:vu}});var Bf=b((aD,Cf)=>{"use strict";var Df=Se(),Fw=Ke(),Nw=Object.getOwnPropertyDescriptor;Cf.exports=function(a){if(!Fw)return Df[a];var e=Nw(Df,a);return e&&e.value}});var Iu=b((sD,_f)=>{"use strict";var Vf=function(){this.head=null,this.tail=null};Vf.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}}};_f.exports=Vf});var Ff=b((nD,Of)=>{"use strict";var qw=mi();Of.exports=/ipad|iphone|ipod/i.test(qw)&&typeof Pebble<"u"});var qf=b((oD,Nf)=>{"use strict";var Uw=mi();Nf.exports=/web0s(?!.*chrome)/i.test(Uw)});var zf=b((uD,Gf)=>{"use strict";var Ki=Se(),Hw=Bf(),Uf=Ui(),Eu=Tu().set,jw=Iu(),Qw=pu(),Ww=Ff(),Gw=qf(),xu=Ds(),Hf=Ki.MutationObserver||Ki.WebKitMutationObserver,jf=Ki.document,Qf=Ki.process,Cs=Ki.Promise,Pu=Hw("queueMicrotask"),Yi,wu,Au,Bs,Wf;Pu||(Yr=new jw,Kr=function(){var a,e;for(xu&&(a=Qf.domain)&&a.exit();e=Yr.get();)try{e()}catch(t){throw Yr.head&&Yi(),t}a&&a.enter()},!Qw&&!xu&&!Gw&&Hf&&jf?(wu=!0,Au=jf.createTextNode(""),new Hf(Kr).observe(Au,{characterData:!0}),Yi=function(){Au.data=wu=!wu}):!Ww&&Cs&&Cs.resolve?(Bs=Cs.resolve(void 0),Bs.constructor=Cs,Wf=Uf(Bs.then,Bs),Yi=function(){Wf(Kr)}):xu?Yi=function(){Qf.nextTick(Kr)}:(Eu=Uf(Eu,Ki),Yi=function(){Eu(Kr)}),Pu=function(a){Yr.head||Yi(),Yr.add(a)});var Yr,Kr;Gf.exports=Pu});var Kf=b((lD,Yf)=>{"use strict";Yf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var Vs=b((cD,Xf)=>{"use strict";Xf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ti=b((dD,Jf)=>{"use strict";var zw=Se();Jf.exports=zw.Promise});var Xi=b((pD,im)=>{"use strict";var Yw=Se(),Xr=Ti(),Kw=ve(),Xw=wo(),Jw=uu(),Zw=$e(),Zf=nu(),eA=ft(),ku=po(),em=Xr&&Xr.prototype,tA=Zw("species"),Ru=!1,tm=Kw(Yw.PromiseRejectionEvent),iA=Xw("Promise",function(){var a=Jw(Xr),e=a!==String(Xr);if(!e&&ku===66||eA&&!(em.catch&&em.finally))return!0;if(!ku||ku<51||!/native code/.test(a)){var t=new Xr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[tA]=i,Ru=t.then(function(){})instanceof i,!Ru)return!0}return!e&&(Zf==="BROWSER"||Zf==="DENO")&&!tm});im.exports={CONSTRUCTOR:iA,REJECTION_EVENT:tm,SUBCLASSING:Ru}});var Ji=b((hD,am)=>{"use strict";var rm=wt(),rA=TypeError,aA=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new rA("Bad Promise constructor");e=i,t=r}),this.resolve=rm(e),this.reject=rm(t)};am.exports.f=function(a){return new aA(a)}});var xm=b(()=>{"use strict";var sA=Te(),nA=ft(),Ns=Ds(),Zt=Se(),oA=fi(),ir=Xe(),sm=zi(),nm=eu(),uA=Ur(),lA=nf(),cA=wt(),Fs=ve(),dA=qe(),pA=uf(),hA=du(),dm=Tu().set,Cu=zf(),fA=Kf(),mA=Vs(),bA=Iu(),pm=qo(),qs=Ti(),Bu=Xi(),hm=Ji(),Us="Promise",fm=Bu.CONSTRUCTOR,gA=Bu.REJECTION_EVENT,SA=Bu.SUBCLASSING,Lu=pm.getterFor(Us),vA=pm.set,Zi=qs&&qs.prototype,Ii=qs,_s=Zi,mm=Zt.TypeError,$u=Zt.document,Vu=Zt.process,Mu=hm.f,yA=Mu,TA=!!($u&&$u.createEvent&&Zt.dispatchEvent),bm="unhandledrejection",IA="rejectionhandled",om=0,gm=1,EA=2,_u=1,Sm=2,Os,um,vm,lm,ym=function(a){var e;return dA(a)&&Fs(e=a.then)?e:!1},Tm=function(a,e){var t=e.value,i=e.state===gm,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,c;try{r?(i||(e.rejection===Sm&&wA(e),e.rejection=_u),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),c=!0)),o===a.promise?n(new mm("Promise-chain cycle")):(l=ym(o))?ir(l,o,s,n):s(o)):n(t)}catch(p){u&&!c&&u.exit(),n(p)}},Im=function(a,e){a.notified||(a.notified=!0,Cu(function(){for(var t=a.reactions,i;i=t.get();)Tm(i,a);a.notified=!1,e&&!a.rejection&&xA(a)}))},Em=function(a,e,t){var i,r;TA?(i=$u.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Zt.dispatchEvent(i)):i={promise:e,reason:t},!gA&&(r=Zt["on"+a])?r(i):a===bm&&fA("Unhandled promise rejection",t)},xA=function(a){ir(dm,Zt,function(){var e=a.facade,t=a.value,i=cm(a),r;if(i&&(r=mA(function(){Ns?Vu.emit("unhandledRejection",t,e):Em(bm,e,t)}),a.rejection=Ns||cm(a)?Sm:_u,r.error))throw r.value})},cm=function(a){return a.rejection!==_u&&!a.parent},wA=function(a){ir(dm,Zt,function(){var e=a.facade;Ns?Vu.emit("rejectionHandled",e):Em(IA,e,a.value)})},er=function(a,e,t){return function(i){a(e,i,t)}},tr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=EA,Im(a,!0))},Du=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new mm("Promise can't be resolved itself");var i=ym(e);i?Cu(function(){var r={done:!1};try{ir(i,e,er(Du,r,a),er(tr,r,a))}catch(s){tr(r,s,a)}}):(a.value=e,a.state=gm,Im(a,!1))}catch(r){tr({done:!1},r,a)}}};if(fm&&(Ii=function(e){pA(this,_s),cA(e),ir(Os,this);var t=Lu(this);try{e(er(Du,t),er(tr,t))}catch(i){tr(t,i)}},_s=Ii.prototype,Os=function(e){vA(this,{type:Us,done:!1,notified:!1,parent:!1,reactions:new bA,rejection:!1,state:om,value:null})},Os.prototype=sm(_s,"then",function(e,t){var i=Lu(this),r=Mu(hA(this,Ii));return i.parent=!0,r.ok=Fs(e)?e:!0,r.fail=Fs(t)&&t,r.domain=Ns?Vu.domain:void 0,i.state===om?i.reactions.add(r):Cu(function(){Tm(r,i)}),r.promise}),um=function(){var a=new Os,e=Lu(a);this.promise=a,this.resolve=er(Du,e),this.reject=er(tr,e)},hm.f=Mu=function(a){return a===Ii||a===vm?new um(a):yA(a)},!nA&&Fs(qs)&&Zi!==Object.prototype)){lm=Zi.then,SA||sm(Zi,"then",function(e,t){var i=this;return new Ii(function(r,s){ir(lm,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Zi.constructor}catch{}nm&&nm(Zi,_s)}sA({global:!0,constructor:!0,wrap:!0,forced:fm},{Promise:Ii});vm=oA.Promise;uA(Ii,Us,!1,!0);lA(Us)});var Rm=b((bD,km)=>{"use strict";var AA=$e(),Am=AA("iterator"),Pm=!1;try{wm=0,Ou={next:function(){return{done:!!wm++}},return:function(){Pm=!0}},Ou[Am]=function(){return this},Array.from(Ou,function(){throw 2})}catch{}var wm,Ou;km.exports=function(a,e){try{if(!e&&!Pm)return!1}catch{return!1}var t=!1;try{var i={};i[Am]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Fu=b((gD,Lm)=>{"use strict";var PA=Ti(),kA=Rm(),RA=Xi().CONSTRUCTOR;Lm.exports=RA||!kA(function(a){PA.all(a).then(void 0,function(){})})});var $m=b(()=>{"use strict";var LA=Te(),$A=Xe(),MA=wt(),DA=Ji(),CA=Vs(),BA=Ls(),VA=Fu();LA({target:"Promise",stat:!0,forced:VA},{all:function(e){var t=this,i=DA.f(t),r=i.resolve,s=i.reject,n=CA(function(){var u=MA(t.resolve),o=[],l=0,c=1;BA(e,function(p){var d=l++,h=!1;c++,$A(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 Dm=b(()=>{"use strict";var _A=Te(),OA=ft(),FA=Xi().CONSTRUCTOR,qu=Ti(),NA=Vt(),qA=ve(),UA=zi(),Mm=qu&&qu.prototype;_A({target:"Promise",proto:!0,forced:FA,real:!0},{catch:function(a){return this.then(void 0,a)}});!OA&&qA(qu)&&(Nu=NA("Promise").prototype.catch,Mm.catch!==Nu&&UA(Mm,"catch",Nu,{unsafe:!0}));var Nu});var Cm=b(()=>{"use strict";var HA=Te(),jA=Xe(),QA=wt(),WA=Ji(),GA=Vs(),zA=Ls(),YA=Fu();HA({target:"Promise",stat:!0,forced:YA},{race:function(e){var t=this,i=WA.f(t),r=i.reject,s=GA(function(){var n=QA(t.resolve);zA(e,function(u){jA(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Bm=b(()=>{"use strict";var KA=Te(),XA=Ji(),JA=Xi().CONSTRUCTOR;KA({target:"Promise",stat:!0,forced:JA},{reject:function(e){var t=XA.f(this),i=t.reject;return i(e),t.promise}})});var Uu=b((AD,Vm)=>{"use strict";var ZA=At(),eP=qe(),tP=Ji();Vm.exports=function(a,e){if(ZA(a),eP(e)&&e.constructor===a)return e;var t=tP.f(a),i=t.resolve;return i(e),t.promise}});var Fm=b(()=>{"use strict";var iP=Te(),rP=Vt(),_m=ft(),aP=Ti(),Om=Xi().CONSTRUCTOR,sP=Uu(),nP=rP("Promise"),oP=_m&&!Om;iP({target:"Promise",stat:!0,forced:_m||Om},{resolve:function(e){return sP(oP&&this===nP?aP:this,e)}})});var Nm=b(()=>{"use strict";xm();$m();Dm();Cm();Bm();Fm()});var jm=b(()=>{"use strict";var uP=Te(),lP=ft(),Hs=Ti(),cP=we(),Um=Vt(),Hm=ve(),dP=du(),qm=Uu(),pP=zi(),ju=Hs&&Hs.prototype,hP=!!Hs&&cP(function(){ju.finally.call({then:function(){}},function(){})});uP({target:"Promise",proto:!0,real:!0,forced:hP},{finally:function(a){var e=dP(this,Um("Promise")),t=Hm(a);return this.then(t?function(i){return qm(e,a()).then(function(){return i})}:a,t?function(i){return qm(e,a()).then(function(){throw i})}:a)}});!lP&&Hm(Hs)&&(Hu=Um("Promise").prototype.finally,ju.finally!==Hu&&pP(ju,"finally",Hu,{unsafe:!0}));var Hu});var Wm=b((DD,Qm)=>{"use strict";Jh();Nm();jm();var fP=Jt();Qm.exports=fP("Promise","finally")});var zm=b((CD,Gm)=>{"use strict";var mP=Wm();Gm.exports=mP});var js=b((BD,Ym)=>{"use strict";var bP=zm();Ym.exports=bP});var db=b(()=>{"use strict";var LP=Te(),$P=Ni(),MP=Wi(),DP=Or(),CP=Fr();LP({target:"Array",proto:!0},{at:function(e){var t=$P(this),i=MP(t),r=DP(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});CP("at")});var hb=b((fB,pb)=>{"use strict";db();var BP=Jt();pb.exports=BP("Array","at")});var mb=b((mB,fb)=>{"use strict";var VP=hb();fb.exports=VP});var gt=b((bB,bb)=>{"use strict";var _P=mb();bb.exports=_P});var pl=b((K0,Nb)=>{"use strict";var zP=pi();Nb.exports=Array.isArray||function(e){return zP(e)==="Array"}});var Ub=b((X0,qb)=>{"use strict";var YP=TypeError,KP=9007199254740991;qb.exports=function(a){if(a>KP)throw YP("Maximum allowed index exceeded");return a}});var Qb=b((J0,jb)=>{"use strict";var XP=pl(),JP=Wi(),ZP=Ub(),ek=Ui(),Hb=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,c=n?ek(n,u):!1,p,d;l<i;)l in t&&(p=c?c(t[l],l,e):t[l],s>0&&XP(p)?(d=JP(p),o=Hb(a,e,p,d,o,s-1)-1):(ZP(o+1),a[o]=p),o++),l++;return o};jb.exports=Hb});var Yb=b((Z0,zb)=>{"use strict";var Wb=pl(),tk=cu(),ik=qe(),rk=$e(),ak=rk("species"),Gb=Array;zb.exports=function(a){var e;return Wb(a)&&(e=a.constructor,tk(e)&&(e===Gb||Wb(e.prototype))?e=void 0:ik(e)&&(e=e[ak],e===null&&(e=void 0))),e===void 0?Gb:e}});var Xb=b((eV,Kb)=>{"use strict";var sk=Yb();Kb.exports=function(a,e){return new(sk(a))(e===0?0:e)}});var Jb=b(()=>{"use strict";var nk=Te(),ok=Qb(),uk=wt(),lk=Ni(),ck=Wi(),dk=Xb();nk({target:"Array",proto:!0},{flatMap:function(e){var t=lk(this),i=ck(t),r;return uk(e),r=dk(t,0),r.length=ok(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Zb=b(()=>{"use strict";var pk=Fr();pk("flatMap")});var tg=b((sV,eg)=>{"use strict";Jb();Zb();var hk=Jt();eg.exports=hk("Array","flatMap")});var rg=b((nV,ig)=>{"use strict";var fk=tg();ig.exports=fk});var la=b((oV,ag)=>{"use strict";var mk=rg();ag.exports=mk});var ca=b((uV,sg)=>{"use strict";var bk=qr(),gk=String;sg.exports=function(a){if(bk(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return gk(a)}});var hl=b((lV,ng)=>{"use strict";ng.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 lg=b((cV,ug)=>{"use strict";var Sk=Ae(),vk=Xt(),yk=ca(),ml=hl(),og=Sk("".replace),Tk=RegExp("^["+ml+"]+"),Ik=RegExp("(^|[^"+ml+"])["+ml+"]+$"),fl=function(a){return function(e){var t=yk(vk(e));return a&1&&(t=og(t,Tk,"")),a&2&&(t=og(t,Ik,"$1")),t}};ug.exports={start:fl(1),end:fl(2),trim:fl(3)}});var hg=b((dV,pg)=>{"use strict";var Ek=jo().PROPER,xk=we(),cg=hl(),dg="\u200B\x85\u180E";pg.exports=function(a){return xk(function(){return!!cg[a]()||dg[a]()!==dg||Ek&&cg[a].name!==a})}});var bl=b((pV,fg)=>{"use strict";var wk=lg().start,Ak=hg();fg.exports=Ak("trimStart")?function(){return wk(this)}:"".trimStart});var bg=b(()=>{"use strict";var Pk=Te(),mg=bl();Pk({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==mg},{trimLeft:mg})});var Sg=b(()=>{"use strict";bg();var kk=Te(),gg=bl();kk({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==gg},{trimStart:gg})});var yg=b((gV,vg)=>{"use strict";Sg();var Rk=Jt();vg.exports=Rk("String","trimLeft")});var Ig=b((SV,Tg)=>{"use strict";var Lk=yg();Tg.exports=Lk});var xg=b((vV,Eg)=>{"use strict";var $k=Ig();Eg.exports=$k});var Fg=b(()=>{"use strict"});var Ng=b(()=>{"use strict"});var Ug=b((eF,qg)=>{"use strict";var Xk=qe(),Jk=pi(),Zk=$e(),eR=Zk("match");qg.exports=function(a){var e;return Xk(a)&&((e=a[eR])!==void 0?!!e:Jk(a)==="RegExp")}});var Qg=b((tF,jg)=>{"use strict";var tR=Se(),iR=we(),Hg=tR.RegExp,rR=!iR(function(){var a=!0;try{Hg(".","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(Hg.prototype,"flags").get.call(e);return u!==i||t!==i});jg.exports={correct:rR}});var Gg=b((iF,Wg)=>{"use strict";var aR=At();Wg.exports=function(){var a=aR(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 Kg=b((rF,Yg)=>{"use strict";var sR=Xe(),nR=mt(),oR=Mr(),zg=Qg(),uR=Gg(),lR=RegExp.prototype;Yg.exports=zg.correct?function(a){return a.flags}:function(a){return!zg.correct&&oR(lR,a)&&!nR(a,"flags")?sR(uR,a):a.flags}});var Jg=b((aF,Xg)=>{"use strict";var yl=Ae(),cR=Ni(),dR=Math.floor,Sl=yl("".charAt),pR=yl("".replace),vl=yl("".slice),hR=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,fR=/\$([$&'`]|\d{1,2})/g;Xg.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=fR;return r!==void 0&&(r=cR(r),o=hR),pR(s,o,function(l,c){var p;switch(Sl(c,0)){case"$":return"$";case"&":return a;case"`":return vl(e,0,t);case"'":return vl(e,n);case"<":p=r[vl(c,1,-1)];break;default:var d=+c;if(d===0)return l;if(d>u){var h=dR(d/10);return h===0?l:h<=u?i[h-1]===void 0?Sl(c,1):i[h-1]+Sl(c,1):l}p=i[d-1]}return p===void 0?"":p})}});var tS=b(()=>{"use strict";var mR=Te(),bR=Xe(),Il=Ae(),Zg=Xt(),gR=ve(),SR=qe(),vR=Ug(),fr=ca(),yR=Cr(),TR=Kg(),IR=Jg(),ER=$e(),xR=ft(),wR=ER("replace"),AR=TypeError,Tl=Il("".indexOf),PR=Il("".replace),eS=Il("".slice),kR=Math.max;mR({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(SR(e)){if(r=vR(e),r&&(s=fr(Zg(TR(e))),!~Tl(s,"g")))throw new AR("`.replaceAll` does not allow non-global regexes");if(n=yR(e,wR),n)return bR(n,e,i,t);if(xR&&r)return PR(fr(i),e,t)}for(u=fr(i),o=fr(e),l=gR(t),l||(t=fr(t)),c=o.length,p=kR(1,c),d=Tl(u,o);d!==-1;)h=l?fr(t(o,d,u)):IR(o,u,d,[],void 0,t),g+=eS(u,m,d)+h,m=d+c,d=d+p>u.length?-1:Tl(u,o,d+p);return m<u.length&&(g+=eS(u,m)),g}})});var rS=b((oF,iS)=>{"use strict";Fg();Ng();tS();var RR=Jt();iS.exports=RR("String","replaceAll")});var sS=b((uF,aS)=>{"use strict";var LR=rS();aS.exports=LR});var oS=b((lF,nS)=>{"use strict";var $R=sS();nS.exports=$R});var lS=b((cF,uS)=>{"use strict";var MR=Or(),DR=ca(),CR=Xt(),BR=RangeError;uS.exports=function(e){var t=DR(CR(this)),i="",r=MR(e);if(r<0||r===1/0)throw new BR("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var fS=b((dF,hS)=>{"use strict";var pS=Ae(),VR=Mo(),cS=ca(),_R=lS(),OR=Xt(),FR=pS(_R),NR=pS("".slice),qR=Math.ceil,dS=function(a){return function(e,t,i){var r=cS(OR(e)),s=VR(t),n=r.length,u=i===void 0?" ":cS(i),o,l;return s<=n||u===""?r:(o=s-n,l=FR(u,qR(o/u.length)),l.length>o&&(l=NR(l,0,o)),a?r+l:l+r)}};hS.exports={start:dS(!1),end:dS(!0)}});var bS=b((pF,mS)=>{"use strict";var UR=mi();mS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(UR)});var gS=b(()=>{"use strict";var HR=Te(),jR=fS().start,QR=bS();HR({target:"String",proto:!0,forced:QR},{padStart:function(e){return jR(this,e,arguments.length>1?arguments[1]:void 0)}})});var vS=b((mF,SS)=>{"use strict";gS();var WR=Jt();SS.exports=WR("String","padStart")});var TS=b((bF,yS)=>{"use strict";var GR=vS();yS.exports=GR});var ES=b((gF,IS)=>{"use strict";var zR=TS();IS.exports=zR});var EL={};Bv(EL,{ChromecastState:()=>Ar,HttpConnectionType:()=>cs,Observable:()=>Ct.Observable,PlaybackState:()=>Ve,Player:()=>es,PredefinedQualityLimits:()=>Pr,SDK_VERSION:()=>IL,Subject:()=>Ct.Subject,Subscription:()=>Ct.Subscription,Surface:()=>ds,VERSION:()=>eo,ValueSubject:()=>Ct.ValueSubject,VideoFormat:()=>xt,VideoQuality:()=>Ct.VideoQuality,areValidLiveRecordSources:()=>rb,clientChecker:()=>j,isMobile:()=>rr});module.exports=Vv(EL);var eo="2.0.140-dev.4c27f703.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_FMP4="HLS_FMP4",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(xt||{});var Ar=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ar||{}),cs=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(cs||{});var ds=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ds||{}),Pr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Pr||{});var Zl=H(gi(),1),wv=H(_e(),1);var J=require("@vkontakte/videoplayer-shared/es2024");var gp=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 vs=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||gp("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)($I),(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})}}},$I=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 Kl=H(_e(),1),pv=H(Gi(),1),hv=H(su(),1);var sb=H(js(),1);var Qu=require("@vkontakte/videoplayer-shared/es2024");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 Pt=require("@vkontakte/videoplayer-shared/es2024"),Z=class{constructor(e){this.transitionStarted$=new Pt.Subject;this.transitionEnded$=new Pt.Subject;this.transitionUpdated$=new Pt.Subject;this.forceChanged$=new Pt.Subject;this.stateChangeStarted$=(0,Pt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Pt.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,Pt.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 Gu=require("@vkontakte/videoplayer-shared/es2024");var Qs=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 Km=H(_e(),1);var rr=()=>/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=rr()}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 Gs=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 Ze=()=>window.ManagedMediaSource||window.MediaSource,ar=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Xm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),zs=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var gP=document.createElement("video"),SP='video/mp4; codecs="avc1.42000a,mp4a.40.2"',vP='video/mp4; codecs="hev1.1.6.L93.B0"',Jm='video/webm; codecs="vp09.00.10.08"',Zm='video/webm; codecs="av01.0.00M.08"',yP='audio/mp4; codecs="mp4a.40.2"',TP='audio/webm; codecs="opus"',eb,IP=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}};IP().catch(a=>{console.log(gP),console.error(a)});var Ys=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:ar(),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=!!Ze()?.isTypeSupported?.(SP),t=!!Ze()?.isTypeSupported?.(vP),i=!!Ze()?.isTypeSupported?.(yP);this._codecs={h264:e,h265:t,vp9:!!Ze()?.isTypeSupported?.(Jm),av1:!!Ze()?.isTypeSupported?.(Zm),aac:i,opus:!!Ze()?.isTypeSupported?.(TP),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",Ks=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:!!Ze()?.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/es2024"),Wu=class{constructor(){this.isInited$=new ib.ValueSubject(!1);this._displayChecker=new Gs,this._deviceChecker=new Ws(this._displayChecker),this._browserChecker=new Qs,this._videoChecker=new Ys(this._deviceChecker,this._browserChecker),this._audioChecker=new Ks,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 Wu;var zu=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=j.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(u=>{switch(u){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return(0,Gu.assertNever)(u)}})},Yu=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_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,Gu.assertNever)(a)}},rb=a=>{let t=Object.keys(a).filter(i=>!Yu(i));return zu(t).length>0};var N=require("@vkontakte/videoplayer-shared/es2024");var EP=5,xP=5,wP=500,ab=7e3,Jr=class{constructor(e){this.subscription=new N.Subscription;this.loadMediaTimeoutSubscription=new N.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,N.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,N.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,N.assertNever)(e)}break}default:(0,N.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(Yu(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 N.Subscription;this.subscription.add(e),this.subscription.add((0,N.merge)(this.videoState.stateChangeStarted$.pipe((0,N.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,N.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 N.Subject;e.add(r.pipe((0,N.debounce)(wP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,N.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)>EP)&&r.next(u),s=u})),e.add((0,N.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,N.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,N.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,N.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<xP&&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,N.assertNever)(n)}}),t((0,N.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,N.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,N.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,N.observableFrom)(["init"])).pipe((0,N.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,N.assertNonNullable)(l);let c=(0,N.getHighestQuality)(Object.keys(l));(0,N.assertNonNullable)(c);let p=l[c];(0,N.assertNonNullable)(p),i=p,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];(0,N.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,N.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,N.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,N.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:N.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,N.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,N.isNonNullable)(u)&&(n.metadata.title=u),(0,N.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,N.timeout)(ab).subscribe(()=>s(`timeout(${ab})`)))});(0,sb.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:N.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var cl=H(_e(),1);var Zu=require("@vkontakte/videoplayer-shared/es2024");var nb=require("@vkontakte/videoplayer-shared/es2024"),ob=a=>{try{a.pause(),a.playbackRate=0,(0,nb.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Xs=require("@vkontakte/videoplayer-shared/es2024"),Ku=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)}},Xu=window.WeakMap?new WeakMap:new Ku,Ju=window.WeakMap?new WeakMap:new Map,AP=(a,e=20)=>{let t=0;return(0,Xs.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,Zu.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),Xu.set(i,r);let s=new Xs.Subscription;return s.add(AP(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},He=a=>{Ju.get(a)?.unsubscribe(),Ju.delete(a);let t=Xu.get(a);Xu.delete(a),t?(0,Zu.clearVideoElement)(a):ob(a)};var el=H(gi(),1),q=require("@vkontakte/videoplayer-shared/es2024");var ti=require("@vkontakte/videoplayer-shared/es2024"),Js=(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},kt=(a,e,t)=>Js(e,()=>a.loop,i=>{(0,ti.isNonNullable)(i)&&(a.loop=i)},{onError:t}),je=(a,e,t,i)=>Js(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)=>Js(e,()=>a.playbackRate,r=>{(0,ti.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Zr=Js;var PP=a=>["__",a.language,a.label].join("|"),kP=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},tl=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(Zr(t.internalTextTracks,()=>(0,el.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(Zr(t.externalTextTracks,()=>(0,el.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(Zr(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(Zr(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:PP(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)||!kP(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=tl;var Ei=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 ub=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},il=a=>{let e=ub(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},lb=a=>{let e=ub(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var $=require("@vkontakte/videoplayer-shared/es2024");var RP=3,cb=(a,e,t=RP)=>{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 Qe=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)(()=>cb(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)),v=(0,$.fromEvent)(a,"leavepictureinpicture").pipe((0,$.shareReplay)(1)),S=new $.ValueSubject(lb(a));t.add(g.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let A=new $.ValueSubject(il(a)),L=(0,$.fromEvent)(a,"fullscreenchange").pipe((0,$.shareReplay)(1));t.add(L.pipe((0,$.map)(()=>il(a))).subscribe(A));let x=.1,D=1e3,U=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(w=>a.duration-a.currentTime<x),(0,$.filterChanged)(),(0,$.shareReplay)(1)),_=(0,$.merge)(U.pipe((0,$.filter)(w=>!a.loop&&w)),(0,$.fromEvent)(a,"ended")).pipe((0,$.throttle)(D),(0,$.mapTo)(void 0),(0,$.shareReplay)(1)),V=(0,$.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>(0,$.fromEvent)(a,w)),U.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$:_,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$:V,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:S,inFullscreen$:A,enterPip$:g,leavePip$:v,destroy:i}};var Ft=require("@vkontakte/videoplayer-shared/es2024"),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 Fe=H(gt(),1),sl=H(_e(),1),xi=H(Gi(),1),M=require("@vkontakte/videoplayer-shared/es2024");var rl=!1,Nt={},gb=a=>{rl=a},Sb=()=>{Nt={}},vb=a=>{a(Nt)},ea=(a,e)=>{rl&&(Nt.meta=Nt.meta??{},Nt.meta[a]=e)},Oe=class{constructor(e){this.name=e}next(e){if(!rl)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/es2024");function al(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function Zs(a,e,t){return!!a&&al(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 yb({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 wb=new Oe("best_bitrate"),tn=(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={}}},rn='Assertion "ABR Tracks is empty array" failed',en=new WeakMap,Tb=new WeakMap,Ib=new WeakMap,ta=(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,Fe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Fe.default)(s,-1);return u&&(0,sl.default)(n,u)?u:n.length?(0,Fe.default)(n,-1):(0,Fe.default)(s,0)},ia=(a,e,t,i)=>{let r=en.get(e);r||(r=[...e].sort(nr(1)),en.set(e,r));let s=en.get(t);s||(s=[...t].sort(nr(1)),en.set(t,s));let n=Ib.get(a);n||(n=s.filter(o=>(0,M.isNonNullable)(o.bitrate)&&(0,M.isNonNullable)(a.bitrate)?a.bitrate/o.bitrate>i:!0),Ib.set(a,n));let u=(0,Fe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Fe.default)(s,-1);return u&&(0,sl.default)(n,u)?u:n.length?(0,Fe.default)(n,-1):(0,Fe.default)(s,0)},Eb=a=>"quality"in a,an=(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=Eb(n)?"video":"audio",o=Eb(n)?n.quality:n.bitrate;return e({message:`
|
|
6
|
+
"use strict";var Rv=Object.create;var ds=Object.defineProperty;var kv=Object.getOwnPropertyDescriptor;var Lv=Object.getOwnPropertyNames;var $v=Object.getPrototypeOf,Mv=Object.prototype.hasOwnProperty;var g=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports),Dv=(a,e)=>{for(var t in e)ds(a,t,{get:e[t],enumerable:!0})},tc=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Lv(e))!Mv.call(a,r)&&r!==t&&ds(a,r,{get:()=>e[r],enumerable:!(i=kv(e,r))||i.enumerable});return a};var Q=(a,e,t)=>(t=a!=null?Rv($v(a)):{},tc(e||!a||!a.__esModule?ds(t,"default",{value:a,enumerable:!0}):t,a)),Cv=a=>tc(ds({},"__esModule",{value:!0}),a);var Se=g((io,ic)=>{"use strict";var Rr=function(a){return a&&a.Math===Math&&a};ic.exports=Rr(typeof globalThis=="object"&&globalThis)||Rr(typeof window=="object"&&window)||Rr(typeof self=="object"&&self)||Rr(typeof global=="object"&&global)||Rr(typeof io=="object"&&io)||function(){return this}()||Function("return this")()});var we=g((wL,rc)=>{"use strict";rc.exports=function(a){try{return!!a()}catch{return!0}}});var kr=g((AL,ac)=>{"use strict";var Bv=we();ac.exports=!Bv(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ro=g((PL,uc)=>{"use strict";var Vv=kr(),oc=Function.prototype,sc=oc.apply,nc=oc.call;uc.exports=typeof Reflect=="object"&&Reflect.apply||(Vv?nc.bind(sc):function(){return nc.apply(sc,arguments)})});var Ae=g((RL,dc)=>{"use strict";var lc=kr(),cc=Function.prototype,ao=cc.call,_v=lc&&cc.bind.bind(ao,ao);dc.exports=lc?_v:function(a){return function(){return ao.apply(a,arguments)}}});var pi=g((kL,hc)=>{"use strict";var pc=Ae(),Ov=pc({}.toString),Fv=pc("".slice);hc.exports=function(a){return Fv(Ov(a),8,-1)}});var so=g((LL,fc)=>{"use strict";var Nv=pi(),qv=Ae();fc.exports=function(a){if(Nv(a)==="Function")return qv(a)}});var ve=g(($L,mc)=>{"use strict";var no=typeof document=="object"&&document.all;mc.exports=typeof no>"u"&&no!==void 0?function(a){return typeof a=="function"||a===no}:function(a){return typeof a=="function"}});var Ke=g((ML,bc)=>{"use strict";var Uv=we();bc.exports=!Uv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Xe=g((DL,gc)=>{"use strict";var Hv=kr(),fs=Function.prototype.call;gc.exports=Hv?fs.bind(fs):function(){return fs.apply(fs,arguments)}});var oo=g(yc=>{"use strict";var Sc={}.propertyIsEnumerable,vc=Object.getOwnPropertyDescriptor,jv=vc&&!Sc.call({1:2},1);yc.f=jv?function(e){var t=vc(this,e);return!!t&&t.enumerable}:Sc});var Lr=g((BL,Tc)=>{"use strict";Tc.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Ec=g((VL,Ic)=>{"use strict";var Qv=Ae(),Wv=we(),Gv=pi(),uo=Object,zv=Qv("".split);Ic.exports=Wv(function(){return!uo("z").propertyIsEnumerable(0)})?function(a){return Gv(a)==="String"?zv(a,""):uo(a)}:uo});var $r=g((_L,xc)=>{"use strict";xc.exports=function(a){return a==null}});var Xt=g((OL,wc)=>{"use strict";var Yv=$r(),Kv=TypeError;wc.exports=function(a){if(Yv(a))throw new Kv("Can't call method on "+a);return a}});var hi=g((FL,Ac)=>{"use strict";var Xv=Ec(),Jv=Xt();Ac.exports=function(a){return Xv(Jv(a))}});var qe=g((NL,Pc)=>{"use strict";var Zv=ve();Pc.exports=function(a){return typeof a=="object"?a!==null:Zv(a)}});var fi=g((qL,Rc)=>{"use strict";Rc.exports={}});var Vt=g((UL,Lc)=>{"use strict";var lo=fi(),co=Se(),ey=ve(),kc=function(a){return ey(a)?a:void 0};Lc.exports=function(a,e){return arguments.length<2?kc(lo[a])||kc(co[a]):lo[a]&&lo[a][e]||co[a]&&co[a][e]}});var Mr=g((HL,$c)=>{"use strict";var ty=Ae();$c.exports=ty({}.isPrototypeOf)});var mi=g((jL,Cc)=>{"use strict";var iy=Se(),Mc=iy.navigator,Dc=Mc&&Mc.userAgent;Cc.exports=Dc?String(Dc):""});var ho=g((QL,Nc)=>{"use strict";var Fc=Se(),po=mi(),Bc=Fc.process,Vc=Fc.Deno,_c=Bc&&Bc.versions||Vc&&Vc.version,Oc=_c&&_c.v8,ht,ms;Oc&&(ht=Oc.split("."),ms=ht[0]>0&&ht[0]<4?1:+(ht[0]+ht[1]));!ms&&po&&(ht=po.match(/Edge\/(\d+)/),(!ht||ht[1]>=74)&&(ht=po.match(/Chrome\/(\d+)/),ht&&(ms=+ht[1])));Nc.exports=ms});var fo=g((WL,Uc)=>{"use strict";var qc=ho(),ry=we(),ay=Se(),sy=ay.String;Uc.exports=!!Object.getOwnPropertySymbols&&!ry(function(){var a=Symbol("symbol detection");return!sy(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&qc&&qc<41})});var mo=g((GL,Hc)=>{"use strict";var ny=fo();Hc.exports=ny&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var bo=g((zL,jc)=>{"use strict";var oy=Vt(),uy=ve(),ly=Mr(),cy=mo(),dy=Object;jc.exports=cy?function(a){return typeof a=="symbol"}:function(a){var e=oy("Symbol");return uy(e)&&ly(e.prototype,dy(a))}});var Dr=g((YL,Qc)=>{"use strict";var py=String;Qc.exports=function(a){try{return py(a)}catch{return"Object"}}});var wt=g((KL,Wc)=>{"use strict";var hy=ve(),fy=Dr(),my=TypeError;Wc.exports=function(a){if(hy(a))return a;throw new my(fy(a)+" is not a function")}});var Cr=g((XL,Gc)=>{"use strict";var by=wt(),gy=$r();Gc.exports=function(a,e){var t=a[e];return gy(t)?void 0:by(t)}});var Yc=g((JL,zc)=>{"use strict";var go=Xe(),So=ve(),vo=qe(),Sy=TypeError;zc.exports=function(a,e){var t,i;if(e==="string"&&So(t=a.toString)&&!vo(i=go(t,a))||So(t=a.valueOf)&&!vo(i=go(t,a))||e!=="string"&&So(t=a.toString)&&!vo(i=go(t,a)))return i;throw new Sy("Can't convert object to primitive value")}});var ft=g((ZL,Kc)=>{"use strict";Kc.exports=!0});var Zc=g((e$,Jc)=>{"use strict";var Xc=Se(),vy=Object.defineProperty;Jc.exports=function(a,e){try{vy(Xc,a,{value:e,configurable:!0,writable:!0})}catch{Xc[a]=e}return e}});var Br=g((t$,id)=>{"use strict";var yy=ft(),Ty=Se(),Iy=Zc(),ed="__core-js_shared__",td=id.exports=Ty[ed]||Iy(ed,{});(td.versions||(td.versions=[])).push({version:"3.43.0",mode:yy?"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 yo=g((i$,ad)=>{"use strict";var rd=Br();ad.exports=function(a,e){return rd[a]||(rd[a]=e||{})}});var Ni=g((r$,sd)=>{"use strict";var Ey=Xt(),xy=Object;sd.exports=function(a){return xy(Ey(a))}});var mt=g((a$,nd)=>{"use strict";var wy=Ae(),Ay=Ni(),Py=wy({}.hasOwnProperty);nd.exports=Object.hasOwn||function(e,t){return Py(Ay(e),t)}});var To=g((s$,od)=>{"use strict";var Ry=Ae(),ky=0,Ly=Math.random(),$y=Ry(1.1.toString);od.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+$y(++ky+Ly,36)}});var Le=g((n$,ld)=>{"use strict";var My=Se(),Dy=yo(),ud=mt(),Cy=To(),By=fo(),Vy=mo(),qi=My.Symbol,Io=Dy("wks"),_y=Vy?qi.for||qi:qi&&qi.withoutSetter||Cy;ld.exports=function(a){return ud(Io,a)||(Io[a]=By&&ud(qi,a)?qi[a]:_y("Symbol."+a)),Io[a]}});var hd=g((o$,pd)=>{"use strict";var Oy=Xe(),cd=qe(),dd=bo(),Fy=Cr(),Ny=Yc(),qy=Le(),Uy=TypeError,Hy=qy("toPrimitive");pd.exports=function(a,e){if(!cd(a)||dd(a))return a;var t=Fy(a,Hy),i;if(t){if(e===void 0&&(e="default"),i=Oy(t,a,e),!cd(i)||dd(i))return i;throw new Uy("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ny(a,e)}});var Eo=g((u$,fd)=>{"use strict";var jy=hd(),Qy=bo();fd.exports=function(a){var e=jy(a,"string");return Qy(e)?e:e+""}});var bs=g((l$,bd)=>{"use strict";var Wy=Se(),md=qe(),xo=Wy.document,Gy=md(xo)&&md(xo.createElement);bd.exports=function(a){return Gy?xo.createElement(a):{}}});var wo=g((c$,gd)=>{"use strict";var zy=Ke(),Yy=we(),Ky=bs();gd.exports=!zy&&!Yy(function(){return Object.defineProperty(Ky("div"),"a",{get:function(){return 7}}).a!==7})});var yd=g(vd=>{"use strict";var Xy=Ke(),Jy=Xe(),Zy=oo(),eT=Lr(),tT=hi(),iT=Eo(),rT=mt(),aT=wo(),Sd=Object.getOwnPropertyDescriptor;vd.f=Xy?Sd:function(e,t){if(e=tT(e),t=iT(t),aT)try{return Sd(e,t)}catch{}if(rT(e,t))return eT(!Jy(Zy.f,e,t),e[t])}});var Ao=g((p$,Td)=>{"use strict";var sT=we(),nT=ve(),oT=/#|\.prototype\./,Vr=function(a,e){var t=lT[uT(a)];return t===dT?!0:t===cT?!1:nT(e)?sT(e):!!e},uT=Vr.normalize=function(a){return String(a).replace(oT,".").toLowerCase()},lT=Vr.data={},cT=Vr.NATIVE="N",dT=Vr.POLYFILL="P";Td.exports=Vr});var Ui=g((h$,Ed)=>{"use strict";var Id=so(),pT=wt(),hT=kr(),fT=Id(Id.bind);Ed.exports=function(a,e){return pT(a),e===void 0?a:hT?fT(a,e):function(){return a.apply(e,arguments)}}});var Po=g((f$,xd)=>{"use strict";var mT=Ke(),bT=we();xd.exports=mT&&bT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var At=g((m$,wd)=>{"use strict";var gT=qe(),ST=String,vT=TypeError;wd.exports=function(a){if(gT(a))return a;throw new vT(ST(a)+" is not an object")}});var bi=g(Pd=>{"use strict";var yT=Ke(),TT=wo(),IT=Po(),gs=At(),Ad=Eo(),ET=TypeError,Ro=Object.defineProperty,xT=Object.getOwnPropertyDescriptor,ko="enumerable",Lo="configurable",$o="writable";Pd.f=yT?IT?function(e,t,i){if(gs(e),t=Ad(t),gs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&$o in i&&!i[$o]){var r=xT(e,t);r&&r[$o]&&(e[t]=i.value,i={configurable:Lo in i?i[Lo]:r[Lo],enumerable:ko in i?i[ko]:r[ko],writable:!1})}return Ro(e,t,i)}:Ro:function(e,t,i){if(gs(e),t=Ad(t),gs(i),TT)try{return Ro(e,t,i)}catch{}if("get"in i||"set"in i)throw new ET("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Hi=g((g$,Rd)=>{"use strict";var wT=Ke(),AT=bi(),PT=Lr();Rd.exports=wT?function(a,e,t){return AT.f(a,e,PT(1,t))}:function(a,e,t){return a[e]=t,a}});var Te=g((S$,Ld)=>{"use strict";var _r=Se(),RT=ro(),kT=so(),LT=ve(),$T=yd().f,MT=Ao(),ji=fi(),DT=Ui(),Qi=Hi(),kd=mt();Br();var CT=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 RT(a,this,arguments)};return e.prototype=a.prototype,e};Ld.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?_r:r?_r[t]:_r[t]&&_r[t].prototype,u=i?ji:ji[t]||Qi(ji,t,{})[t],o=u.prototype,l,p,d,c,h,m,b,S,v;for(c in e)l=MT(i?c:t+(r?".":"#")+c,a.forced),p=!l&&n&&kd(n,c),m=u[c],p&&(a.dontCallGetSet?(v=$T(n,c),b=v&&v.value):b=n[c]),h=p&&b?b:e[c],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&p?S=DT(h,_r):a.wrap&&p?S=CT(h):s&<(h)?S=kT(h):S=h,(a.sham||h&&h.sham||m&&m.sham)&&Qi(S,"sham",!0),Qi(u,c,S),s&&(d=t+"Prototype",kd(ji,d)||Qi(ji,d,{}),Qi(ji[d],c,h),a.real&&o&&(l||!o[c])&&Qi(o,c,h)))}});var Ss=g((v$,Md)=>{"use strict";var BT=yo(),VT=To(),$d=BT("keys");Md.exports=function(a){return $d[a]||($d[a]=VT(a))}});var Cd=g((y$,Dd)=>{"use strict";var _T=we();Dd.exports=!_T(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var vs=g((T$,Vd)=>{"use strict";var OT=mt(),FT=ve(),NT=Ni(),qT=Ss(),UT=Cd(),Bd=qT("IE_PROTO"),Mo=Object,HT=Mo.prototype;Vd.exports=UT?Mo.getPrototypeOf:function(a){var e=NT(a);if(OT(e,Bd))return e[Bd];var t=e.constructor;return FT(t)&&e instanceof t?t.prototype:e instanceof Mo?HT:null}});var Od=g((I$,_d)=>{"use strict";var jT=Math.ceil,QT=Math.floor;_d.exports=Math.trunc||function(e){var t=+e;return(t>0?QT:jT)(t)}});var Or=g((E$,Fd)=>{"use strict";var WT=Od();Fd.exports=function(a){var e=+a;return e!==e||e===0?0:WT(e)}});var qd=g((x$,Nd)=>{"use strict";var GT=Or(),zT=Math.max,YT=Math.min;Nd.exports=function(a,e){var t=GT(a);return t<0?zT(t+e,0):YT(t,e)}});var Do=g((w$,Ud)=>{"use strict";var KT=Or(),XT=Math.min;Ud.exports=function(a){var e=KT(a);return e>0?XT(e,9007199254740991):0}});var Wi=g((A$,Hd)=>{"use strict";var JT=Do();Hd.exports=function(a){return JT(a.length)}});var Co=g((P$,Qd)=>{"use strict";var ZT=hi(),eI=qd(),tI=Wi(),jd=function(a){return function(e,t,i){var r=ZT(e),s=tI(r);if(s===0)return!a&&-1;var n=eI(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}};Qd.exports={includes:jd(!0),indexOf:jd(!1)}});var ys=g((R$,Wd)=>{"use strict";Wd.exports={}});var Yd=g((k$,zd)=>{"use strict";var iI=Ae(),Bo=mt(),rI=hi(),aI=Co().indexOf,sI=ys(),Gd=iI([].push);zd.exports=function(a,e){var t=rI(a),i=0,r=[],s;for(s in t)!Bo(sI,s)&&Bo(t,s)&&Gd(r,s);for(;e.length>i;)Bo(t,s=e[i++])&&(~aI(r,s)||Gd(r,s));return r}});var Vo=g((L$,Kd)=>{"use strict";Kd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var _o=g(($$,Xd)=>{"use strict";var nI=Yd(),oI=Vo();Xd.exports=Object.keys||function(e){return nI(e,oI)}});var Oo=g((M$,ip)=>{"use strict";var Zd=Ke(),uI=we(),ep=Ae(),lI=vs(),cI=_o(),dI=hi(),pI=oo().f,tp=ep(pI),hI=ep([].push),fI=Zd&&uI(function(){var a=Object.create(null);return a[2]=2,!tp(a,2)}),Jd=function(a){return function(e){for(var t=dI(e),i=cI(t),r=fI&&lI(t)===null,s=i.length,n=0,u=[],o;s>n;)o=i[n++],(!Zd||(r?o in t:tp(t,o)))&&hI(u,a?[o,t[o]]:t[o]);return u}};ip.exports={entries:Jd(!0),values:Jd(!1)}});var rp=g(()=>{"use strict";var mI=Te(),bI=Oo().values;mI({target:"Object",stat:!0},{values:function(e){return bI(e)}})});var sp=g((B$,ap)=>{"use strict";rp();var gI=fi();ap.exports=gI.Object.values});var op=g((V$,np)=>{"use strict";var SI=sp();np.exports=SI});var gi=g((_$,up)=>{"use strict";var vI=op();up.exports=vI});var Fr=g((O$,lp)=>{"use strict";lp.exports=function(){}});var cp=g(()=>{"use strict";var yI=Te(),TI=Co().includes,II=we(),EI=Fr(),xI=II(function(){return!Array(1).includes()});yI({target:"Array",proto:!0,forced:xI},{includes:function(e){return TI(this,e,arguments.length>1?arguments[1]:void 0)}});EI("includes")});var Jt=g((q$,dp)=>{"use strict";var wI=Vt();dp.exports=wI});var hp=g((U$,pp)=>{"use strict";cp();var AI=Jt();pp.exports=AI("Array","includes")});var mp=g((H$,fp)=>{"use strict";var PI=hp();fp.exports=PI});var Ue=g((j$,bp)=>{"use strict";var RI=mp();bp.exports=RI});var Sp=g(()=>{"use strict";var LI=Te(),$I=Oo().entries;LI({target:"Object",stat:!0},{entries:function(e){return $I(e)}})});var yp=g((rM,vp)=>{"use strict";Sp();var MI=fi();vp.exports=MI.Object.entries});var Ip=g((aM,Tp)=>{"use strict";var DI=yp();Tp.exports=DI});var Gi=g((sM,Ep)=>{"use strict";var CI=Ip();Ep.exports=CI});var Si=g((nM,xp)=>{"use strict";xp.exports={}});var Pp=g((oM,Ap)=>{"use strict";var BI=Se(),VI=ve(),wp=BI.WeakMap;Ap.exports=VI(wp)&&/native code/.test(String(wp))});var Uo=g((uM,Lp)=>{"use strict";var _I=Pp(),kp=Se(),OI=qe(),FI=Hi(),Fo=mt(),No=Br(),NI=Ss(),qI=ys(),Rp="Object already initialized",qo=kp.TypeError,UI=kp.WeakMap,Is,Nr,Es,HI=function(a){return Es(a)?Nr(a):Is(a,{})},jI=function(a){return function(e){var t;if(!OI(e)||(t=Nr(e)).type!==a)throw new qo("Incompatible receiver, "+a+" required");return t}};_I||No.state?(bt=No.state||(No.state=new UI),bt.get=bt.get,bt.has=bt.has,bt.set=bt.set,Is=function(a,e){if(bt.has(a))throw new qo(Rp);return e.facade=a,bt.set(a,e),e},Nr=function(a){return bt.get(a)||{}},Es=function(a){return bt.has(a)}):(vi=NI("state"),qI[vi]=!0,Is=function(a,e){if(Fo(a,vi))throw new qo(Rp);return e.facade=a,FI(a,vi,e),e},Nr=function(a){return Fo(a,vi)?a[vi]:{}},Es=function(a){return Fo(a,vi)});var bt,vi;Lp.exports={set:Is,get:Nr,has:Es,enforce:HI,getterFor:jI}});var Qo=g((lM,Mp)=>{"use strict";var Ho=Ke(),QI=mt(),$p=Function.prototype,WI=Ho&&Object.getOwnPropertyDescriptor,jo=QI($p,"name"),GI=jo&&function(){}.name==="something",zI=jo&&(!Ho||Ho&&WI($p,"name").configurable);Mp.exports={EXISTS:jo,PROPER:GI,CONFIGURABLE:zI}});var Cp=g(Dp=>{"use strict";var YI=Ke(),KI=Po(),XI=bi(),JI=At(),ZI=hi(),eE=_o();Dp.f=YI&&!KI?Object.defineProperties:function(e,t){JI(e);for(var i=ZI(t),r=eE(t),s=r.length,n=0,u;s>n;)XI.f(e,u=r[n++],i[u]);return e}});var Wo=g((dM,Bp)=>{"use strict";var tE=Vt();Bp.exports=tE("document","documentElement")});var Ko=g((pM,Up)=>{"use strict";var iE=At(),rE=Cp(),Vp=Vo(),aE=ys(),sE=Wo(),nE=bs(),oE=Ss(),_p=">",Op="<",zo="prototype",Yo="script",Np=oE("IE_PROTO"),Go=function(){},qp=function(a){return Op+Yo+_p+a+Op+"/"+Yo+_p},Fp=function(a){a.write(qp("")),a.close();var e=a.parentWindow.Object;return a=null,e},uE=function(){var a=nE("iframe"),e="java"+Yo+":",t;return a.style.display="none",sE.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(qp("document.F=Object")),t.close(),t.F},xs,ws=function(){try{xs=new ActiveXObject("htmlfile")}catch{}ws=typeof document<"u"?document.domain&&xs?Fp(xs):uE():Fp(xs);for(var a=Vp.length;a--;)delete ws[zo][Vp[a]];return ws()};aE[Np]=!0;Up.exports=Object.create||function(e,t){var i;return e!==null?(Go[zo]=iE(e),i=new Go,Go[zo]=null,i[Np]=e):i=ws(),t===void 0?i:rE.f(i,t)}});var zi=g((hM,Hp)=>{"use strict";var lE=Hi();Hp.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:lE(a,e,t),a}});var eu=g((fM,Wp)=>{"use strict";var cE=we(),dE=ve(),pE=qe(),hE=Ko(),jp=vs(),fE=zi(),mE=Le(),bE=ft(),Zo=mE("iterator"),Qp=!1,_t,Xo,Jo;[].keys&&(Jo=[].keys(),"next"in Jo?(Xo=jp(jp(Jo)),Xo!==Object.prototype&&(_t=Xo)):Qp=!0);var gE=!pE(_t)||cE(function(){var a={};return _t[Zo].call(a)!==a});gE?_t={}:bE&&(_t=hE(_t));dE(_t[Zo])||fE(_t,Zo,function(){return this});Wp.exports={IteratorPrototype:_t,BUGGY_SAFARI_ITERATORS:Qp}});var As=g((mM,zp)=>{"use strict";var SE=Le(),vE=SE("toStringTag"),Gp={};Gp[vE]="z";zp.exports=String(Gp)==="[object z]"});var qr=g((bM,Yp)=>{"use strict";var yE=As(),TE=ve(),Ps=pi(),IE=Le(),EE=IE("toStringTag"),xE=Object,wE=Ps(function(){return arguments}())==="Arguments",AE=function(a,e){try{return a[e]}catch{}};Yp.exports=yE?Ps:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=AE(e=xE(a),EE))=="string"?t:wE?Ps(e):(i=Ps(e))==="Object"&&TE(e.callee)?"Arguments":i}});var Xp=g((gM,Kp)=>{"use strict";var PE=As(),RE=qr();Kp.exports=PE?{}.toString:function(){return"[object "+RE(this)+"]"}});var Ur=g((SM,Zp)=>{"use strict";var kE=As(),LE=bi().f,$E=Hi(),ME=mt(),DE=Xp(),CE=Le(),Jp=CE("toStringTag");Zp.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(ME(r,Jp)||LE(r,Jp,{configurable:!0,value:e}),i&&!kE&&$E(r,"toString",DE))}});var th=g((vM,eh)=>{"use strict";var BE=eu().IteratorPrototype,VE=Ko(),_E=Lr(),OE=Ur(),FE=Si(),NE=function(){return this};eh.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=VE(BE,{next:_E(+!i,t)}),OE(a,r,!1,!0),FE[r]=NE,a}});var rh=g((yM,ih)=>{"use strict";var qE=Ae(),UE=wt();ih.exports=function(a,e,t){try{return qE(UE(Object.getOwnPropertyDescriptor(a,e)[t]))}catch{}}});var sh=g((TM,ah)=>{"use strict";var HE=qe();ah.exports=function(a){return HE(a)||a===null}});var oh=g((IM,nh)=>{"use strict";var jE=sh(),QE=String,WE=TypeError;nh.exports=function(a){if(jE(a))return a;throw new WE("Can't set "+QE(a)+" as a prototype")}});var tu=g((EM,uh)=>{"use strict";var GE=rh(),zE=qe(),YE=Xt(),KE=oh();uh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=GE(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch{}return function(r,s){return YE(r),KE(s),zE(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var vh=g((xM,Sh)=>{"use strict";var XE=Te(),JE=Xe(),Rs=ft(),bh=Qo(),ZE=ve(),ex=th(),lh=vs(),ch=tu(),tx=Ur(),ix=Hi(),iu=zi(),rx=Le(),dh=Si(),gh=eu(),ax=bh.PROPER,sx=bh.CONFIGURABLE,ph=gh.IteratorPrototype,ks=gh.BUGGY_SAFARI_ITERATORS,Hr=rx("iterator"),hh="keys",jr="values",fh="entries",mh=function(){return this};Sh.exports=function(a,e,t,i,r,s,n){ex(t,e,i);var u=function(v){if(v===r&&c)return c;if(!ks&&v&&v in p)return p[v];switch(v){case hh:return function(){return new t(this,v)};case jr:return function(){return new t(this,v)};case fh:return function(){return new t(this,v)}}return function(){return new t(this)}},o=e+" Iterator",l=!1,p=a.prototype,d=p[Hr]||p["@@iterator"]||r&&p[r],c=!ks&&d||u(r),h=e==="Array"&&p.entries||d,m,b,S;if(h&&(m=lh(h.call(new a)),m!==Object.prototype&&m.next&&(!Rs&&lh(m)!==ph&&(ch?ch(m,ph):ZE(m[Hr])||iu(m,Hr,mh)),tx(m,o,!0,!0),Rs&&(dh[o]=mh))),ax&&r===jr&&d&&d.name!==jr&&(!Rs&&sx?ix(p,"name",jr):(l=!0,c=function(){return JE(d,this)})),r)if(b={values:u(jr),keys:s?c:u(hh),entries:u(fh)},n)for(S in b)(ks||l||!(S in p))&&iu(p,S,b[S]);else XE({target:e,proto:!0,forced:ks||l},b);return(!Rs||n)&&p[Hr]!==c&&iu(p,Hr,c,{name:r}),dh[e]=c,b}});var Th=g((wM,yh)=>{"use strict";yh.exports=function(a,e){return{value:a,done:e}}});var au=g((AM,Ah)=>{"use strict";var nx=hi(),ru=Fr(),Ih=Si(),xh=Uo(),ox=bi().f,ux=vh(),Ls=Th(),lx=ft(),cx=Ke(),wh="Array Iterator",dx=xh.set,px=xh.getterFor(wh);Ah.exports=ux(Array,"Array",function(a,e){dx(this,{type:wh,target:nx(a),index:0,kind:e})},function(){var a=px(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=null,Ls(void 0,!0);switch(a.kind){case"keys":return Ls(t,!1);case"values":return Ls(e[t],!1)}return Ls([t,e[t]],!1)},"values");var Eh=Ih.Arguments=Ih.Array;ru("keys");ru("values");ru("entries");if(!lx&&cx&&Eh.name!=="values")try{ox(Eh,"name",{value:"values"})}catch{}});var Rh=g((PM,Ph)=>{"use strict";var hx=Le(),fx=Si(),mx=hx("iterator"),bx=Array.prototype;Ph.exports=function(a){return a!==void 0&&(fx.Array===a||bx[mx]===a)}});var su=g((RM,Lh)=>{"use strict";var gx=qr(),kh=Cr(),Sx=$r(),vx=Si(),yx=Le(),Tx=yx("iterator");Lh.exports=function(a){if(!Sx(a))return kh(a,Tx)||kh(a,"@@iterator")||vx[gx(a)]}});var Mh=g((kM,$h)=>{"use strict";var Ix=Xe(),Ex=wt(),xx=At(),wx=Dr(),Ax=su(),Px=TypeError;$h.exports=function(a,e){var t=arguments.length<2?Ax(a):e;if(Ex(t))return xx(Ix(t,a));throw new Px(wx(a)+" is not iterable")}});var Bh=g((LM,Ch)=>{"use strict";var Rx=Xe(),Dh=At(),kx=Cr();Ch.exports=function(a,e,t){var i,r;Dh(a);try{if(i=kx(a,"return"),!i){if(e==="throw")throw t;return t}i=Rx(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Dh(i),t}});var Ms=g(($M,Fh)=>{"use strict";var Lx=Ui(),$x=Xe(),Mx=At(),Dx=Dr(),Cx=Rh(),Bx=Wi(),Vh=Mr(),Vx=Mh(),_x=su(),_h=Bh(),Ox=TypeError,$s=function(a,e){this.stopped=a,this.result=e},Oh=$s.prototype;Fh.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=Lx(e,i),l,p,d,c,h,m,b,S=function(I){return l&&_h(l,"normal"),new $s(!0,I)},v=function(I){return r?(Mx(I),u?o(I[0],I[1],S):o(I[0],I[1])):u?o(I,S):o(I)};if(s)l=a.iterator;else if(n)l=a;else{if(p=_x(a),!p)throw new Ox(Dx(a)+" is not iterable");if(Cx(p)){for(d=0,c=Bx(a);c>d;d++)if(h=v(a[d]),h&&Vh(Oh,h))return h;return new $s(!1)}l=Vx(a,p)}for(m=s?a.next:l.next;!(b=$x(m,l)).done;){try{h=v(b.value)}catch(I){_h(l,"throw",I)}if(typeof h=="object"&&h&&Vh(Oh,h))return h}return new $s(!1)}});var qh=g((MM,Nh)=>{"use strict";var Fx=Ke(),Nx=bi(),qx=Lr();Nh.exports=function(a,e,t){Fx?Nx.f(a,e,qx(0,t)):a[e]=t}});var Uh=g(()=>{"use strict";var Ux=Te(),Hx=Ms(),jx=qh();Ux({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Hx(e,function(i,r){jx(t,i,r)},{AS_ENTRIES:!0}),t}})});var jh=g((BM,Hh)=>{"use strict";au();Uh();var Qx=fi();Hh.exports=Qx.Object.fromEntries});var Wh=g((VM,Qh)=>{"use strict";Qh.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 zh=g(()=>{"use strict";au();var Wx=Wh(),Gx=Se(),zx=Ur(),Gh=Si();for(Ds in Wx)zx(Gx[Ds],Ds),Gh[Ds]=Gh.Array;var Ds});var Kh=g((FM,Yh)=>{"use strict";var Yx=jh();zh();Yh.exports=Yx});var nu=g((NM,Xh)=>{"use strict";var Kx=Kh();Xh.exports=Kx});var Jh=g(()=>{"use strict"});var ou=g((HM,Zh)=>{"use strict";var Qr=Se(),Xx=mi(),Jx=pi(),Cs=function(a){return Xx.slice(0,a.length)===a};Zh.exports=function(){return Cs("Bun/")?"BUN":Cs("Cloudflare-Workers")?"CLOUDFLARE":Cs("Deno/")?"DENO":Cs("Node.js/")?"NODE":Qr.Bun&&typeof Bun.version=="string"?"BUN":Qr.Deno&&typeof Deno.version=="object"?"DENO":Jx(Qr.process)==="process"?"NODE":Qr.window&&Qr.document?"BROWSER":"REST"}()});var Bs=g((jM,ef)=>{"use strict";var Zx=ou();ef.exports=Zx==="NODE"});var rf=g((QM,tf)=>{"use strict";var ew=bi();tf.exports=function(a,e,t){return ew.f(a,e,t)}});var nf=g((WM,sf)=>{"use strict";var tw=Vt(),iw=rf(),rw=Le(),aw=Ke(),af=rw("species");sf.exports=function(a){var e=tw(a);aw&&e&&!e[af]&&iw(e,af,{configurable:!0,get:function(){return this}})}});var uf=g((GM,of)=>{"use strict";var sw=Mr(),nw=TypeError;of.exports=function(a,e){if(sw(e,a))return a;throw new nw("Incorrect invocation")}});var lu=g((zM,lf)=>{"use strict";var ow=Ae(),uw=ve(),uu=Br(),lw=ow(Function.toString);uw(uu.inspectSource)||(uu.inspectSource=function(a){return lw(a)});lf.exports=uu.inspectSource});var du=g((YM,ff)=>{"use strict";var cw=Ae(),dw=we(),cf=ve(),pw=qr(),hw=Vt(),fw=lu(),df=function(){},pf=hw("Reflect","construct"),cu=/^\s*(?:class|function)\b/,mw=cw(cu.exec),bw=!cu.test(df),Wr=function(e){if(!cf(e))return!1;try{return pf(df,[],e),!0}catch{return!1}},hf=function(e){if(!cf(e))return!1;switch(pw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return bw||!!mw(cu,fw(e))}catch{return!0}};hf.sham=!0;ff.exports=!pf||dw(function(){var a;return Wr(Wr.call)||!Wr(Object)||!Wr(function(){a=!0})||a})?hf:Wr});var bf=g((KM,mf)=>{"use strict";var gw=du(),Sw=Dr(),vw=TypeError;mf.exports=function(a){if(gw(a))return a;throw new vw(Sw(a)+" is not a constructor")}});var pu=g((XM,Sf)=>{"use strict";var gf=At(),yw=bf(),Tw=$r(),Iw=Le(),Ew=Iw("species");Sf.exports=function(a,e){var t=gf(a).constructor,i;return t===void 0||Tw(i=gf(t)[Ew])?e:yw(i)}});var yf=g((JM,vf)=>{"use strict";var xw=Ae();vf.exports=xw([].slice)});var If=g((ZM,Tf)=>{"use strict";var ww=TypeError;Tf.exports=function(a,e){if(a<e)throw new ww("Not enough arguments");return a}});var hu=g((eD,Ef)=>{"use strict";var Aw=mi();Ef.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Aw)});var Iu=g((tD,Mf)=>{"use strict";var Je=Se(),Pw=ro(),Rw=Ui(),xf=ve(),kw=mt(),$f=we(),wf=Wo(),Lw=yf(),Af=bs(),$w=If(),Mw=hu(),Dw=Bs(),vu=Je.setImmediate,yu=Je.clearImmediate,Cw=Je.process,fu=Je.Dispatch,Bw=Je.Function,Pf=Je.MessageChannel,Vw=Je.String,mu=0,Gr={},Rf="onreadystatechange",zr,yi,bu,gu;$f(function(){zr=Je.location});var Tu=function(a){if(kw(Gr,a)){var e=Gr[a];delete Gr[a],e()}},Su=function(a){return function(){Tu(a)}},kf=function(a){Tu(a.data)},Lf=function(a){Je.postMessage(Vw(a),zr.protocol+"//"+zr.host)};(!vu||!yu)&&(vu=function(e){$w(arguments.length,1);var t=xf(e)?e:Bw(e),i=Lw(arguments,1);return Gr[++mu]=function(){Pw(t,void 0,i)},yi(mu),mu},yu=function(e){delete Gr[e]},Dw?yi=function(a){Cw.nextTick(Su(a))}:fu&&fu.now?yi=function(a){fu.now(Su(a))}:Pf&&!Mw?(bu=new Pf,gu=bu.port2,bu.port1.onmessage=kf,yi=Rw(gu.postMessage,gu)):Je.addEventListener&&xf(Je.postMessage)&&!Je.importScripts&&zr&&zr.protocol!=="file:"&&!$f(Lf)?(yi=Lf,Je.addEventListener("message",kf,!1)):Rf in Af("script")?yi=function(a){wf.appendChild(Af("script"))[Rf]=function(){wf.removeChild(this),Tu(a)}}:yi=function(a){setTimeout(Su(a),0)});Mf.exports={set:vu,clear:yu}});var Bf=g((iD,Cf)=>{"use strict";var Df=Se(),_w=Ke(),Ow=Object.getOwnPropertyDescriptor;Cf.exports=function(a){if(!_w)return Df[a];var e=Ow(Df,a);return e&&e.value}});var Eu=g((rD,_f)=>{"use strict";var Vf=function(){this.head=null,this.tail=null};Vf.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}}};_f.exports=Vf});var Ff=g((aD,Of)=>{"use strict";var Fw=mi();Of.exports=/ipad|iphone|ipod/i.test(Fw)&&typeof Pebble<"u"});var qf=g((sD,Nf)=>{"use strict";var Nw=mi();Nf.exports=/web0s(?!.*chrome)/i.test(Nw)});var zf=g((nD,Gf)=>{"use strict";var Ki=Se(),qw=Bf(),Uf=Ui(),xu=Iu().set,Uw=Eu(),Hw=hu(),jw=Ff(),Qw=qf(),wu=Bs(),Hf=Ki.MutationObserver||Ki.WebKitMutationObserver,jf=Ki.document,Qf=Ki.process,Vs=Ki.Promise,Ru=qw("queueMicrotask"),Yi,Au,Pu,_s,Wf;Ru||(Yr=new Uw,Kr=function(){var a,e;for(wu&&(a=Qf.domain)&&a.exit();e=Yr.get();)try{e()}catch(t){throw Yr.head&&Yi(),t}a&&a.enter()},!Hw&&!wu&&!Qw&&Hf&&jf?(Au=!0,Pu=jf.createTextNode(""),new Hf(Kr).observe(Pu,{characterData:!0}),Yi=function(){Pu.data=Au=!Au}):!jw&&Vs&&Vs.resolve?(_s=Vs.resolve(void 0),_s.constructor=Vs,Wf=Uf(_s.then,_s),Yi=function(){Wf(Kr)}):wu?Yi=function(){Qf.nextTick(Kr)}:(xu=Uf(xu,Ki),Yi=function(){xu(Kr)}),Ru=function(a){Yr.head||Yi(),Yr.add(a)});var Yr,Kr;Gf.exports=Ru});var Kf=g((oD,Yf)=>{"use strict";Yf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch{}}});var Os=g((uD,Xf)=>{"use strict";Xf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var Ti=g((lD,Jf)=>{"use strict";var Ww=Se();Jf.exports=Ww.Promise});var Xi=g((cD,im)=>{"use strict";var Gw=Se(),Xr=Ti(),zw=ve(),Yw=Ao(),Kw=lu(),Xw=Le(),Zf=ou(),Jw=ft(),ku=ho(),em=Xr&&Xr.prototype,Zw=Xw("species"),Lu=!1,tm=zw(Gw.PromiseRejectionEvent),eA=Yw("Promise",function(){var a=Kw(Xr),e=a!==String(Xr);if(!e&&ku===66||Jw&&!(em.catch&&em.finally))return!0;if(!ku||ku<51||!/native code/.test(a)){var t=new Xr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[Zw]=i,Lu=t.then(function(){})instanceof i,!Lu)return!0}return!e&&(Zf==="BROWSER"||Zf==="DENO")&&!tm});im.exports={CONSTRUCTOR:eA,REJECTION_EVENT:tm,SUBCLASSING:Lu}});var Ji=g((dD,am)=>{"use strict";var rm=wt(),tA=TypeError,iA=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new tA("Bad Promise constructor");e=i,t=r}),this.resolve=rm(e),this.reject=rm(t)};am.exports.f=function(a){return new iA(a)}});var xm=g(()=>{"use strict";var rA=Te(),aA=ft(),Us=Bs(),Zt=Se(),sA=fi(),ir=Xe(),sm=zi(),nm=tu(),nA=Ur(),oA=nf(),uA=wt(),qs=ve(),lA=qe(),cA=uf(),dA=pu(),dm=Iu().set,Bu=zf(),pA=Kf(),hA=Os(),fA=Eu(),pm=Uo(),Hs=Ti(),Vu=Xi(),hm=Ji(),js="Promise",fm=Vu.CONSTRUCTOR,mA=Vu.REJECTION_EVENT,bA=Vu.SUBCLASSING,$u=pm.getterFor(js),gA=pm.set,Zi=Hs&&Hs.prototype,Ii=Hs,Fs=Zi,mm=Zt.TypeError,Mu=Zt.document,_u=Zt.process,Du=hm.f,SA=Du,vA=!!(Mu&&Mu.createEvent&&Zt.dispatchEvent),bm="unhandledrejection",yA="rejectionhandled",om=0,gm=1,TA=2,Ou=1,Sm=2,Ns,um,vm,lm,ym=function(a){var e;return lA(a)&&qs(e=a.then)?e:!1},Tm=function(a,e){var t=e.value,i=e.state===gm,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,u=a.domain,o,l,p;try{r?(i||(e.rejection===Sm&&EA(e),e.rejection=Ou),r===!0?o=t:(u&&u.enter(),o=r(t),u&&(u.exit(),p=!0)),o===a.promise?n(new mm("Promise-chain cycle")):(l=ym(o))?ir(l,o,s,n):s(o)):n(t)}catch(d){u&&!p&&u.exit(),n(d)}},Im=function(a,e){a.notified||(a.notified=!0,Bu(function(){for(var t=a.reactions,i;i=t.get();)Tm(i,a);a.notified=!1,e&&!a.rejection&&IA(a)}))},Em=function(a,e,t){var i,r;vA?(i=Mu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Zt.dispatchEvent(i)):i={promise:e,reason:t},!mA&&(r=Zt["on"+a])?r(i):a===bm&&pA("Unhandled promise rejection",t)},IA=function(a){ir(dm,Zt,function(){var e=a.facade,t=a.value,i=cm(a),r;if(i&&(r=hA(function(){Us?_u.emit("unhandledRejection",t,e):Em(bm,e,t)}),a.rejection=Us||cm(a)?Sm:Ou,r.error))throw r.value})},cm=function(a){return a.rejection!==Ou&&!a.parent},EA=function(a){ir(dm,Zt,function(){var e=a.facade;Us?_u.emit("rejectionHandled",e):Em(yA,e,a.value)})},er=function(a,e,t){return function(i){a(e,i,t)}},tr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=TA,Im(a,!0))},Cu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new mm("Promise can't be resolved itself");var i=ym(e);i?Bu(function(){var r={done:!1};try{ir(i,e,er(Cu,r,a),er(tr,r,a))}catch(s){tr(r,s,a)}}):(a.value=e,a.state=gm,Im(a,!1))}catch(r){tr({done:!1},r,a)}}};if(fm&&(Ii=function(e){cA(this,Fs),uA(e),ir(Ns,this);var t=$u(this);try{e(er(Cu,t),er(tr,t))}catch(i){tr(t,i)}},Fs=Ii.prototype,Ns=function(e){gA(this,{type:js,done:!1,notified:!1,parent:!1,reactions:new fA,rejection:!1,state:om,value:null})},Ns.prototype=sm(Fs,"then",function(e,t){var i=$u(this),r=Du(dA(this,Ii));return i.parent=!0,r.ok=qs(e)?e:!0,r.fail=qs(t)&&t,r.domain=Us?_u.domain:void 0,i.state===om?i.reactions.add(r):Bu(function(){Tm(r,i)}),r.promise}),um=function(){var a=new Ns,e=$u(a);this.promise=a,this.resolve=er(Cu,e),this.reject=er(tr,e)},hm.f=Du=function(a){return a===Ii||a===vm?new um(a):SA(a)},!aA&&qs(Hs)&&Zi!==Object.prototype)){lm=Zi.then,bA||sm(Zi,"then",function(e,t){var i=this;return new Ii(function(r,s){ir(lm,i,r,s)}).then(e,t)},{unsafe:!0});try{delete Zi.constructor}catch{}nm&&nm(Zi,Fs)}rA({global:!0,constructor:!0,wrap:!0,forced:fm},{Promise:Ii});vm=sA.Promise;nA(Ii,js,!1,!0);oA(js)});var km=g((fD,Rm)=>{"use strict";var xA=Le(),Am=xA("iterator"),Pm=!1;try{wm=0,Fu={next:function(){return{done:!!wm++}},return:function(){Pm=!0}},Fu[Am]=function(){return this},Array.from(Fu,function(){throw 2})}catch{}var wm,Fu;Rm.exports=function(a,e){try{if(!e&&!Pm)return!1}catch{return!1}var t=!1;try{var i={};i[Am]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch{}return t}});var Nu=g((mD,Lm)=>{"use strict";var wA=Ti(),AA=km(),PA=Xi().CONSTRUCTOR;Lm.exports=PA||!AA(function(a){wA.all(a).then(void 0,function(){})})});var $m=g(()=>{"use strict";var RA=Te(),kA=Xe(),LA=wt(),$A=Ji(),MA=Os(),DA=Ms(),CA=Nu();RA({target:"Promise",stat:!0,forced:CA},{all:function(e){var t=this,i=$A.f(t),r=i.resolve,s=i.reject,n=MA(function(){var u=LA(t.resolve),o=[],l=0,p=1;DA(e,function(d){var c=l++,h=!1;p++,kA(u,t,d).then(function(m){h||(h=!0,o[c]=m,--p||r(o))},s)}),--p||r(o)});return n.error&&s(n.value),i.promise}})});var Dm=g(()=>{"use strict";var BA=Te(),VA=ft(),_A=Xi().CONSTRUCTOR,Uu=Ti(),OA=Vt(),FA=ve(),NA=zi(),Mm=Uu&&Uu.prototype;BA({target:"Promise",proto:!0,forced:_A,real:!0},{catch:function(a){return this.then(void 0,a)}});!VA&&FA(Uu)&&(qu=OA("Promise").prototype.catch,Mm.catch!==qu&&NA(Mm,"catch",qu,{unsafe:!0}));var qu});var Cm=g(()=>{"use strict";var qA=Te(),UA=Xe(),HA=wt(),jA=Ji(),QA=Os(),WA=Ms(),GA=Nu();qA({target:"Promise",stat:!0,forced:GA},{race:function(e){var t=this,i=jA.f(t),r=i.reject,s=QA(function(){var n=HA(t.resolve);WA(e,function(u){UA(n,t,u).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Bm=g(()=>{"use strict";var zA=Te(),YA=Ji(),KA=Xi().CONSTRUCTOR;zA({target:"Promise",stat:!0,forced:KA},{reject:function(e){var t=YA.f(this),i=t.reject;return i(e),t.promise}})});var Hu=g((xD,Vm)=>{"use strict";var XA=At(),JA=qe(),ZA=Ji();Vm.exports=function(a,e){if(XA(a),JA(e)&&e.constructor===a)return e;var t=ZA.f(a),i=t.resolve;return i(e),t.promise}});var Fm=g(()=>{"use strict";var eP=Te(),tP=Vt(),_m=ft(),iP=Ti(),Om=Xi().CONSTRUCTOR,rP=Hu(),aP=tP("Promise"),sP=_m&&!Om;eP({target:"Promise",stat:!0,forced:_m||Om},{resolve:function(e){return rP(sP&&this===aP?iP:this,e)}})});var Nm=g(()=>{"use strict";xm();$m();Dm();Cm();Bm();Fm()});var jm=g(()=>{"use strict";var nP=Te(),oP=ft(),Qs=Ti(),uP=we(),Um=Vt(),Hm=ve(),lP=pu(),qm=Hu(),cP=zi(),Qu=Qs&&Qs.prototype,dP=!!Qs&&uP(function(){Qu.finally.call({then:function(){}},function(){})});nP({target:"Promise",proto:!0,real:!0,forced:dP},{finally:function(a){var e=lP(this,Um("Promise")),t=Hm(a);return this.then(t?function(i){return qm(e,a()).then(function(){return i})}:a,t?function(i){return qm(e,a()).then(function(){throw i})}:a)}});!oP&&Hm(Qs)&&(ju=Um("Promise").prototype.finally,Qu.finally!==ju&&cP(Qu,"finally",ju,{unsafe:!0}));var ju});var Wm=g(($D,Qm)=>{"use strict";Jh();Nm();jm();var pP=Jt();Qm.exports=pP("Promise","finally")});var zm=g((MD,Gm)=>{"use strict";var hP=Wm();Gm.exports=hP});var Ws=g((DD,Ym)=>{"use strict";var fP=zm();Ym.exports=fP});var db=g(()=>{"use strict";var RP=Te(),kP=Ni(),LP=Wi(),$P=Or(),MP=Fr();RP({target:"Array",proto:!0},{at:function(e){var t=kP(this),i=LP(t),r=$P(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});MP("at")});var hb=g((pB,pb)=>{"use strict";db();var DP=Jt();pb.exports=DP("Array","at")});var mb=g((hB,fb)=>{"use strict";var CP=hb();fb.exports=CP});var gt=g((fB,bb)=>{"use strict";var BP=mb();bb.exports=BP});var pl=g((z0,qb)=>{"use strict";var WP=pi();qb.exports=Array.isArray||function(e){return WP(e)==="Array"}});var Hb=g((Y0,Ub)=>{"use strict";var GP=TypeError,zP=9007199254740991;Ub.exports=function(a){if(a>zP)throw GP("Maximum allowed index exceeded");return a}});var Wb=g((K0,Qb)=>{"use strict";var YP=pl(),KP=Wi(),XP=Hb(),JP=Ui(),jb=function(a,e,t,i,r,s,n,u){for(var o=r,l=0,p=n?JP(n,u):!1,d,c;l<i;)l in t&&(d=p?p(t[l],l,e):t[l],s>0&&YP(d)?(c=KP(d),o=jb(a,e,d,c,o,s-1)-1):(XP(o+1),a[o]=d),o++),l++;return o};Qb.exports=jb});var Kb=g((X0,Yb)=>{"use strict";var Gb=pl(),ZP=du(),eR=qe(),tR=Le(),iR=tR("species"),zb=Array;Yb.exports=function(a){var e;return Gb(a)&&(e=a.constructor,ZP(e)&&(e===zb||Gb(e.prototype))?e=void 0:eR(e)&&(e=e[iR],e===null&&(e=void 0))),e===void 0?zb:e}});var Jb=g((J0,Xb)=>{"use strict";var rR=Kb();Xb.exports=function(a,e){return new(rR(a))(e===0?0:e)}});var Zb=g(()=>{"use strict";var aR=Te(),sR=Wb(),nR=wt(),oR=Ni(),uR=Wi(),lR=Jb();aR({target:"Array",proto:!0},{flatMap:function(e){var t=oR(this),i=uR(t),r;return nR(e),r=lR(t,0),r.length=sR(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var eg=g(()=>{"use strict";var cR=Fr();cR("flatMap")});var ig=g((rV,tg)=>{"use strict";Zb();eg();var dR=Jt();tg.exports=dR("Array","flatMap")});var ag=g((aV,rg)=>{"use strict";var pR=ig();rg.exports=pR});var la=g((sV,sg)=>{"use strict";var hR=ag();sg.exports=hR});var ca=g((nV,ng)=>{"use strict";var fR=qr(),mR=String;ng.exports=function(a){if(fR(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return mR(a)}});var hl=g((oV,og)=>{"use strict";og.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 cg=g((uV,lg)=>{"use strict";var bR=Ae(),gR=Xt(),SR=ca(),ml=hl(),ug=bR("".replace),vR=RegExp("^["+ml+"]+"),yR=RegExp("(^|[^"+ml+"])["+ml+"]+$"),fl=function(a){return function(e){var t=SR(gR(e));return a&1&&(t=ug(t,vR,"")),a&2&&(t=ug(t,yR,"$1")),t}};lg.exports={start:fl(1),end:fl(2),trim:fl(3)}});var fg=g((lV,hg)=>{"use strict";var TR=Qo().PROPER,IR=we(),dg=hl(),pg="\u200B\x85\u180E";hg.exports=function(a){return IR(function(){return!!dg[a]()||pg[a]()!==pg||TR&&dg[a].name!==a})}});var bl=g((cV,mg)=>{"use strict";var ER=cg().start,xR=fg();mg.exports=xR("trimStart")?function(){return ER(this)}:"".trimStart});var gg=g(()=>{"use strict";var wR=Te(),bg=bl();wR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==bg},{trimLeft:bg})});var vg=g(()=>{"use strict";gg();var AR=Te(),Sg=bl();AR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Sg},{trimStart:Sg})});var Tg=g((mV,yg)=>{"use strict";vg();var PR=Jt();yg.exports=PR("String","trimLeft")});var Eg=g((bV,Ig)=>{"use strict";var RR=Tg();Ig.exports=RR});var wg=g((gV,xg)=>{"use strict";var kR=Eg();xg.exports=kR});var Ng=g(()=>{"use strict"});var qg=g(()=>{"use strict"});var Hg=g((JO,Ug)=>{"use strict";var YR=qe(),KR=pi(),XR=Le(),JR=XR("match");Ug.exports=function(a){var e;return YR(a)&&((e=a[JR])!==void 0?!!e:KR(a)==="RegExp")}});var Wg=g((ZO,Qg)=>{"use strict";var ZR=Se(),ek=we(),jg=ZR.RegExp,tk=!ek(function(){var a=!0;try{jg(".","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(jg.prototype,"flags").get.call(e);return u!==i||t!==i});Qg.exports={correct:tk}});var zg=g((eF,Gg)=>{"use strict";var ik=At();Gg.exports=function(){var a=ik(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 Xg=g((tF,Kg)=>{"use strict";var rk=Xe(),ak=mt(),sk=Mr(),Yg=Wg(),nk=zg(),ok=RegExp.prototype;Kg.exports=Yg.correct?function(a){return a.flags}:function(a){return!Yg.correct&&sk(ok,a)&&!ak(a,"flags")?rk(nk,a):a.flags}});var Zg=g((iF,Jg)=>{"use strict";var yl=Ae(),uk=Ni(),lk=Math.floor,Sl=yl("".charAt),ck=yl("".replace),vl=yl("".slice),dk=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,pk=/\$([$&'`]|\d{1,2})/g;Jg.exports=function(a,e,t,i,r,s){var n=t+a.length,u=i.length,o=pk;return r!==void 0&&(r=uk(r),o=dk),ck(s,o,function(l,p){var d;switch(Sl(p,0)){case"$":return"$";case"&":return a;case"`":return vl(e,0,t);case"'":return vl(e,n);case"<":d=r[vl(p,1,-1)];break;default:var c=+p;if(c===0)return l;if(c>u){var h=lk(c/10);return h===0?l:h<=u?i[h-1]===void 0?Sl(p,1):i[h-1]+Sl(p,1):l}d=i[c-1]}return d===void 0?"":d})}});var iS=g(()=>{"use strict";var hk=Te(),fk=Xe(),Il=Ae(),eS=Xt(),mk=ve(),bk=qe(),gk=Hg(),fr=ca(),Sk=Cr(),vk=Xg(),yk=Zg(),Tk=Le(),Ik=ft(),Ek=Tk("replace"),xk=TypeError,Tl=Il("".indexOf),wk=Il("".replace),tS=Il("".slice),Ak=Math.max;hk({target:"String",proto:!0},{replaceAll:function(e,t){var i=eS(this),r,s,n,u,o,l,p,d,c,h,m=0,b="";if(bk(e)){if(r=gk(e),r&&(s=fr(eS(vk(e))),!~Tl(s,"g")))throw new xk("`.replaceAll` does not allow non-global regexes");if(n=Sk(e,Ek),n)return fk(n,e,i,t);if(Ik&&r)return wk(fr(i),e,t)}for(u=fr(i),o=fr(e),l=mk(t),l||(t=fr(t)),p=o.length,d=Ak(1,p),c=Tl(u,o);c!==-1;)h=l?fr(t(o,c,u)):yk(o,u,c,[],void 0,t),b+=tS(u,m,c)+h,m=c+p,c=c+d>u.length?-1:Tl(u,o,c+d);return m<u.length&&(b+=tS(u,m)),b}})});var aS=g((sF,rS)=>{"use strict";Ng();qg();iS();var Pk=Jt();rS.exports=Pk("String","replaceAll")});var nS=g((nF,sS)=>{"use strict";var Rk=aS();sS.exports=Rk});var uS=g((oF,oS)=>{"use strict";var kk=nS();oS.exports=kk});var cS=g((uF,lS)=>{"use strict";var Lk=Or(),$k=ca(),Mk=Xt(),Dk=RangeError;lS.exports=function(e){var t=$k(Mk(this)),i="",r=Lk(e);if(r<0||r===1/0)throw new Dk("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var mS=g((lF,fS)=>{"use strict";var hS=Ae(),Ck=Do(),dS=ca(),Bk=cS(),Vk=Xt(),_k=hS(Bk),Ok=hS("".slice),Fk=Math.ceil,pS=function(a){return function(e,t,i){var r=dS(Vk(e)),s=Ck(t),n=r.length,u=i===void 0?" ":dS(i),o,l;return s<=n||u===""?r:(o=s-n,l=_k(u,Fk(o/u.length)),l.length>o&&(l=Ok(l,0,o)),a?r+l:l+r)}};fS.exports={start:pS(!1),end:pS(!0)}});var gS=g((cF,bS)=>{"use strict";var Nk=mi();bS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(Nk)});var SS=g(()=>{"use strict";var qk=Te(),Uk=mS().start,Hk=gS();qk({target:"String",proto:!0,forced:Hk},{padStart:function(e){return Uk(this,e,arguments.length>1?arguments[1]:void 0)}})});var yS=g((hF,vS)=>{"use strict";SS();var jk=Jt();vS.exports=jk("String","padStart")});var IS=g((fF,TS)=>{"use strict";var Qk=yS();TS.exports=Qk});var xS=g((mF,ES)=>{"use strict";var Wk=IS();ES.exports=Wk});var TL={};Dv(TL,{ChromecastState:()=>Ar,HttpConnectionType:()=>ps,Observable:()=>Ct.Observable,PlaybackState:()=>Ve,Player:()=>is,PredefinedQualityLimits:()=>Pr,SDK_VERSION:()=>yL,Subject:()=>Ct.Subject,Subscription:()=>Ct.Subscription,Surface:()=>hs,VERSION:()=>to,ValueSubject:()=>Ct.ValueSubject,VideoFormat:()=>xt,VideoQuality:()=>Ct.VideoQuality,areValidLiveRecordSources:()=>rb,clientChecker:()=>W,isMobile:()=>rr});module.exports=Cv(TL);var to="2.0.140-dev.7b3cdcf7.0";var Ve=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ve||{}),xt=(w=>(w.MPEG="MPEG",w.DASH="DASH",w.DASH_SEP="DASH_SEP",w.DASH_SEP_VK="DASH_SEP",w.DASH_WEBM="DASH_WEBM",w.DASH_WEBM_AV1="DASH_WEBM_AV1",w.DASH_STREAMS="DASH_STREAMS",w.DASH_WEBM_VK="DASH_WEBM",w.DASH_ONDEMAND="DASH_ONDEMAND",w.DASH_ONDEMAND_VK="DASH_ONDEMAND",w.DASH_LIVE="DASH_LIVE",w.DASH_LIVE_CMAF="DASH_LIVE_CMAF",w.DASH_LIVE_WEBM="DASH_LIVE_WEBM",w.HLS="HLS",w.HLS_ONDEMAND="HLS_ONDEMAND",w.HLS_JS="HLS",w.HLS_FMP4="HLS_FMP4",w.HLS_LIVE="HLS_LIVE",w.HLS_LIVE_CMAF="HLS_LIVE_CMAF",w.WEB_RTC_LIVE="WEB_RTC_LIVE",w))(xt||{});var Ar=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Ar||{}),ps=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(ps||{});var hs=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(hs||{}),Pr=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(Pr||{});var Zl=Q(gi(),1),Ev=Q(Ue(),1);var J=require("@vkontakte/videoplayer-shared/es2024");var gp=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 Ts=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||gp("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)(kI),(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})}}},kI=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 Kl=Q(Ue(),1),cv=Q(Gi(),1),dv=Q(nu(),1);var sb=Q(Ws(),1);var Wu=require("@vkontakte/videoplayer-shared/es2024");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,Wu.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,Wu.assertNever)(e)}};var B=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};var Pt=require("@vkontakte/videoplayer-shared/es2024"),Z=class{constructor(e){this.transitionStarted$=new Pt.Subject;this.transitionEnded$=new Pt.Subject;this.transitionUpdated$=new Pt.Subject;this.forceChanged$=new Pt.Subject;this.stateChangeStarted$=(0,Pt.merge)(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=(0,Pt.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,Pt.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 zu=require("@vkontakte/videoplayer-shared/es2024");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,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 Km=Q(Ue(),1);var rr=()=>/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion??navigator.userAgent)||navigator?.userAgentData?.mobile;var zs=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=rr()}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 Ys=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 Ze=()=>window.ManagedMediaSource||window.MediaSource,ar=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Xm=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Ks=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var mP=document.createElement("video"),bP='video/mp4; codecs="avc1.42000a,mp4a.40.2"',gP='video/mp4; codecs="hev1.1.6.L93.B0"',Jm='video/webm; codecs="vp09.00.10.08"',Zm='video/webm; codecs="av01.0.00M.08"',SP='audio/mp4; codecs="mp4a.40.2"',vP='audio/webm; codecs="opus"',eb,yP=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}};yP().catch(a=>{console.log(mP),console.error(a)});var Xs=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:ar(),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=!!Ze()?.isTypeSupported?.(bP),t=!!Ze()?.isTypeSupported?.(gP),i=!!Ze()?.isTypeSupported?.(SP);this._codecs={h264:e,h265:t,vp9:!!Ze()?.isTypeSupported?.(Jm),av1:!!Ze()?.isTypeSupported?.(Zm),aac:i,opus:!!Ze()?.isTypeSupported?.(vP),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",Js=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:!!Ze()?.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/es2024"),Gu=class{constructor(){this.isInited$=new ib.ValueSubject(!1);this._displayChecker=new Ys,this._deviceChecker=new zs(this._displayChecker),this._browserChecker=new Gs,this._videoChecker=new Xs(this._deviceChecker,this._browserChecker),this._audioChecker=new Js,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)}},W=new Gu;var Yu=a=>{let{containers:e,protocols:t,codecs:i,nativeHlsSupported:r}=W.video,s=(i.h264||i.h265)&&i.aac,n=t.mse||t.mms;return a.filter(u=>{switch(u){case"DASH_SEP":return n&&e.mp4&&s;case"DASH_WEBM":return n&&e.webm&&i.vp9&&i.opus;case"DASH_WEBM_AV1":return n&&e.webm&&i.av1&&i.opus;case"DASH_STREAMS":return n&&(e.mp4&&s||e.webm&&(i.vp9||i.av1)&&(i.opus||i.aac));case"DASH_LIVE":return n&&e.mp4&&s;case"DASH_LIVE_CMAF":return n&&e.mp4&&s&&e.cmaf;case"DASH_ONDEMAND":return n&&e.mp4&&s;case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":case"HLS_LIVE":case"HLS_LIVE_CMAF":return r;case"MPEG":return e.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return t.webrtc&&t.ws&&i.h264&&(e.mp4||e.webm);default:return(0,zu.assertNever)(u)}})},Ku=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_FMP4":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return(0,zu.assertNever)(a)}},rb=a=>{let t=Object.keys(a).filter(i=>!Ku(i));return Yu(t).length>0};var q=require("@vkontakte/videoplayer-shared/es2024");var TP=5,IP=5,EP=500,ab=7e3,Jr=class{constructor(e){this.subscription=new q.Subscription;this.loadMediaTimeoutSubscription=new q.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,q.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,q.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,q.assertNever)(e)}break}default:(0,q.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(Ku(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 q.Subscription;this.subscription.add(e),this.subscription.add((0,q.merge)(this.videoState.stateChangeStarted$.pipe((0,q.map)(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe((0,q.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 q.Subject;e.add(r.pipe((0,q.debounce)(EP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add((0,q.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)>TP)&&r.next(u),s=u})),e.add((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t((0,q.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,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t((0,q.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<IP&&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,q.assertNever)(n)}}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t((0,q.fromEvent)(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=(0,q.merge)(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,q.observableFrom)(["init"])).pipe((0,q.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,q.assertNonNullable)(l);let p=(0,q.getHighestQuality)(Object.keys(l));(0,q.assertNonNullable)(p);let d=l[p];(0,q.assertNonNullable)(d),i=d,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_FMP4":case"HLS_ONDEMAND":{let l=t[e];(0,q.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,q.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,q.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,q.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",p=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:q.ErrorCategory.VIDEO_PIPELINE,message:l,thrown:p}),p}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return(0,q.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,q.isNonNullable)(u)&&(n.metadata.title=u),(0,q.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,q.timeout)(ab).subscribe(()=>s(`timeout(${ab})`)))});(0,sb.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:q.ErrorCategory.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var cl=Q(Ue(),1);var el=require("@vkontakte/videoplayer-shared/es2024");var nb=require("@vkontakte/videoplayer-shared/es2024"),ob=a=>{try{a.pause(),a.playbackRate=0,(0,nb.clearVideoElement)(a),a.remove()}catch(e){console.error(e)}};var Zs=require("@vkontakte/videoplayer-shared/es2024"),Xu=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)}},Ju=window.WeakMap?new WeakMap:new Xu,Zu=window.WeakMap?new WeakMap:new Map,xP=(a,e=20)=>{let t=0;return(0,Zs.fromEvent)(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},He=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?(0,el.clearVideoElement)(i):(i=document.createElement("video"),a.appendChild(i)),Ju.set(i,r);let s=new Zs.Subscription;return s.add(xP(i,e)),Zu.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},je=a=>{Zu.get(a)?.unsubscribe(),Zu.delete(a);let t=Ju.get(a);Ju.delete(a),t?(0,el.clearVideoElement)(a):ob(a)};var tl=Q(gi(),1),U=require("@vkontakte/videoplayer-shared/es2024");var ti=require("@vkontakte/videoplayer-shared/es2024"),en=(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(p=>{let d=a.getState();i(p,d)&&a.setState(p)},s)),i(u,n)||(t(n),o&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(p=>{t(p.to),o&&a.setState(p.to)},s)),l},Rt=(a,e,t)=>en(e,()=>a.loop,i=>{(0,ti.isNonNullable)(i)&&(a.loop=i)},{onError:t}),_e=(a,e,t,i)=>en(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)=>en(e,()=>a.playbackRate,r=>{(0,ti.isNonNullable)(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Zr=en;var wP=a=>["__",a.language,a.label].join("|"),AP=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},il=class a{constructor(e){this.available$=new U.Subject;this.current$=new U.ValueSubject(void 0);this.error$=new U.Subject;this.subscription=new U.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:U.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(Zr(t.internalTextTracks,()=>(0,tl.default)(this.internalTracks),s=>{(0,U.isNonNullable)(s)&&this.setInternal(s)},{equal:(s,n)=>(0,U.isNonNullable)(s)&&(0,U.isNonNullable)(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe((0,U.map)(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Zr(t.externalTextTracks,()=>(0,tl.default)(this.externalTracks),s=>{(0,U.isNonNullable)(s)&&this.setExternal(s)},{equal:(s,n)=>(0,U.isNonNullable)(s)&&(0,U.isNonNullable)(n)&&s.length===n.length&&s.every(({id:u},o)=>u===n[o].id),changed$:this.available$.pipe((0,U.map)(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Zr(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(Zr(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){(0,U.assertNonNullable)(this.video);let{textTracks:e}=this.video;this.subscription.add((0,U.fromEvent)(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add((0,U.merge)((0,U.fromEvent)(e,"addtrack"),(0,U.fromEvent)(e,"removetrack"),(0,U.observableFrom)(["init"])).pipe((0,U.map)(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),(0,U.filterChanged)((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add((0,U.merge)((0,U.fromEvent)(e,"change"),(0,U.observableFrom)(["init"])).pipe((0,U.map)(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),(0,U.map)(i=>i&&this.htmlTextTrackToITextTrack(i).id),(0,U.filterChanged)()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add((0,U.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,U.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,U.isNonNullable)(t.align)&&(r.align=t.align),(0,U.isNonNullable)(t.position)&&(r.position=t.position),(0,U.isNonNullable)(t.size)&&(r.size=t.size),(0,U.isNonNullable)(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){(0,U.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:wP(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,U.assertNonNullable)(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))((0,U.isNullable)(e)||!AP(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,U.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,U.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=il;var Ei=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 ub=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},rl=a=>{let e=ub(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},lb=a=>{let e=ub(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};var $=require("@vkontakte/videoplayer-shared/es2024");var PP=3,cb=(a,e,t=PP)=>{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 Qe=a=>{let e=L=>(0,$.fromEvent)(a,L).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)(()=>cb(a.buffered,a.currentTime)),(0,$.shareReplay)(1)),s=W.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 L=a.error;return{id:L?`MediaError#${L.code}`:"HtmlVideoError",category:$.ErrorCategory.VIDEO_PIPELINE,message:L?L.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)),p=["waiting","seeking","seeked","timeupdate"],d=new $.Subject,c=.3,h;t.add((0,$.merge)(...p.map(L=>(0,$.fromEvent)(a,L))).subscribe(L=>{let te=a.currentTime;a.loop&&(0,$.isNonNullable)(h)&&(0,$.isNonNullable)(te)&&h>=a.duration-c&&te<=c&&d.next(h),h=te}));let m=e("pause").pipe((0,$.filter)(()=>!a.error&&h!==a.duration),(0,$.shareReplay)(1)),b=(0,$.fromEvent)(a,"enterpictureinpicture").pipe((0,$.shareReplay)(1)),S=(0,$.fromEvent)(a,"leavepictureinpicture").pipe((0,$.shareReplay)(1)),v=new $.ValueSubject(lb(a));t.add(b.subscribe(()=>v.next(!0))),t.add(S.subscribe(()=>v.next(!1)));let I=new $.ValueSubject(rl(a)),R=(0,$.fromEvent)(a,"fullscreenchange").pipe((0,$.shareReplay)(1));t.add(R.pipe((0,$.map)(()=>rl(a))).subscribe(I));let w=.1,C=1e3,_=(0,$.fromEvent)(a,"timeupdate").pipe((0,$.map)(L=>a.duration-a.currentTime<w),(0,$.filterChanged)(),(0,$.shareReplay)(1)),O=(0,$.merge)(_.pipe((0,$.filter)(L=>!a.loop&&L)),(0,$.fromEvent)(a,"ended")).pipe((0,$.throttle)(C),(0,$.mapTo)(void 0),(0,$.shareReplay)(1)),j=(0,$.merge)(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(L=>(0,$.fromEvent)(a,L)),_.pipe((0,$.map)(L=>({type:L?"ended":"unknown"})))).pipe((0,$.map)(L=>W.browser.isFirefox&&L.type==="ended"?a.readyState<2:a.readyState<3),(0,$.filterChanged)(),(0,$.shareReplay)(1));return{playing$:s,pause$:m,canplay$:e("canplay"),ended$:O,looped$:d,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$:j,currentBuffer$:r,volumeState$:n,playbackRateState$:u,inPiP$:v,inFullscreen$:I,enterPip$:b,leavePip$:S,destroy:i}};var Ft=require("@vkontakte/videoplayer-shared/es2024"),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 Fe=Q(gt(),1),sl=Q(Ue(),1),xi=Q(Gi(),1),D=require("@vkontakte/videoplayer-shared/es2024");var al=!1,Nt={},gb=a=>{al=a},Sb=()=>{Nt={}},vb=a=>{a(Nt)},ea=(a,e)=>{al&&(Nt.meta=Nt.meta??{},Nt.meta[a]=e)},Oe=class{constructor(e){this.name=e}next(e){if(!al)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/es2024");function yb(a,e,t){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}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 Tb({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 Ab=new Oe("best_bitrate"),rn=(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,D.now)()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},an='Assertion "ABR Tracks is empty array" failed',tn=new WeakMap,Ib=new WeakMap,Eb=new WeakMap,ta=(a,e,t,i)=>{let r=[...e].sort(nr(1)),s=[...t].sort(nr(1)),n=s.filter(o=>(0,D.isNonNullable)(o.bitrate)&&(0,D.isNonNullable)(a.bitrate)?a.bitrate/o.bitrate>i:!0),u=(0,Fe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Fe.default)(s,-1);return u&&(0,sl.default)(n,u)?u:n.length?(0,Fe.default)(n,-1):(0,Fe.default)(s,0)},ia=(a,e,t,i)=>{let r=tn.get(e);r||(r=[...e].sort(nr(1)),tn.set(e,r));let s=tn.get(t);s||(s=[...t].sort(nr(1)),tn.set(t,s));let n=Eb.get(a);n||(n=s.filter(o=>(0,D.isNonNullable)(o.bitrate)&&(0,D.isNonNullable)(a.bitrate)?a.bitrate/o.bitrate>i:!0),Eb.set(a,n));let u=(0,Fe.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1)))??(0,Fe.default)(s,-1);return u&&(0,sl.default)(n,u)?u:n.length?(0,Fe.default)(n,-1):(0,Fe.default)(s,0)},xb=a=>"quality"in a,sn=(a,e,t,i)=>{let r=(0,D.isNonNullable)(i?.last?.bitrate)&&(0,D.isNonNullable)(t?.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&(0,D.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=xb(n)?"video":"audio",o=xb(n)?n.quality:n.bitrate;return e({message:`
|
|
8
8
|
[last ${u} selected] ${o}
|
|
9
|
-
`}),n}return i?.recordSwitch(t),t},
|
|
9
|
+
`}),n}return i?.recordSwitch(t),t},VP=(a,e)=>Math.log(e)/Math.log(a),Pb=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&W.display.pixelRatio){let s=W.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[u=0,o=0,l=0]=a.pixelRatioLogCoefficients,p=VP(n,u*s+o)+l;Number.isFinite(p)&&(r*=p)}}return(0,D.isNonNullable)(t?.min)&&(0,D.isHigherOrEqual)(t.min,a.highQualityLimit)&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},wb=new WeakMap,kt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:p,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:c,stallsPredictedThroughput:h,abrLogger:m,panelSize:b})=>{(0,D.assertNotEmptyArray)(a,an);let{containerSizeFactor:S,containerSizeLimit:v}=Pb({container:e,tuning:i,limits:r,panelSize:b}),I=i.considerPlaybackRate&&(0,D.isNonNullable)(u)?u:1,R=wb.get(a);R||(R=a.filter(x=>!(0,D.isInvariantQuality)(x.quality)).sort((x,k)=>(0,D.isHigher)(x.quality,k.quality)?-1:1),wb.set(a,R));let w=(0,Fe.default)(R,-1)?.quality,C=(0,Fe.default)(R,0)?.quality,_=sr(r,C,w),O=I*rn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),M={},j=null;for(let x of R){let k=!0;if(v)if(x.size)k=x.size.width<=v.width&&x.size.height<=v.height;else{let se=v&&(0,D.videoSizeToQuality)(v);k=se?(0,D.isLowerOrEqual)(x.quality,se):!0}if(!k){M[x.quality]="FitsContainer";continue}let oe=h||t,N=(0,D.isNonNullable)(oe)&&isFinite(oe)&&(0,D.isNonNullable)(x.bitrate)?oe-s>=x.bitrate*O:!0,ae=r?.min===x.quality;if(!N&&!ae){M[x.quality]="FitsThroughput";continue}if(i.lazyQualitySwitch&&(0,D.isNonNullable)(i.minBufferToSwitchUp)&&o&&!(0,D.isInvariantQuality)(o.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,D.isHigher)(x.quality,o.quality)){M[x.quality]="Buffer";continue}if(!!d&&(0,D.isHigherOrEqual)(x.quality,d)&&!ae){M[x.quality]="DroppedFramesLimit";continue}if(!!c&&(0,D.isHigherOrEqual)(x.quality,c)&&!ae){M[x.quality]="StallsLimit";continue}let Re=_||((0,D.isNullable)(r?.max)||(0,D.isLowerOrEqual)(x.quality,r.max))&&((0,D.isNullable)(r?.min)||(0,D.isHigherOrEqual)(x.quality,r.min)),ke=(0,D.isNonNullable)(p)&&!p?(0,D.isLowerOrEqual)(x.quality,i.backgroundVideoQualityLimit):!0;if(!Re||!ke){M[x.quality]="FitsQualityLimits";continue}j||(j=x)}j&&j.bitrate&&Ab.next(j.bitrate);let L=j??(0,Fe.default)(R,-1)??a[0],te=l?.last,F=sn(i,m,L,l);return(0,D.isNonNullable)(l)&&F.quality!==te?.quality&&m({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
|
-
${a.map(
|
|
12
|
+
${a.map(x=>`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${x.size?.width}:${x.size?.height} }`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,xi.default)(i??{}).map(([
|
|
16
|
+
${(0,xi.default)(i??{}).map(([x,k])=>`${x}: ${k}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
|
-
containerSizeFactor: ${
|
|
21
|
-
containerSizeLimit: ${
|
|
20
|
+
containerSizeFactor: ${S},
|
|
21
|
+
containerSizeLimit: ${v?.width??0} x ${v?.height??0},
|
|
22
22
|
estimatedThroughput: ${t},
|
|
23
23
|
stallsPredictedThroughput: ${h},
|
|
24
24
|
reserve: ${s},
|
|
25
25
|
playbackRate: ${u},
|
|
26
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${I},
|
|
27
27
|
forwardBufferHealth: ${n},
|
|
28
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${O},
|
|
29
29
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
30
|
-
droppedVideoMaxQualityLimit: ${
|
|
31
|
-
stallsVideoMaxQualityLimit: ${
|
|
32
|
-
limitsAreInvalid: ${
|
|
30
|
+
droppedVideoMaxQualityLimit: ${d},
|
|
31
|
+
stallsVideoMaxQualityLimit: ${c},
|
|
32
|
+
limitsAreInvalid: ${_},
|
|
33
33
|
maxQualityLimit: ${r?.max},
|
|
34
34
|
minQualityLimit: ${r?.min},
|
|
35
35
|
|
|
36
36
|
[limited video tracks]
|
|
37
|
-
${(0,xi.default)(
|
|
37
|
+
${(0,xi.default)(M).map(([x,k])=>`${x}: ${k}`).join(`
|
|
38
38
|
`)||"All tracks are available"}
|
|
39
39
|
|
|
40
|
-
[best video track] ${
|
|
41
|
-
[selected video track] ${
|
|
42
|
-
`}),
|
|
40
|
+
[best video track] ${j?.quality}
|
|
41
|
+
[selected video track] ${F?.quality}
|
|
42
|
+
`}),F},nn=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:u,current:o,history:l,visible:p,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:c,stallsPredictedThroughput:h,abrLogger:m,panelSize:b})=>{(0,D.assertNotEmptyArray)(a,an);let{containerSizeFactor:S,containerSizeLimit:v}=Pb({container:e,tuning:i,limits:r,panelSize:b}),I=i.considerPlaybackRate&&(0,D.isNonNullable)(u)?u:1,R=a.filter(k=>!(0,D.isInvariantQuality)(k.quality)).sort((k,oe)=>(0,D.isHigher)(k.quality,oe.quality)?-1:1),w=(0,Fe.default)(R,-1)?.quality,C=(0,Fe.default)(R,0)?.quality,_=sr(r,C,w),O=I*rn(n??.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),M={},L=R.filter(k=>{let oe=!0;if(v)if(k.size)oe=k.size.width<=v.width&&k.size.height<=v.height;else{let ie=v&&(0,D.videoSizeToQuality)(v);oe=ie?(0,D.isLowerOrEqual)(k.quality,ie):!0}if(!oe)return M[k.quality]="FitsContainer",!1;let N=h||t,ae=(0,D.isNonNullable)(N)&&isFinite(N)&&(0,D.isNonNullable)(k.bitrate)?N-s>=k.bitrate*O:!0,le=r?.min===k.quality;if(!ae&&!le)return M[k.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&(0,D.isNonNullable)(i.minBufferToSwitchUp)&&o&&!(0,D.isInvariantQuality)(o.quality)&&(n??0)<i.minBufferToSwitchUp&&(0,D.isHigher)(k.quality,o.quality))return M[k.quality]="Buffer",!1;if(!!d&&(0,D.isHigherOrEqual)(k.quality,d)&&!le)return M[k.quality]="DroppedFramesLimit",!1;if(!!c&&(0,D.isHigherOrEqual)(k.quality,c)&&!le)return M[k.quality]="StallsLimit",!1;let ke=_||((0,D.isNullable)(r?.max)||(0,D.isLowerOrEqual)(k.quality,r.max))&&((0,D.isNullable)(r?.min)||(0,D.isHigherOrEqual)(k.quality,r.min)),se=(0,D.isNonNullable)(p)&&!p?(0,D.isLowerOrEqual)(k.quality,i.backgroundVideoQualityLimit):!0;return!ke||!se?(M[k.quality]="FitsQualityLimits",!1):!0})[0];L&&L.bitrate&&Ab.next(L.bitrate);let te=L??(0,Fe.default)(R,-1)??a[0],F=l?.last,x=sn(i,m,te,l);return(0,D.isNonNullable)(l)&&x.quality!==F?.quality&&m({message:`
|
|
43
43
|
[VIDEO TRACKS ABR]
|
|
44
44
|
[available video tracks]
|
|
45
|
-
${a.map(
|
|
45
|
+
${a.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate}, size: ${k.size?.width}:${k.size?.height} }`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,xi.default)(i??{}).map(([
|
|
49
|
+
${(0,xi.default)(i??{}).map(([k,oe])=>`${k}: ${oe}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
53
|
-
containerSizeFactor: ${
|
|
54
|
-
containerSizeLimit: ${
|
|
53
|
+
containerSizeFactor: ${S},
|
|
54
|
+
containerSizeLimit: ${v?.width??0} x ${v?.height??0},
|
|
55
55
|
estimatedThroughput: ${t},
|
|
56
56
|
stallsPredictedThroughput: ${h},
|
|
57
57
|
reserve: ${s},
|
|
58
58
|
playbackRate: ${u},
|
|
59
|
-
playbackRateFactor: ${
|
|
59
|
+
playbackRateFactor: ${I},
|
|
60
60
|
forwardBufferHealth: ${n},
|
|
61
|
-
bitrateFactor: ${
|
|
61
|
+
bitrateFactor: ${O},
|
|
62
62
|
minBufferToSwitchUp: ${i.minBufferToSwitchUp},
|
|
63
|
-
droppedVideoMaxQualityLimit: ${
|
|
64
|
-
stallsVideoMaxQualityLimit: ${
|
|
65
|
-
limitsAreInvalid: ${
|
|
63
|
+
droppedVideoMaxQualityLimit: ${d},
|
|
64
|
+
stallsVideoMaxQualityLimit: ${c},
|
|
65
|
+
limitsAreInvalid: ${_},
|
|
66
66
|
maxQualityLimit: ${r?.max},
|
|
67
67
|
minQualityLimit: ${r?.min},
|
|
68
68
|
|
|
69
69
|
[limited video tracks]
|
|
70
|
-
${(0,xi.default)(
|
|
70
|
+
${(0,xi.default)(M).map(([k,oe])=>`${k}: ${oe}`).join(`
|
|
71
71
|
`)||"All tracks are available"}
|
|
72
72
|
|
|
73
|
-
[best video track] ${
|
|
74
|
-
[selected video track] ${
|
|
75
|
-
`}),
|
|
73
|
+
[best video track] ${L?.quality}
|
|
74
|
+
[selected video track] ${x?.quality}
|
|
75
|
+
`}),x},on=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{(0,D.assertNotEmptyArray)(t,an);let p=r.considerPlaybackRate&&(0,D.isNonNullable)(s)?s:1,d=[...t].sort(nr(-1)),c=a.bitrate;(0,D.assertNonNullable)(c);let h=p*rn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=ta(a,e,t,r.minVideoAudioRatio),S=l||i;(0,D.isNonNullable)(S)&&isFinite(S)&&(m=d.find(R=>(0,D.isNonNullable)(R.bitrate)&&(0,D.isNonNullable)(b?.bitrate)?S-c>=R.bitrate*h&&R.bitrate>=b.bitrate:!1)),m||(m=b);let v=u?.last,I=m&&sn(r,o,m,u);return(0,D.isNonNullable)(u)&&I?.bitrate!==v?.bitrate&&o({message:`
|
|
76
76
|
[AUDIO TRACKS ABR]
|
|
77
77
|
[available audio tracks]
|
|
78
|
-
${t.map(
|
|
78
|
+
${t.map(R=>`{ id: ${R.id}, bitrate: ${R.bitrate} }`).join(`
|
|
79
79
|
`)}
|
|
80
80
|
|
|
81
81
|
[tuning]
|
|
82
|
-
${(0,xi.default)(r??{}).map(([
|
|
82
|
+
${(0,xi.default)(r??{}).map(([R,w])=>`${R}: ${w}`).join(`
|
|
83
83
|
`)}
|
|
84
84
|
|
|
85
85
|
[limit params]
|
|
86
86
|
estimatedThroughput: ${i},
|
|
87
87
|
stallsPredictedThroughput: ${l},
|
|
88
|
-
reserve: ${
|
|
88
|
+
reserve: ${c},
|
|
89
89
|
playbackRate: ${s},
|
|
90
|
-
playbackRateFactor: ${
|
|
90
|
+
playbackRateFactor: ${p},
|
|
91
91
|
forwardBufferHealth: ${n},
|
|
92
92
|
bitrateFactor: ${h},
|
|
93
93
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
94
94
|
|
|
95
|
-
[selected audio track] ${
|
|
96
|
-
`}),
|
|
95
|
+
[selected audio track] ${I?.id}
|
|
96
|
+
`}),I},un=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:u,abrLogger:o,stallsPredictedThroughput:l})=>{(0,D.assertNotEmptyArray)(t,an);let p=r.considerPlaybackRate&&(0,D.isNonNullable)(s)?s:1,d=Ib.get(t);d||(d=[...t].sort(nr(-1)),Ib.set(t,d));let c=a.bitrate;(0,D.assertNonNullable)(c);let h=p*rn(n??.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=ia(a,e,t,r.minVideoAudioRatio),S=l||i;(0,D.isNonNullable)(S)&&isFinite(S)&&(m=d.find(R=>(0,D.isNonNullable)(R.bitrate)&&(0,D.isNonNullable)(b?.bitrate)?S-c>=R.bitrate*h&&R.bitrate>=b.bitrate:!1)),m||(m=b);let v=u?.last,I=m&&sn(r,o,m,u);return(0,D.isNonNullable)(u)&&I?.bitrate!==v?.bitrate&&o({message:`
|
|
97
97
|
[AUDIO TRACKS ABR]
|
|
98
98
|
[available audio tracks]
|
|
99
|
-
${t.map(
|
|
99
|
+
${t.map(R=>`{ id: ${R.id}, bitrate: ${R.bitrate} }`).join(`
|
|
100
100
|
`)}
|
|
101
101
|
|
|
102
102
|
[tuning]
|
|
103
|
-
${(0,xi.default)(r??{}).map(([
|
|
103
|
+
${(0,xi.default)(r??{}).map(([R,w])=>`${R}: ${w}`).join(`
|
|
104
104
|
`)}
|
|
105
105
|
|
|
106
106
|
[limit params]
|
|
107
107
|
estimatedThroughput: ${i},
|
|
108
108
|
stallsPredictedThroughput: ${l},
|
|
109
|
-
reserve: ${
|
|
109
|
+
reserve: ${c},
|
|
110
110
|
playbackRate: ${s},
|
|
111
|
-
playbackRateFactor: ${
|
|
111
|
+
playbackRateFactor: ${p},
|
|
112
112
|
forwardBufferHealth: ${n},
|
|
113
113
|
bitrateFactor: ${h},
|
|
114
114
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
115
115
|
|
|
116
|
-
[selected audio track] ${
|
|
117
|
-
`}),A};var Me=a=>new URL(a).hostname;var G=require("@vkontakte/videoplayer-shared/es2024");var Mb=H(gt(),1);var kb=H(_e(),1),Pb=a=>{if(a instanceof DOMException&&(0,kb.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"))},We=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!Pb(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return Pb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};var et=require("@vkontakte/videoplayer-shared/es2024");var Rb=H(gi(),1),Lt=require("@vkontakte/videoplayer-shared/es2024");function Pe(){return(0,Lt.now)()}function nl(a){return Pe()-a}function ol(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 Lb(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,v=()=>{if(o)return;(0,Lt.assertNonNullable)(c);let O=nl(c),E;if(O<g){E=g-O,setTimeout(v,E);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,U()},S=O=>(s=O,ee),A=O=>(p=O,ee),L=()=>(h="json",ee),x=()=>{if(!o){if(--l>=0){v(),i&&i();return}o=!0,p&&p(),t&&t()}},D=O=>(d=O,ee),U=()=>{c=Pe(),n=new r,n.open("get",a);let O=0,E,R=0,oe=()=>((0,Lt.assertNonNullable)(c),Math.max(c,Math.max(E||0,R||0)));if(s&&n.addEventListener("progress",F=>{let re=Pe();s.updateChunk&&F.loaded>O&&(s.updateChunk(oe(),F.loaded-O),O=F.loaded,E=re)}),u&&(n.timeout=u,n.addEventListener("timeout",()=>x())),n.addEventListener("load",()=>{if(o)return;(0,Lt.assertNonNullable)(n);let F=n.status;if(F>=200&&F<300){let{response:re,responseType:le}=n,ge=re?.byteLength;if(typeof ge=="number"&&s){let Ee=ge-O;Ee&&s.updateChunk&&s.updateChunk(oe(),Ee)}le==="json"&&(!re||!(0,Rb.default)(re).length)?x():(p&&p(),e(re))}else x()}),n.addEventListener("error",()=>{x()}),d){let F=()=>{(0,Lt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(R=Pe(),n.removeEventListener("readystatechange",F))};n.addEventListener("readystatechange",F)}return n.responseType=h,n.send(),ee},ee={withBitrateReporting:S,withParallel:D,withJSONResponse:L,withRetryCount:O=>(l=O,ee),withRetryInterval:(O,E)=>((0,Lt.isNonNullable)(O)&&(g=O),(0,Lt.isNonNullable)(E)&&(m=E),ee),withTimeout:O=>(u=O,ee),withFinally:A,send:U,abort:()=>{n&&(n.abort(),n=void 0),o=!0,p&&p()}};return ee}var ra=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 $b=H(gi(),1);var aa=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Pe(),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=Pe()-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=Pe()}_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=Pe();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,$b.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 Db=require("@vkontakte/videoplayer-shared/es2024");var un=1e4,ul=3;var NP=6e4,qP=10,UP=1,HP=500,sa=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 Db.Subject,this.chunkRateEstimator=new ra(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ol(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=ol(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||{};!yb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Mb.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,et.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=()=>{Lb(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new aa(ul,un,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 x=s&&(!c||c===this.rep);return x||t("Not running!"),x},d=(x,D,U)=>{o&&o.abort(),o=or(this.urlResolver.resolve(x,!1),D,U,()=>this._retryCallback()).withTimeout(un).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ul).withFinally(()=>{o=null}).send()},h=(x,D,U)=>{(0,et.assertNonNullable)(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(x,!1),D,U,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},m=x=>{let D=i.playbackRate;i.playbackRate!==x&&(t(`Playback rate switch: ${D}=>${x}`),i.playbackRate=x)},g=x=>{this.lowLatency=x,t(`lowLatency changed to ${x}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let x=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let U=Pe()-1e4,_=0;for(let V=0;V<this.bufferStates.length;V++){let w=this.bufferStates[V];x=Math.min(x,w.buf),w.ts<U&&_++}this.bufferStates.splice(0,_),t(`update playback rate; minBuffer=${x} drop=${_} jitter=${this.sourceJitter}`);let C=x-UP;this.sourceJitter>=0?C-=this.sourceJitter/2:this.sourceJitter-=1,C>3?m(1.15):C>1?m(1.1):C>.3?m(1.05):m(1)}},S=x=>{let D,U=()=>D&&D.start?D.start.length:0,_=F=>D.start[F]/1e3,C=F=>D.dur[F]/1e3,V=F=>D.fragIndex+F,w=(F,re)=>({chunkIdx:V(F),startTS:_(F),dur:C(F),discontinuity:re}),ee=()=>{let F=0;if(D&&D.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=D.dur.length-1;for(;Ee>=0&&(ge-=D.dur[Ee],!(ge<=0));--Ee);F=Math.min(Ee,D.dur.length-1-le),F=Math.max(F,0)}return w(F,!0)},O=F=>{let re=U();if(!(re<=0)){if((0,et.isNonNullable)(F)){for(let le=0;le<re;le++)if(_(le)>F)return w(le)}return ee()}},E=F=>{let re=U(),le=F?F.chunkIdx+1:0,ge=le-D.fragIndex;if(!(re<=0)){if(!F||ge<0||ge-re>qP)return t(`Resync: offset=${ge} bChunks=${re} chunk=`+JSON.stringify(F)),ee();if(!(ge>=re))return w(le-D.fragIndex,!1)}},R=(F,re,le)=>{l&&l.abort(),l=or(this.urlResolver.resolve(F,!0,this.lowLatency),re,le,()=>this._retryCallback()).withTimeout(un).withRetryCount(ul).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(F,re)=>{R(x,le=>{if(!p())return;D=le;let ge=!!D.lowLatency;ge!==this.lowLatency&&g(ge);let Ee=0;for(let Re=0;Re<D.dur.length;++Re)Ee+=D.dur[Re];Ee>0&&((0,et.assertNonNullable)(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ee/D.dur.length)),r({name:"index",zeroTime:D.zeroTime,shiftDuration:D.shiftDuration}),this.sourceJitter=D.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,D.jitter/1e3)):1,F(O(re))},()=>this._handleNetworkError())},nextChunk:E}},A=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),(0,et.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:x=>{let{videoElement:D,logger:U}=this.params,_=S(e.jidxUrl),C,V,w,ee,O=0,E,R,oe,F=()=>{E&&(clearTimeout(E),E=void 0);let te=Math.max(HP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ne=O+te,Ce=Pe(),xe=Math.min(1e4,Ne-Ce);O=Ce;let at=()=>{l||p()&&_.seek(()=>{p()&&(O=Pe(),re(),F())})};xe>0?E=window.setTimeout(()=>{this.paused?F():at()},xe):at()},re=()=>{let te;for(;te=_.nextChunk(ee);)ee=te,Le(te);let Ne=_.nextChunk(w);if(Ne){if(w&&Ne.discontinuity){U("Detected discontinuity; restarting playback"),this.paused?F():(A(),this._initPlayerWith(e));return}Re(Ne)}else F()},le=(te,Ne)=>{if(!p()||!this.sourceBuffer)return;let Ce,xe,at,Gt=yt=>{window.setTimeout(()=>{p()&&le(te,Ne)},yt)};if(this.sourceBuffer.updating)U("Source buffer is updating; delaying appendBuffer"),Gt(100);else{let yt=Pe(),Ye=D.currentTime;!this.paused&&D.buffered.length>1&&R===Ye&&yt-oe>500&&(U("Stall suspected; trying to fix"),this._fixupStall()),R!==Ye&&(R=Ye,oe=yt);let zt=this._getBufferSizeSec();if(zt>30)U(`Buffered ${zt} seconds; delaying appendBuffer`),Gt(2e3);else try{this.sourceBuffer.appendBuffer(te),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:zt}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ne&&Ne()}catch(Tt){if(Tt.name==="QuotaExceededError")U("QuotaExceededError; delaying appendBuffer"),at=this.sourceBuffer.buffered.length,at!==0&&(Ce=this.sourceBuffer.buffered.start(0),xe=Ye,xe-Ce>4&&this.sourceBuffer.remove(Ce,xe-3)),Gt(1e3);else throw Tt}}},ge=()=>{V&&C&&(U([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(w)]),le(V,function(){V=null,re()}))},Ee=te=>e.fragUrlTemplate.replace("%%id%%",te.chunkIdx),Re=te=>{p()&&h(Ee(te),(Ne,Ce)=>{if(p()){if(Ce/=1e3,V=Ne,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,et.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(te),!1)))},ae=te=>{p()&&(e.cachedHeader=te,le(te,()=>{C=!0,ge()}))};s=!0,_.seek(te=>{if(p()){if(O=Pe(),!te){F();return}ee=te,!(0,et.isNullable)(x)||te.startTS>x?Re(te):(w=te,re())}},x),e.cachedHeader?ae(e.cachedHeader):d(e.headerUrl,ae,()=>this._handleNetworkError())},stop:A,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,et.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,et.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,et.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=Pe();if(this.chunkRateEstimator.addInterval(d,m,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-d,speed:v}),!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&&nl(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=Pe();p<u&&(n=d),u=p}}}_fetchManifest(e,t,i){this.manifestRequest=or(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(un).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;We(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))},NP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Cb=H(Gi(),1),be=require("@vkontakte/videoplayer-shared/es2024"),ll=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,Cb.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=ll;var ln=require("@vkontakte/videoplayer-shared/es2024"),Bb=require("@vkontakte/videoplayer-shared/es2024");var na=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var jP=(a,e)=>new ln.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,u)=>{n.forEach(o=>t.next(o.isIntersecting||na()))},{...i,...e});r.observe(a);let s=(0,Bb.fromEvent)(document,"visibilitychange").pipe((0,ln.map)(n=>!document.hidden||na())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),ut=jP;var QP=["paused","playing","ready"],WP=["paused","playing","ready"],oa=class{constructor(e){this.subscription=new G.Subscription;this.videoState=new Z("stopped");this.representations$=new G.ValueSubject([]);this.droppedFramesManager=new ur;this.maxSeekBackTime$=new G.ValueSubject(1/0);this.zeroTime$=new G.ValueSubject(void 0);this.liveOffset=new Ei;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:G.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,G.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,G.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,cl.default)(WP,e)&&(n||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,cl.default)(QP,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,G.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:G.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,G.merge)(this.videoState.stateChangeStarted$.pipe((0,G.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,G.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=Qe(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,G.map)(r=>r.map(({track:s})=>s)),(0,G.filter)(r=>!!r.length),(0,G.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,G.filterChanged)(),(0,G.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,G.combine)({zeroTime:this.zeroTime$.pipe((0,G.filter)(G.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(je(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,G.videoQualityToHeight)(r),min:s&&(0,G.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,G.assertNever)(r.to)}},t)).add((0,G.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,G.observableFrom)(["init"])).pipe((0,G.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),He(this.video)}createLiveDashPlayer(){let e=new sa({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,G.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,G.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,G.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 Vb=oa;var WS=H(_e(),1);var ke=(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 Y=require("@vkontakte/videoplayer-shared/es2024");var{NativeAbortSignal:V0,NativeAbortController:_0}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self<"u"?self:global);function _b(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 Ob(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 cn=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 cn{constructor(){super(),this.listeners||cn.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 wi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new wi;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}},wi=class{constructor(){Object.defineProperty(this,"signal",{value:new lr,writable:!0,configurable:!0})}abort(e){let t=Ob(e),i=_b(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(wi.prototype[Symbol.toStringTag]="AbortController",lr.prototype[Symbol.toStringTag]="AbortSignal");function dn(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 dl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!dn({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 GP=()=>"fetch"in window,ua=GP()&&dn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Fb=ua?dl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ua?Fb.fetch:window.fetch,G0=ua?Fb.Request:window.Request,ue=ua?wi:window.AbortController,z0=ua?lr:window.AbortSignal;var US=H(_e(),1),Bl=H(la(),1);var wg=H(xg(),1),cr=require("@vkontakte/videoplayer-shared/es2024"),pn=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,wg.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 T=require("@vkontakte/videoplayer-shared/es2024");var mn=H(_e(),1),ki=H(gt(),1),bn=H(la(),1);var Mk=(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)},Dk=a=>window.clearTimeout(a),Ag=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),Pg=!Ag(window.requestIdleCallback)||!Ag(window.cancelIdleCallback),dr=Pg?Mk:window.requestIdleCallback,$t=Pg?Dk:window.cancelIdleCallback;var VS=H(js(),1);var ai=require("@vkontakte/videoplayer-shared/es2024");var Ck=18,kg=!1;try{kg=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=Ck}catch(a){console.error(a)}var gl=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)};kg&&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)}}},Rg=gl;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 P=require("@vkontakte/videoplayer-shared/es2024");var $g=H(gt(),1);var hn=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 Lg=require("@vkontakte/videoplayer-shared/es2024");var da=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,Lg.assertNever)(e)}}};var pa=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 ha=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 fa=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 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.data=this.content}};var Ai=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 ga=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=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 ya=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Ta=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 Ia=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=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 xa=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};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.valid&&(this.sequenceNumber=this.readUint32())}};var Pa=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ka=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 Ra=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 La=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 $a=class extends se{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ma=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 Da=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 Vk={ftyp:pa,moov:ha,mvhd:fa,moof:ma,mdat:ba,sidx:Ai,trak:ga,mdia:Ia,mfhd:Aa,tkhd:Ea,traf:Pa,tfhd:ka,tfdt:Ra,trun:La,minf:xa,sv3d:Sa,st3d:va,prhd:ya,proj:wa,equi:Ta,uuid:da,stbl:$a,stsd:Ma,avc1:Da,unknown:hr},qt=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||!hn(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=Vk[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=>{hn(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 Ok=new TextDecoder("ascii"),Fk=a=>Ok.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",Nk=a=>{let e=new Ai(a,new qt),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})},qk=(a,e)=>{let i=new qt().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)},Uk=a=>{let t=new qt().parse(a),i=new si(t),r={},s=i.findAll("uuid"),n=(0,$g.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},Hk=a=>{let t=new qt().parse(a);return new si(t).find("sidx")?.timescale},jk=(a,e)=>{let i=new qt().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},Qk=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 qt().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},Mg={validateData:Fk,parseInit:Qk,getIndexRange:()=>{},parseSegments:Nk,parseFeedableSegmentChunk:qk,getChunkEndTime:jk,getServerLatencyTimestamps:Uk,getTimescaleFromIndex:Hk};var Va=H(_e(),1),Ut=require("@vkontakte/videoplayer-shared/es2024");var Cg=require("@vkontakte/videoplayer-shared/es2024");var Dg={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"}},Bg=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=Ba(a,t),r=i in Dg,s=r?Dg[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=Ba(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}},Ba=(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 Ba(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,Cg.assertNever)(e)}},Pi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Bg(i);if(!e(r))return;r.type==="master"&&Pi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},Vg=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=Bg(a);return Pi(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 _g=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Wk=[231,22612,22743,167,171,163,160,175],Gk=a=>{let e,t,i,r,s=!1,n=!1,u=!1,o,l,c=!1,p=0;return Pi(a,({tag:d,type:h,value:m,valueSize:g})=>{if(d===21419){let v=St(m,h);l=Ba(v)}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?Pi(m,({tag:v,type:S,value:A})=>v===30321?(c=St(A,S)===1,!1):!0):s&&n&&(0,Va.default)(_g,d)&&(u=!0),!u}),(0,Ut.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Ut.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Ut.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}}}},zk=a=>{if((0,Ut.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Yk=(a,e)=>{let t=!1,i=!1,r=u=>(0,Ut.isNonNullable)(u.time)&&(0,Ut.isNonNullable)(u.position),s=[],n;return Pi(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,Va.default)(_g,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}}})},Kk=a=>{let e=0,t=!1;try{Pi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Va.default)(Wk,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Va.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Og={validateData:Vg,parseInit:Gk,getIndexRange:zk,parseSegments:Yk,parseFeedableSegmentChunk:Kk};var Mt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Og;case"mp4":return Mg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Dt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var xl=H(oS(),1),kS=H(Gi(),1),RS=H(ES(),1),LS=H(gt(),1),wl=H(gi(),1);var xS=H(_e(),1),El=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,xS.default)(["6E","7A","F4"],u)}}return!1};var _a=require("@vkontakte/videoplayer-shared/es2024");var wS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var AS=a=>{try{let e=YR(),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 YR(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
116
|
+
[selected audio track] ${I?.id}
|
|
117
|
+
`}),I};var $e=a=>new URL(a).hostname;var Y=require("@vkontakte/videoplayer-shared/es2024");var Db=Q(gt(),1);var kb=Q(Ue(),1),Rb=a=>{if(a instanceof DOMException&&(0,kb.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"))},We=async(a,e)=>{let t=a.muted;try{await a.play()}catch(i){if(!Rb(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{await a.play()}catch(r){return Rb(r)&&(a.muted=!1,console.warn(r)),!1}}return!0};var et=require("@vkontakte/videoplayer-shared/es2024");var Lb=Q(gi(),1),Lt=require("@vkontakte/videoplayer-shared/es2024");function Pe(){return(0,Lt.now)()}function nl(a){return Pe()-a}function ol(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 $b(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,p,d,c=!1,h="arraybuffer",m=7e3,b=2e3,S=()=>{if(o)return;(0,Lt.assertNonNullable)(p);let F=nl(p),x;if(F<b){x=b-F,setTimeout(S,x);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,_()},v=F=>(s=F,te),I=F=>(d=F,te),R=()=>(h="json",te),w=()=>{if(!o){if(--l>=0){S(),i&&i();return}o=!0,d&&d(),t&&t()}},C=F=>(c=F,te),_=()=>{p=Pe(),n=new r,n.open("get",a);let F=0,x,k=0,oe=()=>((0,Lt.assertNonNullable)(p),Math.max(p,Math.max(x||0,k||0)));if(s&&n.addEventListener("progress",N=>{let ae=Pe();s.updateChunk&&N.loaded>F&&(s.updateChunk(oe(),N.loaded-F),F=N.loaded,x=ae)}),u&&(n.timeout=u,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(o)return;(0,Lt.assertNonNullable)(n);let N=n.status;if(N>=200&&N<300){let{response:ae,responseType:le}=n,ge=ae?.byteLength;if(typeof ge=="number"&&s){let Ee=ge-F;Ee&&s.updateChunk&&s.updateChunk(oe(),Ee)}le==="json"&&(!ae||!(0,Lb.default)(ae).length)?w():(d&&d(),e(ae))}else w()}),n.addEventListener("error",()=>{w()}),c){let N=()=>{(0,Lt.assertNonNullable)(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(k=Pe(),n.removeEventListener("readystatechange",N))};n.addEventListener("readystatechange",N)}return n.responseType=h,n.send(),te},te={withBitrateReporting:v,withParallel:C,withJSONResponse:R,withRetryCount:F=>(l=F,te),withRetryInterval:(F,x)=>((0,Lt.isNonNullable)(F)&&(b=F),(0,Lt.isNonNullable)(x)&&(m=x),te),withTimeout:F=>(u=F,te),withFinally:I,send:_,abort:()=>{n&&(n.abort(),n=void 0),o=!0,d&&d()}};return te}var ra=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 Mb=Q(gi(),1);var aa=class{constructor(e,t,i,r,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Pe(),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=Pe()-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=Pe()}_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=Pe();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,Mb.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 Cb=require("@vkontakte/videoplayer-shared/es2024");var ln=1e4,ul=3;var OP=6e4,FP=10,NP=1,qP=500,sa=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.waitingForFirstBufferAfterSrcChange=!1;this.params=e,this.soundProhibitedEvent$=new Cb.Subject,this.chunkRateEstimator=new ra(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ol(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=ol(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*(W.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||{};!Tb({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Db.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,et.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=()=>{$b(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),this.waitingForFirstBufferAfterSrcChange=!1,s({name:"playing"})):n()})};this.waitingForFirstBufferAfterSrcChange=!0,n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new aa(ul,ln,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,p=!1,d=()=>{let w=s&&(!p||p===this.rep);return w||t("Not running!"),w},c=(w,C,_)=>{o&&o.abort(),o=or(this.urlResolver.resolve(w,!1),C,_,()=>this._retryCallback()).withTimeout(ln).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ul).withFinally(()=>{o=null}).send()},h=(w,C,_)=>{(0,et.assertNonNullable)(this.filesFetcher),u?.abort(),u=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),C,_,()=>this._retryCallback()).withFinally(()=>{u=null}).send()},m=w=>{let C=i.playbackRate;i.playbackRate!==w&&(t(`Playback rate switch: ${C}=>${w}`),i.playbackRate=w)},b=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let _=Pe()-1e4,O=0;for(let j=0;j<this.bufferStates.length;j++){let L=this.bufferStates[j];w=Math.min(w,L.buf),L.ts<_&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${w} drop=${O} jitter=${this.sourceJitter}`);let M=w-NP;this.sourceJitter>=0?M-=this.sourceJitter/2:this.sourceJitter-=1,M>3?m(1.15):M>1?m(1.1):M>.3?m(1.05):m(1)}},v=w=>{let C,_=()=>C&&C.start?C.start.length:0,O=N=>C.start[N]/1e3,M=N=>C.dur[N]/1e3,j=N=>C.fragIndex+N,L=(N,ae)=>({chunkIdx:j(N),startTS:O(N),dur:M(N),discontinuity:ae}),te=()=>{let N=0;if(C&&C.dur){let ae=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,le=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ge=ae;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 L(N,!0)},F=N=>{let ae=_();if(!(ae<=0)){if((0,et.isNonNullable)(N)){for(let le=0;le<ae;le++)if(O(le)>N)return L(le)}return te()}},x=N=>{let ae=_(),le=N?N.chunkIdx+1:0,ge=le-C.fragIndex;if(!(ae<=0)){if(!N||ge<0||ge-ae>FP)return t(`Resync: offset=${ge} bChunks=${ae} chunk=`+JSON.stringify(N)),te();if(!(ge>=ae))return L(le-C.fragIndex,!1)}},k=(N,ae,le)=>{l&&l.abort(),l=or(this.urlResolver.resolve(N,!0,this.lowLatency),ae,le,()=>this._retryCallback()).withTimeout(ln).withRetryCount(ul).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(N,ae)=>{k(w,le=>{if(!d())return;C=le;let ge=!!C.lowLatency;ge!==this.lowLatency&&b(ge);let Ee=0;for(let Re=0;Re<C.dur.length;++Re)Ee+=C.dur[Re];Ee>0&&((0,et.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(ae))},()=>this._handleNetworkError())},nextChunk:x}},I=()=>{s=!1,u&&u.abort(),o&&o.abort(),l&&l.abort(),(0,et.assertNonNullable)(this.filesFetcher),this.filesFetcher.abortAll()};return p={start:w=>{let{videoElement:C,logger:_}=this.params,O=v(e.jidxUrl),M,j,L,te,F=0,x,k,oe,N=()=>{x&&(clearTimeout(x),x=void 0);let ie=Math.max(qP,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ne=F+ie,Ce=Pe(),xe=Math.min(1e4,Ne-Ce);F=Ce;let at=()=>{l||d()&&O.seek(()=>{d()&&(F=Pe(),ae(),N())})};xe>0?x=window.setTimeout(()=>{this.paused?N():at()},xe):at()},ae=()=>{let ie;for(;ie=O.nextChunk(te);)te=ie,ke(ie);let Ne=O.nextChunk(L);if(Ne){if(L&&Ne.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?N():(I(),this._initPlayerWith(e));return}Re(Ne)}else N()},le=(ie,Ne)=>{if(!d()||!this.sourceBuffer)return;let Ce,xe,at,Gt=yt=>{window.setTimeout(()=>{d()&&le(ie,Ne)},yt)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),Gt(100);else{let yt=Pe(),Ye=C.currentTime;!this.paused&&C.buffered.length>1&&k===Ye&&yt-oe>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),k!==Ye&&(k=Ye,oe=yt);let zt=this._getBufferSizeSec();if(zt>30)_(`Buffered ${zt} seconds; delaying appendBuffer`),Gt(2e3);else try{this.sourceBuffer.appendBuffer(ie),this.videoPlayStarted?(this.bufferStates.push({ts:yt,buf:zt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ne&&Ne()}catch(Tt){if(Tt.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),at=this.sourceBuffer.buffered.length,at!==0&&(Ce=this.sourceBuffer.buffered.start(0),xe=Ye,xe-Ce>4&&this.sourceBuffer.remove(Ce,xe-3)),Gt(1e3);else throw Tt}}},ge=()=>{j&&M&&(_([`Appending chunk, sz=${j.byteLength}:`,JSON.stringify(L)]),le(j,function(){j=null,ae()}))},Ee=ie=>e.fragUrlTemplate.replace("%%id%%",ie.chunkIdx),Re=ie=>{d()&&h(Ee(ie),(Ne,Ce)=>{if(d()){if(Ce/=1e3,j=Ne,L=ie,n=ie.startTS,Ce){let xe=Math.min(10,ie.dur/Ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}ge()}},()=>this._handleNetworkError())},ke=ie=>{d()&&((0,et.assertNonNullable)(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(ie),!1)))},se=ie=>{d()&&(e.cachedHeader=ie,le(ie,()=>{M=!0,ge()}))};s=!0,O.seek(ie=>{if(d()){if(F=Pe(),!ie){N();return}te=ie,!(0,et.isNullable)(w)||ie.startTS>w?Re(ie):(L=ie,ae())}},w),e.cachedHeader?se(e.cachedHeader):c(e.headerUrl,se,()=>this._handleNetworkError())},stop:I,getTimestampSec:()=>n},p}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),(0,et.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,et.assertNonNullable)(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return(0,et.isNonNullable)(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let c,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}c=this._selectQuality(d),c?this._switchToQuality(c):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(c,h)=>{let m=Pe();if(this.chunkRateEstimator.addInterval(c,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-c,speed:S}),!0}},get:()=>{let c=this.chunkRateEstimator.getBitRate();return c?c*.85:0}},n=-1/0,u,o=!0,l=()=>{let d=s.get();if(d&&u&&this.autoQuality){if(o&&d>u&&nl(n)<3e4)return;i(d)}o=this.autoQuality};return{updateChunk:(d,c)=>{let h=s.updateChunk(d,c);return h&&l(),h},notifySwitch:d=>{let c=Pe();d<u&&(n=c),u=d}}}_fetchManifest(e,t,i){this.manifestRequest=or(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ln).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;We(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))},OP))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Bb=Q(Gi(),1),be=require("@vkontakte/videoplayer-shared/es2024"),ll=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,Bb.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=ll;var cn=require("@vkontakte/videoplayer-shared/es2024"),Vb=require("@vkontakte/videoplayer-shared/es2024");var na=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var UP=(a,e)=>new cn.Observable(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,u)=>{n.forEach(o=>t.next(o.isIntersecting||na()))},{...i,...e});r.observe(a);let s=(0,Vb.fromEvent)(document,"visibilitychange").pipe((0,cn.map)(n=>!document.hidden||na())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),ut=UP;var HP=["paused","playing","ready"],jP=["paused","playing","ready"],oa=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new Z("stopped");this.representations$=new Y.ValueSubject([]);this.droppedFramesManager=new ur;this.maxSeekBackTime$=new Y.ValueSubject(1/0);this.zeroTime$=new Y.ValueSubject(void 0);this.liveOffset=new Ei;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:Y.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,Y.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,Y.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,cl.default)(jP,e)&&(n||u)){this.prepare();return}if(r?.to!=="paused"&&s.state==="requested"&&(0,cl.default)(HP,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,Y.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:Y.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add((0,Y.merge)(this.videoState.stateChangeStarted$.pipe((0,Y.map)(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe((0,Y.map)(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=He(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($e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=Qe(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe((0,Y.map)(r=>r.map(({track:s})=>s)),(0,Y.filter)(r=>!!r.length),(0,Y.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,Y.filterChanged)(),(0,Y.map)(r=>-r/1e3)).subscribe(this.params.output.duration$)).add((0,Y.combine)({zeroTime:this.zeroTime$.pipe((0,Y.filter)(Y.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(Rt(this.video,this.params.desiredState.isLooped,t)).add(_e(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(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,Y.videoQualityToHeight)(r),min:s&&(0,Y.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,Y.assertNever)(r.to)}},t)).add((0,Y.merge)(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,(0,Y.observableFrom)(["init"])).pipe((0,Y.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),je(this.video)}createLiveDashPlayer(){let e=new sa({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,Y.isNonNullable)(t)?t:kt(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:p})=>p.id===s)?.representation;(0,Y.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,Y.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=oa;var Me=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};var V=require("@vkontakte/videoplayer-shared/es2024");var{NativeAbortSignal:C0,NativeAbortController:B0}=function(a){return{NativeAbortSignal:a.AbortSignal,NativeAbortController:a.AbortController}}(typeof self<"u"?self:global);function Ob(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 Fb(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 dn=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 dn{constructor(){super(),this.listeners||dn.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 wi;return setTimeout(()=>t.abort(new DOMException(`This signal is timeout in ${e}ms`,"TimeoutError")),e),t.signal}static any(e){let t=new wi;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}},wi=class{constructor(){Object.defineProperty(this,"signal",{value:new lr,writable:!0,configurable:!0})}abort(e){let t=Fb(e),i=Ob(t);this.signal.reason=t,this.signal.dispatchEvent(i)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(wi.prototype[Symbol.toStringTag]="AbortController",lr.prototype[Symbol.toStringTag]="AbortSignal");function pn(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 dl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!pn({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,p){let d;p&&p.signal&&(d=p.signal,delete p.signal);let c=new t(l,p);return d&&Object.defineProperty(c,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),c},s.prototype=t.prototype);let n=e;return{fetch:(o,l)=>{let p=s&&s.prototype.isPrototypeOf(o)?o.signal:l?l.signal:void 0;if(p){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(p.aborted)return Promise.reject(d);let c=new Promise((h,m)=>{p.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([c,n(o,l)])}return n(o,l)},Request:s}}var QP=()=>"fetch"in window,ua=QP()&&pn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Nb=ua?dl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ua?Nb.fetch:window.fetch,Q0=ua?Nb.Request:window.Request,ue=ua?wi:window.AbortController,W0=ua?lr:window.AbortSignal;var US=Q(Ue(),1),Bl=Q(la(),1);var Ag=Q(wg(),1),cr=require("@vkontakte/videoplayer-shared/es2024"),hn=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,Ag.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 T=require("@vkontakte/videoplayer-shared/es2024");var bn=Q(Ue(),1),Ri=Q(gt(),1),gn=Q(la(),1);var LR=(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)},$R=a=>window.clearTimeout(a),Pg=a=>typeof a=="function"&&a?.toString().endsWith("{ [native code] }"),Rg=!Pg(window.requestIdleCallback)||!Pg(window.cancelIdleCallback),dr=Rg?LR:window.requestIdleCallback,$t=Rg?$R:window.cancelIdleCallback;var VS=Q(Ws(),1);var ai=require("@vkontakte/videoplayer-shared/es2024");var MR=18,kg=!1;try{kg=W.browser.isSafari&&!!W.browser.safariVersion&&W.browser.safariVersion<=MR}catch(a){console.error(a)}var gl=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)};kg&&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)}}},Lg=gl;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/es2024");var Mg=Q(gt(),1);var fn=a=>a.valid,ne=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 ne{};var $g=require("@vkontakte/videoplayer-shared/es2024");var da=class extends ne{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,$g.assertNever)(e)}}};var pa=class extends ne{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 ha=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pe=class extends ne{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 fa=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 ma=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ba=class extends ne{constructor(e,t){super(e,t),this.data=this.content}};var Ai=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 ga=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var va=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 ya=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32())}};var Ta=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 Ia=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ea=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 xa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Aa=class extends pe{constructor(e,t){super(e,t),this.valid&&(this.sequenceNumber=this.readUint32())}};var Pa=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ra=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 La=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 $a=class extends ne{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ma=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 Da=class extends ne{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 CR={ftyp:pa,moov:ha,mvhd:fa,moof:ma,mdat:ba,sidx:Ai,trak:ga,mdia:Ia,mfhd:Aa,tkhd:Ea,traf:Pa,tfhd:Ra,tfdt:ka,trun:La,minf:xa,sv3d:Sa,st3d:va,prhd:ya,proj:wa,equi:Ta,uuid:da,stbl:$a,stsd:Ma,avc1:Da,unknown:hr},qt=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||!fn(n))break;t.push(n),i+=n.size}return t}createBox(e,t){let i=CR[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=>{fn(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 VR=new TextDecoder("ascii"),_R=a=>VR.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",OR=a=>{let e=new Ai(a,new qt),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})},FR=(a,e)=>{let i=new qt().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,d=o.source.byteOffset-u.source.byteOffset+o.size;return new DataView(a.buffer,l,d)},NR=a=>{let t=new qt().parse(a),i=new si(t),r={},s=i.findAll("uuid"),n=(0,Mg.default)(s,-1);return n?{serverDataReceivedTimestamp:n.userData.received,serverDataPreparedTime:n.userData.received}:r},qR=a=>{let t=new qt().parse(a);return new si(t).find("sidx")?.timescale},UR=(a,e)=>{let i=new qt().parse(a),s=new si(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),u=s[s.length-1].children.find(d=>d.type==="tfdt"),o=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return o.sampleDuration.length?l=o.sampleDuration.reduce((d,c)=>d+c,0):l=n.defaultSampleDuration*o.sampleCount,(Number(u.baseMediaDecodeTime)+l)/e*1e3},HR=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 qt().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},Dg={validateData:_R,parseInit:HR,getIndexRange:()=>{},parseSegments:OR,parseFeedableSegmentChunk:FR,getChunkEndTime:UR,getServerLatencyTimestamps:NR,getTimescaleFromIndex:qR};var Va=Q(Ue(),1),Ut=require("@vkontakte/videoplayer-shared/es2024");var Bg=require("@vkontakte/videoplayer-shared/es2024");var Cg={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"}},Vg=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=Ba(a,t),r=i in Cg,s=r?Cg[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,p=Ba(o),d=l*2**((u-1)*8)+p,c=t+u,h;return c+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+c):h=new DataView(a.buffer,a.byteOffset+c,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:c,tagSize:c+d,value:h,valueSize:d}},Ba=(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 Ba(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,Bg.assertNever)(e)}},Pi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=Vg(i);if(!e(r))return;r.type==="master"&&Pi(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=Vg(a);return Pi(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 Og=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],jR=[231,22612,22743,167,171,163,160,175],QR=a=>{let e,t,i,r,s=!1,n=!1,u=!1,o,l,p=!1,d=0;return Pi(a,({tag:c,type:h,value:m,valueSize:b})=>{if(c===21419){let S=St(m,h);l=Ba(S)}else c!==21420&&(l=void 0);return c===408125543?(e=m.byteOffset,t=m.byteOffset+b):c===357149030?s=!0:c===290298740?n=!0:c===2807729?i=St(m,h):c===17545?r=St(m,h):c===21420&&l===475249515?o=St(m,h):c===374648427?Pi(m,({tag:S,type:v,value:I})=>S===30321?(p=St(I,v)===1,!1):!0):s&&n&&(0,Va.default)(Og,c)&&(u=!0),!u}),(0,Ut.assertNonNullable)(e,"Failed to parse webm Segment start"),(0,Ut.assertNonNullable)(t,"Failed to parse webm Segment end"),(0,Ut.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:p,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},WR=a=>{if((0,Ut.isNullable)(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},GR=(a,e)=>{let t=!1,i=!1,r=u=>(0,Ut.isNonNullable)(u.time)&&(0,Ut.isNonNullable)(u.position),s=[],n;return Pi(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,Va.default)(Og,u)&&(i=!0)}return!(t&&i)}),n&&r(n)&&s.push(n),s.map((u,o)=>{let{time:l,position:p}=u,d=s[o+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+p,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},zR=a=>{let e=0,t=!1;try{Pi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Va.default)(jR,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||=(0,Va.default)([163,160,175],i.tag)),!0):!1)}catch{}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},Fg={validateData:_g,parseInit:QR,getIndexRange:WR,parseSegments:GR,parseFeedableSegmentChunk:zR};var Mt=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return Fg;case"mp4":return Dg}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Dt=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var xl=Q(uS(),1),kS=Q(Gi(),1),LS=Q(xS(),1),$S=Q(gt(),1),wl=Q(gi(),1);var wS=Q(Ue(),1),El=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,wS.default)(["6E","7A","F4"],u)}}return!1};var _a=require("@vkontakte/videoplayer-shared/es2024");var AS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var PS=a=>{try{let e=Gk(),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 Gk(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",p=`^(?:(?<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 PS=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,xl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,kS.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,xl.default)(t,n,(u,o)=>(0,_a.isNullable)(s)?u:(0,_a.isNullable)(o)?s:(0,RS.default)(s,parseInt(o,10),"0"))}return t},fn=(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(V=>V.textContent?.trim()??""),u=(0,LS.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,v;o&&(v={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 S,A=s.getAttribute("mediaPresentationDuration"),L=[...s.getElementsByTagName("Period")],x=L.reduce((V,w)=>({...V,[w.id]:w.children}),{}),D=L.reduce((V,w)=>({...V,[w.id]:w.getAttribute("duration")}),{});A?S=PS(A):(0,wl.default)(D).filter(V=>V).length&&!o?S=(0,wl.default)(D).reduce((V,w)=>V+(PS(w)??0),0):g&&(S=parseInt(g,10));let U=0,_=s.getAttribute("profiles")?.split(",")??[];for(let V of L.map(w=>w.id))for(let w of x[V]){let ee=w.getAttribute("id")??"id"+(U++).toString(10),O=w.getAttribute("mimeType")??"",E=w.getAttribute("codecs")??"",R=w.getAttribute("contentType")??O?.split("/")[0],oe=w.getAttribute("profiles")?.split(",")??[],F=AS(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:F.language,isDefault:Ee==="main",label:re,codecs:E,hdr:Re==="video"&&El(E),mime:O,representations:[]};for(let ae of le){let te=ae.getAttribute("lang")??void 0,Ne=re??w.getAttribute("label")??ae.getAttribute("label")??void 0,Ce=ae.querySelector("BaseURL")?.textContent?.trim()??"",xe=new URL(Ce||u,e).toString(),at=ae.getAttribute("mimeType")??O,Gt=ae.getAttribute("codecs")??E??"",yt;if(R==="text"){let Ye=ae.getAttribute("id")||"",zt=F.privateuse?.includes("x-auto")||Ye.includes("_auto"),Tt=ae.querySelector("SegmentTemplate");if(Tt){let Ir={representationId:ae.getAttribute("id")??void 0,bandwidth:ae.getAttribute("bandwidth")??void 0},ts=parseInt(ae.getAttribute("bandwidth")??"",10)/1e3,is=parseInt(Tt.getAttribute("startNumber")??"",10)??1,Ci=parseInt(Tt.getAttribute("timescale")??"",10),Jn=Tt.querySelectorAll("SegmentTimeline S")??[],Bi=Tt.getAttribute("media");if(!Bi)continue;let rs=[],as=0,ss="",Vi=0,Er=is,Be=0;for(let dt of Jn){let li=parseInt(dt.getAttribute("d")??"",10),st=parseInt(dt.getAttribute("r")??"",10)||0,Yt=parseInt(dt.getAttribute("t")??"",10);Be=Number.isFinite(Yt)?Yt:Be;let ci=li/Ci*1e3,_i=Be/Ci*1e3;for(let It=0;It<st+1;It++){let Kt=vt(Bi,{...Ir,segmentNumber:Er.toString(10),segmentTime:(Be+It*li).toString(10)}),Oi=(_i??0)+It*ci,wr=Oi+ci;Er++,rs.push({time:{from:Oi,to:wr},url:Kt})}Be+=(st+1)*li,as+=(st+1)*ci}Vi=Be/Ci*1e3,ss=vt(Bi,{...Ir,segmentNumber:Er.toString(10),segmentTime:Be.toString(10)});let xr={time:{from:Vi,to:1/0},url:ss},Bt={type:"template",baseUrl:xe,segmentTemplateUrl:Bi,initUrl:"",totalSegmentsDurationMs:as,segments:rs,nextSegmentBeyondManifest:xr,timescale:Ci};yt={id:Ye,kind:"text",segmentReference:Bt,profiles:[],duration:S,bitrate:ts,mime:"",codecs:"",width:0,height:0,isAuto:zt}}else yt={id:Ye,isAuto:zt,kind:"text",url:xe}}else{let Ye=ae.getAttribute("contentType")??at?.split("/")[0]??R,zt=w.getAttribute("profiles")?.split(",")??[],Tt=parseInt(ae.getAttribute("width")??"",10),Ir=parseInt(ae.getAttribute("height")??"",10),ts=parseInt(ae.getAttribute("bandwidth")??"",10)/1e3,is=ae.getAttribute("frameRate")??"",Ci=ae.getAttribute("quality")??void 0,Jn=is?wS(is):void 0,Bi=ae.getAttribute("id")??"id"+(U++).toString(10),rs=Ye==="video"?`${Ir}p`:Ye==="audio"?`${ts}Kbps`:Gt,as=`${Bi}@${rs}`,ss=[..._,...oe,...zt],Vi,Er=ae.querySelector("SegmentBase"),Be=ae.querySelector("SegmentTemplate")??ge;if(Er){let Bt=ae.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[dt,li]=Bt.split("-").map(Kt=>parseInt(Kt,10)),st={from:dt,to:li},Yt=ae.querySelector("SegmentBase")?.getAttribute("indexRange"),[ci,_i]=Yt?Yt.split("-").map(Kt=>parseInt(Kt,10)):[],It=Yt?{from:ci,to:_i}:void 0;Vi={type:"byteRange",url:xe,initRange:st,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")??"",st=Be.getAttribute("media"),Yt=parseInt(Be.getAttribute("startNumber")??"",10)??1,ci=vt(li,Bt);if(!st)throw new ReferenceError("No media attribute in SegmentTemplate");let _i=Be.querySelectorAll("SegmentTimeline S")??[],It=[],Kt=0,Oi="",wr=0;if(_i.length){let ns=Yt,pt=0;for(let Fi of _i){let Et=parseInt(Fi.getAttribute("d")??"",10),di=parseInt(Fi.getAttribute("r")??"",10)||0,os=parseInt(Fi.getAttribute("t")??"",10);pt=Number.isFinite(os)?os:pt;let Zn=Et/dt*1e3,Pv=pt/dt*1e3;for(let us=0;us<di+1;us++){let kv=vt(st,{...Bt,segmentNumber:ns.toString(10),segmentTime:(pt+us*Et).toString(10)}),ec=(Pv??0)+us*Zn,Rv=ec+Zn;ns++,It.push({time:{from:ec,to:Rv},url:kv})}pt+=(di+1)*Et,Kt+=(di+1)*Zn}wr=pt/dt*1e3,Oi=vt(st,{...Bt,segmentNumber:ns.toString(10),segmentTime:pt.toString(10)})}else if((0,_a.isNonNullable)(S)){let pt=parseInt(Be.getAttribute("duration")??"",10)/dt*1e3,Fi=Math.ceil(S/pt),Et=0;for(let di=1;di<Fi;di++){let os=vt(st,{...Bt,segmentNumber:di.toString(10),segmentTime:Et.toString(10)});It.push({time:{from:Et,to:Et+pt},url:os}),Et+=pt}wr=Et,Oi=vt(st,{...Bt,segmentNumber:Fi.toString(10),segmentTime:Et.toString(10)})}let Av={time:{from:wr,to:1/0},url:Oi};Vi={type:"template",baseUrl:xe,segmentTemplateUrl:st,initUrl:ci,totalSegmentsDurationMs:Kt,segments:It,nextSegmentBeyondManifest:Av,timescale:dt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ye||!at)continue;let xr={video:"video",audio:"audio",text:"text"}[Ye];if(!xr)continue;Re||=xr,yt={id:as,kind:xr,segmentReference:Vi,profiles:ss,duration:S,bitrate:ts,mime:at,codecs:Gt,width:Tt,height:Ir,fps:Jn,quality:Ci}}Le.language||=te,Le.label||=Ne,Le.mime||=at,Le.codecs||=Gt,Le.hdr||=Re==="video"&&El(Gt),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(at=>at.id===te.id)?.segmentReference,xe=te.segmentReference;xe.segments.push(...Ce.segments),xe.nextSegmentBeyondManifest=Ce.nextSegmentBeyondManifest}else r[Re].push(Le)}}return{duration:S,streams:r,baseUrls:n,live:v}};var Al=H(gt(),1);var $S=require("@vkontakte/videoplayer-shared/es2024"),MS=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?ii(s):void 0)??(0,$S.videoSizeToQuality)({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},DS=({id:a,bitrate:e})=>({id:a,bitrate:e}),CS=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),BS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Pl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Al.default)(i.split("."),0),isDefault:r}),kl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Al.default)(r.split("."),0)}),Rl=a=>"url"in a,tt=a=>a.type==="template";var Ll=require("@vkontakte/videoplayer-shared/es2024"),z=(a,e)=>(0,Ll.isNonNullable)(a)&&(0,Ll.isNonNullable)(e)&&a.readyState==="open"&&KR(a,e);function KR(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Oa=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.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 Rg(this.sourceBuffer),this.subscription.add((0,P.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let u,o=this.mediaSource.readyState;o!=="open"&&(u={id:`SegmentEjection_source_${o}`,category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),u??={id:"SegmentEjection",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(u)})),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||!z(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,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(!z(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||!z(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(!z(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||!z(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,bn.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){!z(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||!z(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)||!z(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=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,mn.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,P.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,bn.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,bn.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,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,P.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(!tt(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 v=h<=i&&m>=i,S=h>i||v||g===0&&i===0,A=Math.min(this.forwardBufferTarget,this.bufferLimit),L=this.preloadOnly&&h<=i+A||r<A&&m-h>=A||m<=i+A;return(d==="none"||d==="partially_ejected"&&S&&L&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,m)))&&S&&L});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"){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,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,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,mn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!z(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||!z(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 v=new DataView(e.buffer,e.byteOffset+c,d);await this.sourceBufferTaskQueue.append(v,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 v=new DataView(e.buffer,e.byteOffset+c+o.feedingBytes,o.loadedBytes-o.feedingBytes),S=o.loadedBytes===d?v:g.parseFeedableSegmentChunk(v);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)||!z(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",Rl(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,VS.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(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&&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||!z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,P.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=Rl(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,mn.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||!z(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||!z(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||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,P.isNullable)(e)?0:ke(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!z(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||!z(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:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||(0,P.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:P.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 gn=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 Q=require("@vkontakte/videoplayer-shared/es2024");var Sn=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var yn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new Q.Subject;this.manifestReceived=new Q.Subject;this.firstBytesRequested=new Q.Subject;this.firstBytesReceived=new Q.Subject;this.lastConnectionType$=new Q.ValueSubject(void 0);this.lastConnectionReused$=new Q.ValueSubject(void 0);this.lastRequestFirstBytes$=new Q.ValueSubject(void 0);this.recoverableError$=new Q.Subject;this.error$=new Q.Subject;this.abortAllController=new ue;this.subscription=new Q.SubscriptionRemovable;this.fetchManifest=(0,Q.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=Sn(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(vn);return r?(t.log("success",(0,Q.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,Q.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,Q.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,Q.assertNever)(t)}this.requestQuic&&(c=ni(c));let h=this.abortAllController.signal,m;if(n){let E=new ue;if(m=(0,Q.merge)((0,Q.fromEvent)(this.abortAllController.signal,"abort"),(0,Q.fromEvent)(n,"abort")).subscribe(()=>{try{E.abort()}catch(R){vn(R)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(R){vn(R)}h=E.signal}let g=0,v=(0,Q.now)();d.log("startRequest",(0,Q.flattenObject)({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:v})),this.firstBytesRequested.next();let S=yield this.doFetch(c,{priority:s,headers:p,signal:h}),A=(0,Q.now)();if(!S)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(A-v),!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,Q.now)(),R={requestStartedAt:v,requestEndedAt:E,duration:E-v};return d.log("endRequest",(0,Q.flattenObject)(R)),d.end(),S.arrayBuffer()}let L=S.body;if(u){let E;[L,E]=S.body.tee(),this.throughputEstimator?.trackStream(E,o)}let x=L.getReader(),D,U=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(U)&&(D=U),!D&&i&&(D=i.to-i.from+1);let _=D?new Uint8Array(D):new Uint8Array(0),C=!1,V=E=>{this.unsubscribeAbortSubscription(m),C=!0,vn(E)},w=(0,Q.abortable)(h,async function*({done:E,value:R}){if(g===0&&(this.lastRequestFirstBytes$.next((0,Q.now)()-v),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(m);return}if(!E&&R){if(l&&D)_.set(R,g),g+=R.byteLength;else{let oe=new Uint8Array(_.length+R.length);oe.set(_),oe.set(R,_.length),_=oe,g+=R.byteLength}r?.(new DataView(_.buffer),g),yield x?.read().then(w,V)}}.bind(this));yield x?.read().then(w,V),this.unsubscribeAbortSubscription(m);let ee=(0,Q.now)(),O={failed:C,requestStartedAt:v,requestEndedAt:ee,duration:ee-v};return C?(d.error("endRequest",(0,Q.flattenObject)(O)),d.end(),null):(d.log("endRequest",(0,Q.flattenObject)(O)),d.end(),_.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,Q.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 S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;g=new DataView(S)}let v=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(p),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,Q.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}=gn(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,Q.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:Q.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Q.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Q.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Q.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Q.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},vn=a=>{if(!Dt(a))throw a};var Ht=(a,e,t)=>t*e+(1-t)*a,$l=(a,e)=>a.reduce((t,i)=>t+i,0)/e,_S=(a,e,t,i)=>{let r=0,s=t,n=$l(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 Fa=require("@vkontakte/videoplayer-shared/es2024"),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 Fa.ValueSubject(e.initial),this.debounced$=new Fa.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Oe(`raw_${t}`),this.smoothedSeries$=new Oe(`smoothed_${t}`),this.reportedSeries$=new Oe(`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,Fa.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 Tn=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 In=class extends oi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=$l(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ht(this.emaSmoothed,e,this.params.emaAlpha);let i=_S(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var En=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 Tn({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new In({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 En({initial:e,label:"liveEdgeDelay",...t})}};var gr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var xn=require("@vkontakte/videoplayer-shared/es2024");var Na=class a{constructor(e,t){this.currentRepresentation$=new xn.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,xn.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 An=H(gt(),1),Ml=H(_e(),1),qa=require("@vkontakte/videoplayer-shared/es2024");var wn=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,qa.assertNever)(a)}return[t,i]},OS=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...wn(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(j.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...wn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...wn(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...wn(a),...s,"HLS","HLS_ONDEMAND"];default:(0,qa.assertNever)(e)}if(j.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:(0,qa.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},FS=({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,qa.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"]},Dl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Pn=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,An.default)(t.value.split("."),0)}for(let t of a){let i=(0,An.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,An.default)(e.value.split("."),0)},kn=a=>{let e=a.map(i=>Sr(i)),{codecs:t}=j.video;return eL().filter(i=>{if((0,Ml.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Rn=a=>{let e=a.map(i=>Sr(i)),{codecs:t}=j.video;return tL().filter(i=>{if((0,Ml.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Sr=a=>a.split(".")[0].replace("0",""),eL=()=>["av1","vp9","hev1","avc1"],tL=()=>["opus","mp4a"];var aL=["timeupdate","progress","play","seeked","stalled","waiting"],sL=["timeupdate","progress","loadeddata","playing","seeked"];var Ln=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new T.Subscription;this.representationSubscription=new T.Subscription;this.state$=new Z("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.manifestRequested=new T.Subject;this.manifestReceived=new T.Subject;this.firstBytesRequested=new T.Subject;this.firstBytesReceived=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.destroyController=new ue;this.initManifest=(0,T.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:T.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,T.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=fn(e??"",this.manifestUrlString)}catch(o){let l=pn(e)??{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,c)=>!!(this.element?.canPlayType?.(l)&&Ze()?.isTypeSupported?.(`${l}; codecs="${c}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:p}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";p||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let c=t.streams[o].filter(({mime:d,codecs:h})=>i(o,d,h));r[o]=c;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let d=c.map(({codecs:h})=>h);o==="audio"&&(n=Rn(d),p=n[0]),o==="video"&&(s=kn(d),this.forceVideoCodec&&(0,US.default)(s,this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[o]=c.filter(({codecs:h})=>Sr(h)===p))}else{let d=new Set(c.map(({codecs:h})=>h));p=Pn(d),p&&(r[o]=c.filter(({codecs:h})=>h.startsWith(p)))}if(o==="video"){let d=this.tuning.preferHDR,h=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);j.display.isHDR&&d&&h?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",(0,T.flattenObject)(u)),u}.bind(this));this.initRepresentations=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=d=>{this.representationSubscription.add((0,T.fromEvent)(d,"error").pipe((0,T.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=zs();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ar())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 Oa("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let d=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Oa("audio",this.source,d,n),this.bufferManagers.push(this.audioBufferManager)}Na.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Na(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,T.merge)(...sL.map(d=>(0,T.fromEvent)(this.element,d))).pipe((0,T.map)(d=>this.element?ke(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(d=>{d>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,T.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,T.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,T.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||gr(this.element,1)})),this.representationSubscription.add((0,T.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.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,T.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,T.filter)(({isLive:h})=>h),(0,T.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,T.map)(({rtt:h,bufferLength:m,segmentServerLatency:g})=>{let v=ei(this.manifestUrlString,2);return(h/2+m+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:g})=>{if(!g||!m)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,L=h-v;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(L)>S&&(x=1+Math.sign(L)*A),gr(this.element,x)})),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(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??g))-g}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let d=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,v=ei(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,A=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),L=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,D=isFinite(h)?h:m,U=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),_=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(_);let C="none";if(U?C="active_low_latency":this.isLowLatency$.getValue()&&_?(this.bufferManagers.forEach(V=>V.proceedLowLatencyLive()),C="active_low_latency"):v!==0&&D<A?C="live_forward_buffering":D<A+x&&(C="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),C==="live_forward_buffering"||C==="live_with_target_offset"){let V=d-(A+L),w=this.normolizeLiveOffset(Math.trunc(v+V/g)),ee=Math.abs(w-v),O=0;!h||ee<=this.tuning.dashCmafLive.offsetCalculationError?O=v:w>0&&ee>this.tuning.dashCmafLive.offsetCalculationError&&(O=w),this.manifestUrlString=ye(this.manifestUrlString,O,2)}(C==="live_with_target_offset"||C==="live_forward_buffering")&&(d=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:T.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,T.merge)(...this.bufferManagers.map(d=>d.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(d=>d.fullyBuffered$.getValue()))),c=(0,T.merge)(...this.bufferManagers.map(d=>d.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(d=>d.onLastSegment$.getValue()))),p=(0,T.combine)({allBuffersFull:l,someBufferEnded:c}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:d,someBufferEnded:h})=>d&&h),(0,T.filter)(d=>d));if(this.representationSubscription.add((0,T.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:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add((0,T.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:T.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,Bl.default)((0,Bl.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,T.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,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:T.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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new yn({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,T.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.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,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...aL.map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.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,T.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:T.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,T.flattenObject)(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,T.interval)(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:T.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,T.assertNonNullable)(this.element),(0,T.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,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.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}getCodecs(){return this.manifest?.codecs}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,T.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,T.flattenObject)(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var $n=class{constructor(e,t){this.fov=e,this.orientation=t}};var Mn=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 HS=`attribute vec2 a_vertex;
|
|
124
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(p,"i")}var RS=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,xl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,kS.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,xl.default)(t,n,(u,o)=>(0,_a.isNullable)(s)?u:(0,_a.isNullable)(o)?s:(0,LS.default)(s,parseInt(o,10),"0"))}return t},mn=(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(j=>j.textContent?.trim()??""),u=(0,$S.default)(n,0)??"",o=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),p=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],c=d?.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,h=d?.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d?.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,S;o&&(S={availabilityStartTime:l?new Date(l).getTime():0,publishTime:p?new Date(p).getTime():0,latestSegmentPublishTime:c?new Date(c).getTime():0,streamIsAlive:h==="yes",streamIsUnpublished:m==="yes"});let v,I=s.getAttribute("mediaPresentationDuration"),R=[...s.getElementsByTagName("Period")],w=R.reduce((j,L)=>({...j,[L.id]:L.children}),{}),C=R.reduce((j,L)=>({...j,[L.id]:L.getAttribute("duration")}),{});I?v=RS(I):(0,wl.default)(C).filter(j=>j).length&&!o?v=(0,wl.default)(C).reduce((j,L)=>j+(RS(L)??0),0):b&&(v=parseInt(b,10));let _=0,O=s.getAttribute("profiles")?.split(",")??[];for(let j of R.map(L=>L.id))for(let L of w[j]){let te=L.getAttribute("id")??"id"+(_++).toString(10),F=L.getAttribute("mimeType")??"",x=L.getAttribute("codecs")??"",k=L.getAttribute("contentType")??F?.split("/")[0],oe=L.getAttribute("profiles")?.split(",")??[],N=PS(L.getAttribute("lang")??"")??{},ae=L.querySelector("Label")?.textContent?.trim()??void 0,le=L.querySelectorAll("Representation"),ge=L.querySelector("SegmentTemplate"),Ee=L.querySelector("Role")?.getAttribute("value")??void 0,Re=k,ke={id:te,language:N.language,isDefault:Ee==="main",label:ae,codecs:x,hdr:Re==="video"&&El(x),mime:F,representations:[]};for(let se of le){let ie=se.getAttribute("lang")??void 0,Ne=ae??L.getAttribute("label")??se.getAttribute("label")??void 0,Ce=se.querySelector("BaseURL")?.textContent?.trim()??"",xe=new URL(Ce||u,e).toString(),at=se.getAttribute("mimeType")??F,Gt=se.getAttribute("codecs")??x??"",yt;if(k==="text"){let Ye=se.getAttribute("id")||"",zt=N.privateuse?.includes("x-auto")||Ye.includes("_auto"),Tt=se.querySelector("SegmentTemplate");if(Tt){let Ir={representationId:se.getAttribute("id")??void 0,bandwidth:se.getAttribute("bandwidth")??void 0},rs=parseInt(se.getAttribute("bandwidth")??"",10)/1e3,as=parseInt(Tt.getAttribute("startNumber")??"",10)??1,Ci=parseInt(Tt.getAttribute("timescale")??"",10),Zn=Tt.querySelectorAll("SegmentTimeline S")??[],Bi=Tt.getAttribute("media");if(!Bi)continue;let ss=[],ns=0,os="",Vi=0,Er=as,Be=0;for(let dt of Zn){let li=parseInt(dt.getAttribute("d")??"",10),st=parseInt(dt.getAttribute("r")??"",10)||0,Yt=parseInt(dt.getAttribute("t")??"",10);Be=Number.isFinite(Yt)?Yt:Be;let ci=li/Ci*1e3,_i=Be/Ci*1e3;for(let It=0;It<st+1;It++){let Kt=vt(Bi,{...Ir,segmentNumber:Er.toString(10),segmentTime:(Be+It*li).toString(10)}),Oi=(_i??0)+It*ci,wr=Oi+ci;Er++,ss.push({time:{from:Oi,to:wr},url:Kt})}Be+=(st+1)*li,ns+=(st+1)*ci}Vi=Be/Ci*1e3,os=vt(Bi,{...Ir,segmentNumber:Er.toString(10),segmentTime:Be.toString(10)});let xr={time:{from:Vi,to:1/0},url:os},Bt={type:"template",baseUrl:xe,segmentTemplateUrl:Bi,initUrl:"",totalSegmentsDurationMs:ns,segments:ss,nextSegmentBeyondManifest:xr,timescale:Ci};yt={id:Ye,kind:"text",segmentReference:Bt,profiles:[],duration:v,bitrate:rs,mime:"",codecs:"",width:0,height:0,isAuto:zt}}else yt={id:Ye,isAuto:zt,kind:"text",url:xe}}else{let Ye=se.getAttribute("contentType")??at?.split("/")[0]??k,zt=L.getAttribute("profiles")?.split(",")??[],Tt=parseInt(se.getAttribute("width")??"",10),Ir=parseInt(se.getAttribute("height")??"",10),rs=parseInt(se.getAttribute("bandwidth")??"",10)/1e3,as=se.getAttribute("frameRate")??"",Ci=se.getAttribute("quality")??void 0,Zn=as?AS(as):void 0,Bi=se.getAttribute("id")??"id"+(_++).toString(10),ss=Ye==="video"?`${Ir}p`:Ye==="audio"?`${rs}Kbps`:Gt,ns=`${Bi}@${ss}`,os=[...O,...oe,...zt],Vi,Er=se.querySelector("SegmentBase"),Be=se.querySelector("SegmentTemplate")??ge;if(Er){let Bt=se.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[dt,li]=Bt.split("-").map(Kt=>parseInt(Kt,10)),st={from:dt,to:li},Yt=se.querySelector("SegmentBase")?.getAttribute("indexRange"),[ci,_i]=Yt?Yt.split("-").map(Kt=>parseInt(Kt,10)):[],It=Yt?{from:ci,to:_i}:void 0;Vi={type:"byteRange",url:xe,initRange:st,indexRange:It}}else if(Be){let Bt={representationId:se.getAttribute("id")??void 0,bandwidth:se.getAttribute("bandwidth")??void 0},dt=parseInt(Be.getAttribute("timescale")??"",10),li=Be.getAttribute("initialization")??"",st=Be.getAttribute("media"),Yt=parseInt(Be.getAttribute("startNumber")??"",10)??1,ci=vt(li,Bt);if(!st)throw new ReferenceError("No media attribute in SegmentTemplate");let _i=Be.querySelectorAll("SegmentTimeline S")??[],It=[],Kt=0,Oi="",wr=0;if(_i.length){let us=Yt,pt=0;for(let Fi of _i){let Et=parseInt(Fi.getAttribute("d")??"",10),di=parseInt(Fi.getAttribute("r")??"",10)||0,ls=parseInt(Fi.getAttribute("t")??"",10);pt=Number.isFinite(ls)?ls:pt;let eo=Et/dt*1e3,wv=pt/dt*1e3;for(let cs=0;cs<di+1;cs++){let Av=vt(st,{...Bt,segmentNumber:us.toString(10),segmentTime:(pt+cs*Et).toString(10)}),ec=(wv??0)+cs*eo,Pv=ec+eo;us++,It.push({time:{from:ec,to:Pv},url:Av})}pt+=(di+1)*Et,Kt+=(di+1)*eo}wr=pt/dt*1e3,Oi=vt(st,{...Bt,segmentNumber:us.toString(10),segmentTime:pt.toString(10)})}else if((0,_a.isNonNullable)(v)){let pt=parseInt(Be.getAttribute("duration")??"",10)/dt*1e3,Fi=Math.ceil(v/pt),Et=0;for(let di=1;di<Fi;di++){let ls=vt(st,{...Bt,segmentNumber:di.toString(10),segmentTime:Et.toString(10)});It.push({time:{from:Et,to:Et+pt},url:ls}),Et+=pt}wr=Et,Oi=vt(st,{...Bt,segmentNumber:Fi.toString(10),segmentTime:Et.toString(10)})}let xv={time:{from:wr,to:1/0},url:Oi};Vi={type:"template",baseUrl:xe,segmentTemplateUrl:st,initUrl:ci,totalSegmentsDurationMs:Kt,segments:It,nextSegmentBeyondManifest:xv,timescale:dt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ye||!at)continue;let xr={video:"video",audio:"audio",text:"text"}[Ye];if(!xr)continue;Re||=xr,yt={id:ns,kind:xr,segmentReference:Vi,profiles:os,duration:v,bitrate:rs,mime:at,codecs:Gt,width:Tt,height:Ir,fps:Zn,quality:Ci}}ke.language||=ie,ke.label||=Ne,ke.mime||=at,ke.codecs||=Gt,ke.hdr||=Re==="video"&&El(Gt),ke.representations.push(yt)}if(Re){let se=r[Re].find(ie=>ie.id===ke.id);if(se&&ke.representations.every(ie=>ie.segmentReference.type==="template"))for(let ie of se.representations){let Ce=ke.representations.find(at=>at.id===ie.id)?.segmentReference,xe=ie.segmentReference;xe.segments.push(...Ce.segments),xe.nextSegmentBeyondManifest=Ce.nextSegmentBeyondManifest}else r[Re].push(ke)}}return{duration:v,streams:r,baseUrls:n,live:S}};var Al=Q(gt(),1);var MS=require("@vkontakte/videoplayer-shared/es2024"),Oa=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?ii(s):void 0)??(0,MS.videoSizeToQuality)({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},DS=({id:a,bitrate:e})=>({id:a,bitrate:e}),CS=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),BS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Pl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Al.default)(i.split("."),0),isDefault:r}),Rl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Al.default)(r.split("."),0)}),kl=a=>"url"in a,tt=a=>a.type==="template";var Ll=require("@vkontakte/videoplayer-shared/es2024"),K=(a,e)=>(0,Ll.isNonNullable)(a)&&(0,Ll.isNonNullable)(e)&&a.readyState==="open"&&zk(a,e);function zk(a,e){for(let t=0;t<a.activeSourceBuffers.length;++t)if(a.activeSourceBuffers[t]===e)return!0;return!1}var Fa=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.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=(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 Lg(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||!K(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,pr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=this.getForwardBufferDuration(u),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<p).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(!K(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||!K(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(!K(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||!K(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,gn.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(c=>c.id===o);l&&this.representations.set(o,l);let p=this.representations.get(o);if(!p||!tt(p.segmentReference))return;let d=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.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 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(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!K(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||!K(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)||!K(this.mediaSource,this.sourceBuffer)||(0,A.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if((0,A.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,A.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,A.isNullable)(r)||(0,A.isNullable)(s))return;let n=r.find(c=>e>=c.time.from&&e<c.time.to);(0,A.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let u=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),h=Oa(i),m=Oa(t),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,A.isNonNullable)(h)&&(0,A.isNonNullable)(m)&&(0,A.isHigher)(h.quality,m.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(b||S?u+=Math.min(c,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=n.time.to-e+o&&(u=n?n.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let I=[...this.segments.entries()].map(([R,w])=>{let C=w.find(_=>e>=_.time.from&&e<_.time.to);return{representationId:R,status:C?.status}}).find(R=>R.status==="fed")?.representationId;if(!I)return;this.playingRepresentationId=I,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))}}if(isFinite(this.bufferLimit)&&pr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let p=[];if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,u),p.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,bn.default)(p,n))c="high";else{let h=(0,Ri.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(p,t,c).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=(0,Ri.default)(r,-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-this.getForwardBufferDuration(e)<o),this.onLastSegment$.next(e-d.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,gn.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,gn.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,Ri.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,Ri.default)(e,-1)?.time.to:0)||0}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!tt(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:c,time:{from:h,to:m}},b)=>{let S=h<=i&&m>=i,v=h>i||S||b===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),R=this.preloadOnly&&h<=i+I||r<I&&m-h>=I||m<=i+I;return(c==="none"||c==="partially_ejected"&&v&&R&&this.sourceBuffer&&K(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,m)))&&v&&R});if(s===-1)return[];if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<n.length&&(u<=p||o<=d);c++){let h=n[c];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,A.abortable)(u,async function*(){let p=(0,A.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,p))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let p=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)(),!p)return;let d=new DataView(p),c=Mt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(d,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=c.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Dt(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())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,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(tt(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,Ri.default)(e,0).byte.from,to:(0,Ri.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(!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,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,A.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,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:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,bn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!K(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),p=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(o.status="partially_fed",u.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),u.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!K(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 p=l.byte.from-i,d=l.byte.to-i,c=d-p+1,h=p<r,m=d<=r;if(!h)continue;let b=Mt(u.mime);if(l.status==="downloading"&&m){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+p,c);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(c,r-p),o.loadedBytes>o.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),v=o.loadedBytes===c?S:b.parseFeedableSegmentChunk(S);v?.byteLength&&(l.status="partially_fed",o.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(o.fedBytes+=v.byteLength,o.fedBytes===c&&this.onSegmentFullyAppended(o,t)):await n())}}}onSegmentFullyAppended(e,t){if(!((0,A.isNullable)(this.sourceBuffer)||!K(this.mediaSource,this.sourceBuffer))){!this.isLive&&W.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.tuning.dash.useNewRepresentationSwitch||(this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))),e.segment.status="fed",kl(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,VS.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:p}=u,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let c=p;this.isLive&&tt(e.segmentReference)&&(c=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,c),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||!K(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,A.isNullable)(e))return!1;let r=[],s=0,n=o=>{o.sort((p,d)=>p.from-d.from);let l=[o[0]];for(let p=1;p<o.length;p++){let{from:d,to:c}=o[p],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,c):l.push(o[p])}return l},u=o=>{if(s>=t)return r;r.push({...o.time}),r=n(r);let l=kl(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 p=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(p||d)&&l.status==="fed"&&u(l)}for(let o=0;o<this.sourceBuffer.buffered.length;o++){let l=this.sourceBuffer.buffered.start(o)*1e3,p=this.sourceBuffer.buffered.end(o)*1e3,d=0;for(let c of this.segments.values())for(let h of c)(0,bn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(p)&&d++;if(d===this.segments.size){let c={time:{from:l,to:p},url:"",status:"none"};u(c)}}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 p of l)p.time.from>=e+o&&p.status==="fed"&&u(p)}return r.length?(await Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,p)=>l||p,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!K(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||!K(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||!K(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,A.isNullable)(e)?0:Me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!K(this.mediaSource,this.sourceBuffer)))for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to,persistent:!1},{buffered:s}=this.sourceBuffer;for(let n=0;n<s.length;n++){let u=s.start(n)*1e3,o=s.end(n)*1e3;if(!(o<=i.time.from||u>=i.time.to)){if(u<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),u<i.time.to&&u>i.time.from&&(r.to=u)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){if(this.gapDetectionIdleCallback||!this.sourceBuffer||!K(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,{usePersistentGaps:r}=this.tuning.dash;this.gaps=this.gaps.filter(s=>{if(r&&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}),this.gapDetectionIdleCallback=dr(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:A.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,A.isNullable)(this.sourceBuffer)||!K(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(p=>p.from-t<=n&&p.to+t>=u),l=e.filter(p=>n>=p.from&&n<p.to-t||u>p.from+t&&u<=p.to);o||(l.length===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category: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 Sn=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 G=require("@vkontakte/videoplayer-shared/es2024");var vn=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Tn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new G.Subject;this.manifestReceived=new G.Subject;this.firstBytesRequested=new G.Subject;this.firstBytesReceived=new G.Subject;this.lastConnectionType$=new G.ValueSubject(void 0);this.lastConnectionReused$=new G.ValueSubject(void 0);this.lastRequestFirstBytes$=new G.ValueSubject(void 0);this.recoverableError$=new G.Subject;this.error$=new G.Subject;this.abortAllController=new ue;this.subscription=new G.SubscriptionRemovable;this.fetchManifest=(0,G.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=vn(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(yn);return r?(t.log("success",(0,G.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,G.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,G.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 p=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let x=new URL(p,location.href);x.searchParams.append("bytes",`${i.from}-${i.to}`),p=x.toString();break}default:(0,G.assertNever)(t)}this.requestQuic&&(p=ni(p));let h=this.abortAllController.signal,m;if(n){let x=new ue;if(m=(0,G.merge)((0,G.fromEvent)(this.abortAllController.signal,"abort"),(0,G.fromEvent)(n,"abort")).subscribe(()=>{try{x.abort()}catch(k){yn(k)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{x.abort()}catch(k){yn(k)}h=x.signal}let b=0,S=(0,G.now)();c.log("startRequest",(0,G.flattenObject)({url:p,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:S})),this.firstBytesRequested.next();let v=yield this.doFetch(p,{priority:s,headers:d,signal:h}),I=(0,G.now)();if(!v)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(I-S),!v.ok||!v.body){this.unsubscribeAbortSubscription(m);let x=`Fetch error ${v.status}: ${v.statusText}`;return c.error("error",{message:x}),c.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let x=(0,G.now)(),k={requestStartedAt:S,requestEndedAt:x,duration:x-S};return c.log("endRequest",(0,G.flattenObject)(k)),c.end(),v.arrayBuffer()}let R=v.body;if(u){let x;[R,x]=v.body.tee(),this.throughputEstimator?.trackStream(x,o)}let w=R.getReader(),C,_=parseInt(v.headers.get("content-length")??"",10);Number.isFinite(_)&&(C=_),!C&&i&&(C=i.to-i.from+1);let O=C?new Uint8Array(C):new Uint8Array(0),M=!1,j=x=>{this.unsubscribeAbortSubscription(m),M=!0,yn(x)},L=(0,G.abortable)(h,async function*({done:x,value:k}){if(b===0&&(this.lastRequestFirstBytes$.next((0,G.now)()-S),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(m);return}if(!x&&k){if(l&&C)O.set(k,b),b+=k.byteLength;else{let oe=new Uint8Array(O.length+k.length);oe.set(O),oe.set(k,O.length),O=oe,b+=k.byteLength}r?.(new DataView(O.buffer),b),yield w?.read().then(L,j)}}.bind(this));yield w?.read().then(L,j),this.unsubscribeAbortSubscription(m);let te=(0,G.now)(),F={failed:M,requestStartedAt:S,requestEndedAt:te,duration:te-S};return M?(c.error("endRequest",(0,G.flattenObject)(F)),c.end(),null):(c.log("endRequest",(0,G.flattenObject)(F)),c.end(),O.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,G.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,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(p,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!d)return null;let c=new DataView(d,r-n,s-n+1);if(!t.validateData(c))throw new Error("Invalid media file");let h=t.parseInit(c),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(d,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,G.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}=Sn(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,G.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:G.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:G.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:G.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:G.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:G.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},yn=a=>{if(!Dt(a))throw a};var Ht=(a,e,t)=>t*e+(1-t)*a,$l=(a,e)=>a.reduce((t,i)=>t+i,0)/e,_S=(a,e,t,i)=>{let r=0,s=t,n=$l(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 Na=require("@vkontakte/videoplayer-shared/es2024"),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 Na.ValueSubject(e.initial),this.debounced$=new Na.ValueSubject(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Oe(`raw_${t}`),this.smoothedSeries$=new Oe(`smoothed_${t}`),this.reportedSeries$=new Oe(`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,Na.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 In=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 En=class extends oi{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=$l(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ht(this.emaSmoothed,e,this.params.emaAlpha);let i=_S(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var xn=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 In({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new En({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 xn({initial:e,label:"liveEdgeDelay",...t})}};var gr=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};var wn=require("@vkontakte/videoplayer-shared/es2024");var qa=class a{constructor(e,t){this.currentRepresentation$=new wn.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,wn.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 Pn=Q(gt(),1),Ml=Q(Ue(),1),Ua=require("@vkontakte/videoplayer-shared/es2024");var An=a=>{let{webmDecodingInfo:e}=W.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,Ua.assertNever)(a)}return[t,i]},OS=({webmCodec:a,androidPreferredFormat:e,iosPreferredFormat:t,preferMultiStream:i})=>{let r=[...i?["DASH_STREAMS"]:[],...An(a),"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]],s=[...i?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...i?[]:["DASH_STREAMS"]];if(W.device.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...s,"MPEG",...An(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...An(a),"MPEG",...s,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...An(a),...s,"HLS","HLS_ONDEMAND"];default:(0,Ua.assertNever)(e)}if(W.video.nativeHlsSupported)switch(t){case"hls":return[...r,"HLS","HLS_FMP4","HLS_ONDEMAND","MPEG"];case"hls_fmp4":return[...r,"HLS_FMP4","HLS","HLS_ONDEMAND","MPEG"];default:(0,Ua.assertNever)(t)}return[...r,"HLS","HLS_ONDEMAND","MPEG"]},FS=({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=W.device.isMac&&W.browser.isSafari;if(W.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,Ua.assertNever)(a)}else W.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"]},Dl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Rn=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,Pn.default)(t.value.split("."),0)}for(let t of a){let i=(0,Pn.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,Pn.default)(e.value.split("."),0)},kn=a=>{let e=a.map(i=>Sr(i)),{codecs:t}=W.video;return Jk().filter(i=>{if((0,Ml.default)(e,i))switch(i){case"av1":return t.av1;case"vp9":return t.vp9;case"avc1":return t.h264;case"hev1":return t.h265;default:return!1}else return!1})},Ln=a=>{let e=a.map(i=>Sr(i)),{codecs:t}=W.video;return Zk().filter(i=>{if((0,Ml.default)(e,i))switch(i){case"opus":return t.opus;case"mp4a":return t.aac;default:return!1}else return!1})},Sr=a=>a.split(".")[0].replace("0",""),Jk=()=>["av1","vp9","hev1","avc1"],Zk=()=>["opus","mp4a"];var iL=["timeupdate","progress","play","seeked","stalled","waiting"],rL=["timeupdate","progress","loadeddata","playing","seeked"];var $n=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];this.subscription=new T.Subscription;this.representationSubscription=new T.Subscription;this.state$=new Z("none");this.currentVideoRepresentation$=new T.ValueSubject(void 0);this.currentVideoRepresentationInit$=new T.ValueSubject(void 0);this.currentAudioRepresentation$=new T.ValueSubject(void 0);this.currentVideoSegmentLength$=new T.ValueSubject(0);this.currentAudioSegmentLength$=new T.ValueSubject(0);this.error$=new T.Subject;this.manifestRequested=new T.Subject;this.manifestReceived=new T.Subject;this.firstBytesRequested=new T.Subject;this.firstBytesReceived=new T.Subject;this.lastConnectionType$=new T.ValueSubject(void 0);this.lastConnectionReused$=new T.ValueSubject(void 0);this.lastRequestFirstBytes$=new T.ValueSubject(void 0);this.currentLiveTextRepresentation$=new T.ValueSubject(null);this.isLive$=new T.ValueSubject(!1);this.isActiveLive$=new T.ValueSubject(!1);this.isLowLatency$=new T.ValueSubject(!1);this.liveDuration$=new T.ValueSubject(0);this.liveSeekableDuration$=new T.ValueSubject(0);this.liveAvailabilityStartTime$=new T.ValueSubject(0);this.liveStreamStatus$=new T.ValueSubject(void 0);this.bufferLength$=new T.ValueSubject(0);this.liveLatency$=new T.ValueSubject(void 0);this.liveLoadBufferLength$=new T.ValueSubject(0);this.livePositionFromPlayer$=new T.ValueSubject(0);this.currentStallDuration$=new T.ValueSubject(0);this.videoLastDataObtainedTimestamp$=new T.ValueSubject(0);this.fetcherRecoverableError$=new T.Subject;this.fetcherError$=new T.Subject;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new T.Subject;this.gapWatchdogActive=!1;this.destroyController=new ue;this.initManifest=(0,T.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:T.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=(0,T.abortable)(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:T.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=mn(e??"",this.manifestUrlString)}catch(o){let l=hn(e)??{id:"ManifestParsing",category:T.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,p)=>!!(this.element?.canPlayType?.(l)&&Ze()?.isTypeSupported?.(`${l}; codecs="${p}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:d}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";d||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let p=t.streams[o].filter(({mime:c,codecs:h})=>i(o,c,h));r[o]=p;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let c=p.map(({codecs:h})=>h);o==="audio"&&(n=Ln(c),d=n[0]),o==="video"&&(s=kn(c),this.forceVideoCodec&&(0,US.default)(s,this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[o]=p.filter(({codecs:h})=>Sr(h)===d))}else{let c=new Set(p.map(({codecs:h})=>h));d=Rn(c),d&&(r[o]=p.filter(({codecs:h})=>h.startsWith(d)))}if(o==="video"){let c=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);W.display.isHDR&&c&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",(0,T.flattenObject)(u)),u}.bind(this));this.initRepresentations=(0,T.abortable)(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",(0,T.flattenObject)({initialVideo:e,initialAudio:t,sourceHls:i})),(0,T.assertNonNullable)(this.manifest),(0,T.assertNonNullable)(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add((0,T.fromEvent)(c,"error").pipe((0,T.filter)(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=Ks();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ar())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((c,h)=>[...c,...h.representations],[]);if(this.videoBufferManager=new Fa("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],(0,T.isNonNullable)(t)){let c=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Fa("audio",this.source,c,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.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,T.merge)(...rL.map(c=>(0,T.fromEvent)(this.element,c))).pipe((0,T.map)(c=>this.element?Me(this.element.buffered,this.element.currentTime*1e3):0),(0,T.filterChanged)(),(0,T.tap)(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&o()})).subscribe(this.bufferLength$)),this.representationSubscription.add((0,T.merge)((0,T.fromEvent)(this.element,"ended"),this.forceEnded$).subscribe(()=>{o()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe((0,T.filterChanged)()).subscribe(h=>this.liveStreamEndTimestamp=(0,T.now)())),this.subscription.add((0,T.fromEvent)(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=(0,T.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,T.fromEvent)(this.element,"play").subscribe(h=>this.livePauseWatchdogSubscription?.unsubscribe())),this.representationSubscription.add((0,T.combine)({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.map)(({isActiveLive:h,isLowLatency:m})=>h&&m),(0,T.filterChanged)()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||gr(this.element,1)})),this.representationSubscription.add((0,T.combine)({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe((0,T.filter)(({bufferLength:h,isActiveLive:m,isLowLatency:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((0,T.combine)({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe((0,T.filter)(({isLive:h})=>h),(0,T.filterChanged)((h,m)=>m.bufferLength<h.bufferLength),(0,T.map)(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let S=ei(this.manifestUrlString,2);return(h/2+m+b+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add((0,T.combine)({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:h,isActiveLive:m,isLowLatency:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,R=h-S;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(R)>v&&(w=1+Math.sign(R)*I),gr(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let b=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=0;this.representationSubscription.add((0,T.combine)({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe((0,T.throttle)(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(!this.element||this.isUpdatingLive)return;let b=this.element.playbackRate,S=ei(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),R=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,w=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,C=isFinite(h)?h:m,_=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let M="none";if(_?M="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(j=>j.proceedLowLatencyLive()),M="active_low_latency"):S!==0&&C<I?M="live_forward_buffering":C<I+w&&(M="live_with_target_offset"),isFinite(h)&&(c=h>c?h:c),M==="live_forward_buffering"||M==="live_with_target_offset"){let j=c-(I+R),L=this.normolizeLiveOffset(Math.trunc(S+j/b)),te=Math.abs(L-S),F=0;!h||te<=this.tuning.dashCmafLive.offsetCalculationError?F=S:L>0&&te>this.tuning.dashCmafLive.offsetCalculationError&&(F=L),this.manifestUrlString=ye(this.manifestUrlString,F,2)}(M==="live_with_target_offset"||M==="live_forward_buffering")&&(c=0,await this.updateLive())},h=>{this.error$.next({id:"updateLive",category:T.ErrorCategory.VIDEO_PIPELINE,thrown:h,message:"Failed to update live with subscription"})}))}let l=(0,T.merge)(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe((0,T.map)(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),p=(0,T.merge)(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe((0,T.map)(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),d=(0,T.combine)({allBuffersFull:l,someBufferEnded:p}).pipe((0,T.filterChanged)(),(0,T.map)(({allBuffersFull:c,someBufferEnded:h})=>c&&h),(0,T.filter)(c=>c));if(this.representationSubscription.add((0,T.merge)(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:T.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add((0,T.merge)(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{c&&(this.timeoutSourceOpenId=setTimeout(()=>{if(this.source?.readyState==="open"){h();return}this.error$.next({id:"OpenOfStream",category:T.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 c=[this.manifest.duration??0,...(0,Bl.default)((0,Bl.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(...c)/1e3}this.audioBufferManager&&(0,T.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,T.interval)(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:T.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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Tn({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()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}async seekLive(e){(0,T.assertNonNullable)(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?(0,T.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,T.assertNonNullable)(this.element),this.state$.setState("running"),this.subscription.add((0,T.merge)(...iL.map(e=>(0,T.fromEvent)(this.element,e)),(0,T.fromEvent)(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:T.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add((0,T.fromEvent)(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add((0,T.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&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,T.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,p=o<s&&r-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&r-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((p||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 c=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(c).catch(h=>{this.error$.next({id:"stallIntervalCallback",category:T.ErrorCategory.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:h})}),i.liveLastOffset=c}else{let c=this.element.currentTime*1e3;this.videoBufferManager?.maintain(c),this.audioBufferManager?.maintain(c),i.position=c}this.tracer.log("stallIntervalCallback",(0,T.flattenObject)(i))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,T.interval)(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:T.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,T.assertNonNullable)(this.element),(0,T.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,T.isNullable)(this.element)||(0,T.isNullable)(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",(0,T.flattenObject)({requestedPosition:e,forcePrecise:t,position:i})))}warmUpMediaSourceIfNeeded(e=this.element?.currentTime){(0,T.isNonNullable)(this.element)&&(0,T.isNonNullable)(this.source)&&(0,T.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}getCodecs(){return this.manifest?.codecs}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,T.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},{usePersistentGaps:r}=this.tuning.dash;this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let s=this.element.currentTime*1e3,n=[],u=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let l of o.gaps)(r&&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.push(1/0):n.push(l.to));if(n.length){let o=Math.max(...n)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i={...i,gapEnds:n,jumpTo:o,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",(0,T.flattenObject)(i)))}}calculateDurationFromSegments(){return Math.max(this.videoBufferManager?.calculateDurationFromSegments()||0,this.audioBufferManager?.calculateDurationFromSegments()||0)}};var Mn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Dn=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 HS=`attribute vec2 a_vertex;
|
|
125
125
|
attribute vec2 a_texel;
|
|
126
126
|
|
|
127
127
|
varying vec2 v_texel;
|
|
@@ -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 vr=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 $n(this.params.fov,this.params.orientation),this.cameraRotationManager=new Mn(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(HS,this.gl.VERTEX_SHADER),i=this.createShader(jS,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/es2024");var Dn="stalls_manager_metrics",Vl="stalls_manager_abr_params",QS="stalls_manager_default_tuning_abr_params",_l=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(Vl):{};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(QS)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(Vl),this.setStoredData(QS,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Dn,"[]");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(Dn,[]),this.setStoredData(Vl,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(Dn,"[]"),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(Dn,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}))}},Cn=_l;var Ge=require("@vkontakte/videoplayer-shared/es2024"),Bn=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 Ri=class{constructor(e){this.subscription=new Y.Subscription;this.videoState=new Z("stopped");this.observableVideo=null;this.droppedFramesManager=new ur;this.stallsManager=new Cn;this.elementSizeManager=new Bn;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,Y.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new vr(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 Ln({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,Y.isNullable)(this.observableVideo)&&(this.observableVideo=Qe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:Y.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,Y.filter)(l=>!!l.length),(0,Y.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,Y.map)(l=>l.to.state!=="none"),(0,Y.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,Y.filter)(Y.isNonNullable),(0,Y.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,Y.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(je(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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),p=this.player.getCodecs();if((0,Y.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of c.audio){h.push(Pl(m));let g=[];for(let v of m.representations){let S=DS(v);g.push(S),this.audioTracksMap.set(S,{stream:m,representation:v})}this.audioStreamsMap.set(m,g)}this.params.output.availableAudioStreams$.next(h)}let d=[];for(let h of c.video){d.push(kl(h));let m=[];for(let g of h.representations){let v=MS({...g,streamId:h.id});v&&(m.push(v),this.videoTracksMap.set(v,{stream:h,representation:g}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(d);for(let h of c.text)for(let m of h.representations){let g=CS(h,m);this.textTracksMap.set(g,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),p?.video&&this.params.output.availableVideoCodecs$.next(p.video),p?.audio&&this.params.output.availableAudioCodecs$.next(p.audio),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,Y.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,Y.fromEvent)(this.video,"progress")).pipe((0,Y.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,WS.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(v=>this.videoTracksMap.get(v)?.representation.id===d.id);(0,Y.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 v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",h.id,v)}},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,Y.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(kl(d));let m=this.player.calculateDurationFromSegments();m&&this.params.output.duration$.next(m/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,Y.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(Pl(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,Y.map)(({to:l})=>l==="ready"),(0,Y.filterChanged)());this.subscription.add((0,Y.merge)(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,Y.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,Y.merge)(u,this.player.state$.stateChangeEnded$,(0,Y.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let o=(0,Y.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,Y.observableFrom)(["init"])).pipe((0,Y.debounce)(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ia:ta,t=this.params.tuning.useNewAutoSelectVideoTrack?on:nn,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:sn,{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=ke(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 v=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(m/Math.min(g,v||1/0),1),A=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),L=[...this.audioStreamsMap.keys()].find(({id:w})=>w===A?.id)??this.audioStreamsMap.keys().next().value,x=0;if(L){if(l&&!n){let w=e(l,h,this.audioStreamsMap.get(L)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,w?.bitrate??-1/0)}if(c){let w=e(c,h,this.audioStreamsMap.get(L)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);x=Math.max(x,w?.bitrate??-1/0)}}let D=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:x,forwardBufferHealth:S,current:c,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),U=n?D??l:l??D,_=L&&t(U,h,this.audioStreamsMap.get(L)??[],{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}),C=this.videoTracksMap.get(U)?.representation,V=_&&this.audioTracksMap.get(_)?.representation;if(C&&V)return[C,V];if(C&&!V&&this.audioTracksMap.size===0)return[C,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){We(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:Y.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),He(this.video),this.tracer.end()}};var Ua=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/es2024");var Ha=class extends Ri{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=BS(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 K=require("@vkontakte/videoplayer-shared/es2024");var rv=H(_e(),1),jl=H(la(),1);var y=require("@vkontakte/videoplayer-shared/es2024");var Nn=H(_e(),1),$i=H(gt(),1),qn=H(la(),1);var tv=H(js(),1);var ui=require("@vkontakte/videoplayer-shared/es2024");var lL=18,GS=!1;try{GS=j.browser.isSafari&&!!j.browser.safariVersion&&j.browser.safariVersion<=lL}catch(a){console.error(a)}var Ol=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)};GS&&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)}}},zS=Ol;var k=require("@vkontakte/videoplayer-shared/es2024");var Fl=H(gt(),1);var Vn=require("@vkontakte/videoplayer-shared/es2024"),YS=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?ii(s):void 0)??(0,Vn.videoSizeToQuality)({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},KS=({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}),JS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Nl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Fl.default)(i.split("."),0),isDefault:r}),ql=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Fl.default)(r.split("."),0)}),Ul=a=>"url"in a,it=a=>a.type==="template";var ZS=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},Li=(a,e)=>{for(let t of a)if(e(t))return t;return null},ev=a=>{let e=!1,t=(0,Vn.throttleFn)(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};var Fn=require("@vkontakte/videoplayer-shared/es2024");var _n=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 On=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Fn.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,Fn.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!z(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=_n(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 ja=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:u,compatibilityMode:o=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new k.ValueSubject(0);this.currentLowLatencySegmentLength$=new k.ValueSubject(0);this.currentSegmentLength$=new k.ValueSubject(0);this.onLastSegment$=new k.ValueSubject(!1);this.fullyBuffered$=new k.ValueSubject(!1);this.playingRepresentation$=new k.ValueSubject(void 0);this.playingRepresentationInit$=new k.ValueSubject(void 0);this.error$=new k.Subject;this.gaps=[];this.subscription=new k.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,k.abortable)(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);(0,k.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 zS(this.sourceBuffer),this.sourceBufferBufferedDiff=new On(this.mediaSource,this.sourceBuffer),this.subscription.add((0,k.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>{this.maintain()})),this.subscription.add((0,k.fromEvent)(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:k.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let u=this.getCurrentPosition();if(!this.sourceBuffer||!u||!z(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,pr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=ke(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,k.assertNonNullable)(i,"No init buffer for starting representation"),(0,k.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,k.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,k.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,k.isNullable)(s)||(0,k.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,k.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!z(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,k.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,k.abortable)(this.destroyAbortController.signal,async function*(e,t=!1){if(!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);(0,k.assertNonNullable)(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if((0,k.isNullable)(s)||(0,k.isNullable)(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),(0,k.assertNonNullable)(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!z(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,k.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,k.abortable)(this.destroyAbortController.signal,async function*(e){let t=(0,qn.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||!it(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,k.assertNonNullable)(r);let s=this.segments.get(i);(0,k.assertNonNullable)(s,"No segments for starting representation");let n=this.initData.get(i);if((0,k.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){!z(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ue,(0,k.abortable)(this.switchAbortController.signal,async function*(i,r=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);(0,k.assertNonNullable)(s,`No such representation ${i}`);let n=this.segments.get(i),u=this.initData.get(i);if((0,k.isNullable)(u)||(0,k.isNullable)(n)?yield this.loadInit(s,"high",!1):u instanceof Promise&&(yield u),n=this.segments.get(i),(0,k.assertNonNullable)(n,"No segments for starting representation"),u=this.initData.get(i),!(!(u instanceof ArrayBuffer)||!this.sourceBuffer||!z(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,k.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,k.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,k.isNullable)(e)||(0,k.isNullable)(this.downloadingRepresentationId)||(0,k.isNullable)(this.playingRepresentationId)||(0,k.isNullable)(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||(0,k.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if((0,k.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);(0,k.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=ke(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=ke(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,Nn.default)(o,r))c="high";else{let p=(0,$i.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&&ke(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,$i.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-ke(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,k.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,qn.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,qn.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!it(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,$i.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,k.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(!it(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 v=h<=i&&m>=i,S=h>i||v||g===0&&i===0,A=Math.min(this.forwardBufferTarget,this.bufferLimit),L=this.preloadOnly&&h<=i+A||r<A&&m-h>=A||m<=i+A;return(d==="none"||d==="partially_ejected"&&S&&L&&this.sourceBuffer&&z(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,m)))&&S&&L});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"){it(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await(0,k.abortable)(u,async function*(){let c=(0,k.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,k.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())it(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,k.abortable)(n,async function*(){let o=(0,k.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,o),(0,k.fromEvent)(window,"online").pipe((0,k.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,k.now)(),this.failedDownloads=0}catch(o){this.abortActiveSegments(e),Dt(o)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(it(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,$i.default)(e,0).byte.from,to:(0,$i.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(u,o)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,k.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:k.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!it(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,k.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:k.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,Nn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!z(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||!z(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),v=o.loadedBytes===d?g:Mt(u.mime).parseFeedableSegmentChunk(g);v?.byteLength&&(l.status="partially_fed",o.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(o.fedBytes+=v.byteLength,o.fedBytes===d&&this.onSegmentFullyAppended(o,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!((0,k.isNullable)(this.sourceBuffer)||!z(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:k.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",Ul(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,tv.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,k.abortable)(this.destroyAbortController.signal,async function*(){let u=(0,k.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&&it(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:k.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||!z(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||(0,k.isNullable)(e))return!1;this.checkEjectedSegments();let r=[],s=0,n=u=>{if(s>=t)return;r.push({...u.time});let o=Ul(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,Nn.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=ZS(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||!z(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||!z(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||!z(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||!z(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,k.isNullable)(e)?0:ke(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!z(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||!z(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:k.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if((0,k.isNullable)(this.sourceBuffer)||!z(this.mediaSource,this.sourceBuffer)||(0,k.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=_n(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:k.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,$i.default)(e,-1)?.time.to:0)||0}};var W=require("@vkontakte/videoplayer-shared/es2024");var Hn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new W.Subject;this.manifestReceived=new W.Subject;this.firstBytesRequested=new W.Subject;this.firstBytesReceived=new W.Subject;this.lastConnectionType$=new W.ValueSubject(void 0);this.lastConnectionReused$=new W.ValueSubject(void 0);this.lastRequestFirstBytes$=new W.ValueSubject(void 0);this.recoverableError$=new W.Subject;this.error$=new W.Subject;this.abortAllController=new ue;this.subscription=new W.SubscriptionRemovable;this.fetchManifest=(0,W.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=Sn(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Un);return r?(t.log("success",(0,W.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,W.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,W.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,W.assertNever)(t)}this.requestQuic&&(c=ni(c));let h=this.abortAllController.signal,m;if(n){let E=new ue;if(m=(0,W.merge)((0,W.fromEvent)(this.abortAllController.signal,"abort"),(0,W.fromEvent)(n,"abort")).subscribe(()=>{try{E.abort()}catch(R){Un(R)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{E.abort()}catch(R){Un(R)}h=E.signal}let g=0,v=(0,W.now)();d.log("startRequest",(0,W.flattenObject)({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:v})),this.firstBytesRequested.next();let S=yield this.doFetch(c,{priority:s,headers:p,signal:h}),A=(0,W.now)();if(!S)return d.error("error",{message:"No response in request"}),d.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(A-v),!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,W.now)(),R={requestStartedAt:v,requestEndedAt:E,duration:E-v};return d.log("endRequest",(0,W.flattenObject)(R)),d.end(),S.arrayBuffer()}let L=S.body;if(u){let E;[L,E]=S.body.tee(),this.throughputEstimator?.trackStream(E,o)}let x=L.getReader(),D,U=parseInt(S.headers.get("content-length")??"",10);Number.isFinite(U)&&(D=U),!D&&i&&(D=i.to-i.from+1);let _=D?new Uint8Array(D):new Uint8Array(0),C=!1,V=E=>{this.unsubscribeAbortSubscription(m),C=!0,Un(E)},w=(0,W.abortable)(h,async function*({done:E,value:R}){if(g===0&&(this.lastRequestFirstBytes$.next((0,W.now)()-v),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(m);return}if(!E&&R){if(l&&D)_.set(R,g),g+=R.byteLength;else{let oe=new Uint8Array(_.length+R.length);oe.set(_),oe.set(R,_.length),_=oe,g+=R.byteLength}r?.(new DataView(_.buffer),g),yield x?.read().then(w,V)}}.bind(this));yield x?.read().then(w,V),this.unsubscribeAbortSubscription(m);let ee=(0,W.now)(),O={failed:C,requestStartedAt:v,requestEndedAt:ee,duration:ee-v};return C?(d.error("endRequest",(0,W.flattenObject)(O)),d.end(),null):(d.log("endRequest",(0,W.flattenObject)(O)),d.end(),_.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,W.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 S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;g=new DataView(S)}let v=t.parseSegments(g,h,m);return{init:h,dataView:new DataView(p),segments:v}}.bind(this));this.fetchTemplateRepresentation=(0,W.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}=gn(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,W.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:W.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:W.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:W.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:W.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:W.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Un=a=>{if(!Dt(a))throw a};var jn=require("@vkontakte/videoplayer-shared/es2024");var Qa=class a{constructor(e,t){this.currentRepresentation$=new jn.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,jn.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&&it(t.segmentReference))}};var pL=["progress","play","seeked","stalled","waiting"],hL=["timeupdate","progress","loadeddata","playing","seeked"];var Qn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];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.manifestRequested=new y.Subject;this.manifestReceived=new y.Subject;this.firstBytesRequested=new y.Subject;this.firstBytesReceived=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(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:y.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=fn(e??"",this.manifestUrlString)}catch(o){let l=pn(e)??{id:"ManifestParsing",category:y.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,c)=>!!(this.element?.canPlayType?.(l)&&Ze()?.isTypeSupported?.(`${l}; codecs="${c}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:p}=t.live,d=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*d),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";p||(h=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let c=t.streams[o].filter(({mime:d,codecs:h})=>i(o,d,h));r[o]=c;let p;if(this.tuning.dash.codecsPrioritizeEnabled){let d=c.map(({codecs:h})=>h);o==="audio"&&(n=Rn(d),p=n[0]),o==="video"&&(s=kn(d),this.forceVideoCodec&&(0,rv.default)(s,this.forceVideoCodec)?p=this.forceVideoCodec:p=s[0]),p&&(r[o]=c.filter(({codecs:h})=>Sr(h)===p))}else{let d=new Set(c.map(({codecs:h})=>h));p=Pn(d),p&&(r[o]=c.filter(({codecs:h})=>h.startsWith(p)))}if(o==="video"){let d=this.tuning.preferHDR,h=r.video.some(g=>g.hdr),m=r.video.some(g=>!g.hdr);j.display.isHDR&&d&&h?r.video=r.video.filter(g=>g.hdr):m&&(r.video=r.video.filter(g=>!g.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",(0,y.flattenObject)(u)),u}.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.representationSubscription=new y.Subscription,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=zs();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ar())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 ja("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 ja("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.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,y.merge)(...hL.map(d=>(0,y.fromEvent)(this.element,d))).pipe((0,y.map)(d=>this.element?ke(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 v=ei(this.manifestUrlString,2);return(h/2+m+g+v)/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 v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,A=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,L=h-v;if(this.isManualDecreasePlaybackInLive())return;let x=1;Math.abs(L)>S&&(x=1+Math.sign(L)*A),gr(this.element,x)})),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(S=>S.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,v=ei(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,A=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),L=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,D=isFinite(h)?h:m,U=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),_=S<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(_);let C="none";if(U?C="active_low_latency":this.isLowLatency$.getValue()&&_?(this.bufferManagers.forEach(V=>V.proceedLowLatencyLive()),C="active_low_latency"):v!==0&&D<A?C="live_forward_buffering":D<A+x&&(C="live_with_target_offset"),isFinite(h)&&(d=h>d?h:d),C==="live_forward_buffering"||C==="live_with_target_offset"){let V=d-(A+L),w=this.normolizeLiveOffset(Math.trunc(v+V/g)),ee=Math.abs(w-v),O=0;!h||ee<=this.tuning.dashCmafLive.offsetCalculationError?O=v:w>0&&ee>this.tuning.dashCmafLive.offsetCalculationError&&(O=w),this.manifestUrlString=ye(this.manifestUrlString,O,2)}(C==="live_with_target_offset"||C==="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,jl.default)((0,jl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),it(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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new Hn({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");let e=(0,y.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,y.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,y.merge)(...pL.map(t=>(0,y.fromEvent)(this.element,t)),(0,y.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:y.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,y.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,y.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,y.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:y.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,y.flattenObject)(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,y.interval)(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:y.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,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}getCodecs(){return this.manifest?.codecs}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(){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,y.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 ze=require("@vkontakte/videoplayer-shared/es2024"),Wn=class{constructor(){this.subscription=new ze.Subscription;this.pipSize$=new ze.ValueSubject(void 0);this.videoSize$=new ze.ValueSubject(void 0);this.elementSize$=new ze.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=ze.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,ze.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,ze.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,ze.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 Mi=class{constructor(e){this.subscription=new K.Subscription;this.videoState=new Z("stopped");this.observableVideo=null;this.droppedFramesManager=new ur;this.stallsManager=new Cn;this.elementSizeManager=new Wn;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,K.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new vr(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,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,K.isNullable)(this.observableVideo)&&(this.observableVideo=Qe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:K.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,K.filter)(p=>!!p.length),(0,K.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,K.map)(p=>p.to.state!=="none"),(0,K.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,K.filter)(K.isNonNullable),(0,K.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,K.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(kt(this.video,t.isLooped,r)),this.subscription.add(je(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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:p})=>{if(p==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams(),h=this.player.getCodecs();if((0,K.assertNonNullable)(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let g=[];for(let v of d.audio){g.push(Nl(v));let S=[];for(let A of v.representations){let L=KS(A);S.push(L),this.audioTracksMap.set(L,{stream:v,representation:A})}this.audioStreamsMap.set(v,S)}this.params.output.availableAudioStreams$.next(g)}let m=[];for(let g of d.video){m.push(ql(g));let v=[];for(let S of g.representations){let A=YS({...S,streamId:g.id});A&&(v.push(A),this.videoTracksMap.set(A,{stream:g,representation:S}))}this.videoStreamsMap.set(g,v)}this.params.output.availableVideoStreams$.next(m);for(let g of d.text)for(let v of g.representations){let S=XS(g,v);this.textTracksMap.set(S,{stream:g,representation:v})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else p==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&&ev(u)||null;this.subscription.add((0,K.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,K.fromEvent)(this.video,"progress")).pipe((0,K.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=Li(this.videoTracksMap.keys(),S=>this.videoTracksMap.get(S)?.representation.id===h.id);(0,K.isNonNullable)(g)&&(this.stallsManager.lastVideoTrackSelected=g);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.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 S=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,S)}},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,K.filterChanged)()).subscribe(p=>{let d=Li(this.videoTracksMap.entries(),([,{representation:S}])=>S.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(ql(m));let v=this.player.calculateDurationFromSegments();v&&this.params.output.duration$.next(v/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,K.filterChanged)()).subscribe(p=>{let d=Li(this.audioTracksMap.entries(),([,{representation:v}])=>v.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(Nl(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,K.map)(({to:p})=>p==="ready"),(0,K.filterChanged)());this.subscription.add((0,K.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,K.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,K.merge)(l,this.player.state$.stateChangeEnded$,(0,K.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let c=(0,K.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,K.observableFrom)(["init"])).pipe((0,K.debounce)(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ia:ta,t=this.params.tuning.useNewAutoSelectVideoTrack?on:nn,i=this.params.tuning.useNewAutoSelectVideoTrack?Rt:sn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=Li(this.videoTracksMap.keys(),C=>C.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=Li(this.videoStreamsMap.keys(),C=>C.id===c.id),d=p&&this.videoStreamsMap.get(p);if(!d)return;let h=ke(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,v=Math.min(h/Math.min(m,g||1/0),1),S=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),A=S?.id&&Li(this.audioStreamsMap.keys(),C=>C.id===S.id)||this.audioStreamsMap.keys().next().value,L=0;if(A){if(o&&!n){let C=e(o,d,this.audioStreamsMap.get(A)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);L=Math.max(L,C?.bitrate??-1/0)}if(l){let C=e(l,d,this.audioStreamsMap.get(A)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);L=Math.max(L,C?.bitrate??-1/0)}}let x=o;(n||!x)&&(x=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:L,forwardBufferHealth:v,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 D=A&&t(x,d,this.audioStreamsMap.get(A)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.stallsManager.abrTuningParams,forwardBufferHealth:v,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),U=this.videoTracksMap.get(x)?.representation,_=D&&this.audioTracksMap.get(D)?.representation;U&&_?(this.selectedRepresentations.video=U,this.selectedRepresentations.audio=_):U&&!_&&this.audioTracksMap.size===0&&(this.selectedRepresentations.video=U,this.selectedRepresentations.audio=null)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){We(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:K.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),He(this.video),this.tracer.end()}};var Wa=class extends Mi{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/es2024");var Ga=class extends Mi{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=JS(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 av="X-Playback-Duration",Ql=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(av)?parseInt(e.headers.get(av),10):void 0};var ie=require("@vkontakte/videoplayer-shared/es2024");var Gl=H(su(),1);var Gn=require("@vkontakte/videoplayer-shared/es2024");var mL=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,Gn.videoSizeToQuality)({width:t,height:i})}return e??null},bL=(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,Gl.default)(u[1].split(",").map(
|
|
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,rt.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:rt.ErrorCategory.WTF,thrown:t,message:e})}};var za=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 Ei;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)=>zn(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 Yn(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=Qe(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(je(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),He(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(),Ql(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();Ql(p).then(d=>{(0,ie.isNullable)(d)||this.maxSeekBackTime$.next(d)})}}).catch(()=>{})}})}playIfAllowed(){We(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/es2024");var Ya=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),this.params.output.manifestRequested$.next(),zn(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.params.output.manifestReceived$.next(),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=Qe(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(kt(this.video,t.isLooped,i)),this.subscription.add(je(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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),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),He(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(){We(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 nv=H(Gi(),1),zl=H(gi(),1),ov=H(gt(),1);var fe=require("@vkontakte/videoplayer-shared/es2024");var Ka=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,nv.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,zl.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=Qe(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(kt(this.video,t.isLooped,i)),this.subscription.add(je(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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),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),He(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(){We(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,zl.default)(this.trackUrls).map(l=>l.track);if(!r||!s||sr(e,n[0].quality,(0,ov.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/es2024");var lv=require("@vkontakte/videoplayer-shared/es2024"),uv=["stun:videostun.mycdn.me:80"],SL=1e3,vL=3,Yl=()=>null,Kn=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=Yl;this.externalStopCallback=Yl;this.externalErrorCallback=Yl;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:uv}]};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:lv.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),SL)}normalizeOptions(e={}){let t={stunServerList:uv,maxRetryNumber:vL,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Xa=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 Kn(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),He(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=Qe(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(je(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(){We(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 yr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};var I=require("@vkontakte/videoplayer-shared/es2024");var Qt=require("@vkontakte/videoplayer-shared/es2024"),cv=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/es2024");function dv(){return new(window.AudioContext||window.webkitAudioContext)}var Tr=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=dv();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 yL={chunkDuration:5e3,maxParallelRequests:5},Ja=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),availableVideoCodecs$:new I.ValueSubject([]),availableAudioStreams$:new I.ValueSubject([]),currentAudioStream$:new I.ValueSubject(void 0),availableAudioTracks$:new I.ValueSubject([]),availableAudioCodecs$: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,manifestRequested$:new I.Subject,manifestReceived$:new I.Subject,firstBytesRequested$:new I.Subject,firstBytesReceived$: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=zu([...FS(this.params.tuning),...OS(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,Kl.default)(r,l)),...t.filter(l=>(0,Kl.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,I.flattenObject)(s)),this.screenFormatsIterator=new yr(s);let n=[...Dl(!0),...Dl(!1)];this.chromecastFormatsIterator=new yr(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&&Tr.isSupported()&&(this.volumeMultiplierManager=new Tr(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new yr(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((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()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let 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 Wa({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new Ua({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),this.params.tuning.useNewDashProvider?new Ga({...u,source:o}):new Ha({...u,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new Ya({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new za({...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 Ka({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new Vb({...u,source:o,config:{...yL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,I.assertNonNullable)(o),new Xa({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 Jr({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,hv.default)((0,pv.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))),cv({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=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,d=l&&!o&&(u&&t||!c);n={...n,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):p?this.switchToNextVideoCodec():(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 X=require("@vkontakte/videoplayer-shared/es2024");var TL=5e3,fv="one_video_throughput",mv="one_video_rtt",Za=window.navigator.connection,bv=()=>{let a=Za?.downlink;if((0,X.isNonNullable)(a)&&a!==10)return a*1e3},gv=()=>{let a=Za?.rtt;if((0,X.isNonNullable)(a)&&a!==3e3)return a},Sv=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Xl=class a{constructor(e){this.subscription=new X.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(fv)||(e.useBrowserEstimation?bv():void 0)||TL,i=a.load(mv)??(e.useBrowserEstimation?gv():void 0)??0;if(this.throughput$=new X.ValueSubject(t),this.rtt$=new X.ValueSubject(i),this.rttAdjustedThroughput$=new X.ValueSubject(Sv(t,i,e.rttPenaltyRequestSize)),this.throughput=jt.getSmoothedValue(t,-1,e),this.rtt=jt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=bv();n&&this.throughput.next(n);let u=gv();(0,X.isNonNullable)(u)&&this.rtt.next(u)};Za&&"onchange"in Za&&this.subscription.add((0,X.fromEvent)(Za,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{X.safeStorage.set(fv,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{X.safeStorage.set(mv,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,X.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,X.map)(({throughput:r,rtt:s})=>Sv(r,s,e.rttPenaltyRequestSize)),(0,X.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,X.now)(),r=new X.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,X.fromEvent)(e,"progress").pipe((0,X.once)()).subscribe(s=>{t=s.loaded,i=(0,X.now)()}));break;case 1:case 0:r.add((0,X.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,X.now)()}));break}r.add((0,X.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,u=(0,X.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,X.now)(),n=0,u=(0,X.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,X.now)()-s,1),this.concurrentDownloads.delete(e);else if(p){if(t){let d=(0,X.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,X.now)()}else n+=p.byteLength;u=(0,X.now)()}else r+=p.byteLength,n+=p.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,X.now)()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,X.now)()-u,this.concurrentDownloads.size),n=0,u=(0,X.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=X.safeStorage.get(e);if((0,X.isNonNullable)(t))return parseInt(t,10)??void 0}},vv=Xl;var Di=require("@vkontakte/videoplayer-shared/es2024"),yv={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:Di.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Di.VideoQuality.Q_720P,trafficSavingLimit:Di.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:Di.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,codecsPrioritizeEnabled:!1},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",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,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,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},Tv=a=>({...(0,Di.fillWithDefault)(a,yv),configName:[...a.configName??[],...yv.configName]});var f=require("@vkontakte/videoplayer-shared/es2024");var Wt=require("@vkontakte/videoplayer-shared/es2024"),Jl=({seekState:a,position$:e})=>(0,Wt.merge)(a.stateChangeEnded$.pipe((0,Wt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,Wt.filter)(Wt.isNonNullable)),e.pipe((0,Wt.filter)(()=>a.getState().state==="none")));var Iv=require("@vkontakte/videoplayer-shared/es2024"),Ev=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,Iv.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Xn=require("@vkontakte/videoplayer-shared/es2024"),xv=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,Xn.filter)(r=>r.length>0),(0,Xn.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var es=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,manifestRequested$:new f.Subject,manifestReceived$:new f.Subject,firstBytesRequested$:new f.Subject,firstBytesReceived$: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:vb,getCurrentTime$:new f.ValueSubject(null)};if(this.initLogs(),this.tuning=Tv(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,Zl.default)(this.info).forEach(i=>i.setSuppressErrors(!0)),(0,Zl.default)(this.events).forEach(i=>i.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new vs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new vv(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,wv.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=Ev(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ja({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(()=>{xv(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(al(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:Jl({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(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.manifestRequested$.pipe((0,f.once)()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe((0,f.once)()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe((0,f.once)()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe((0,f.once)()).subscribe(this.events.firstBytesReceived$)).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),Sb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>gb(t)),this.providerContainer.current$.subscribe(({type:t})=>ea("provider",t)),e.duration$.subscribe(t=>ea("duration",t)),e.availableVideoTracks$.pipe((0,f.filter)(t=>!!t.length),(0,f.once)()).subscribe(t=>ea("tracks",t)),this.events.fatalError$.subscribe(new Oe("fatalError")),this.events.managedError$.subscribe(new Oe("managedError")),e.position$.subscribe(new Oe("position")),e.currentVideoTrack$.pipe((0,f.map)(t=>t?.quality)).subscribe(new Oe("quality")),this.info.currentBuffer$.subscribe(new Oe("buffer")),e.isBuffering$.subscribe(new Oe("isBuffering"))].forEach(t=>this.subscription.add(t)),ea("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&&!na()}};var Ct=require("@vkontakte/videoplayer-shared/es2024"),IL=`@vkontakte/videoplayer-core@${eo}`;
|
|
178
|
+
`;var vr=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 Mn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Dn(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(HS,this.gl.VERTEX_SHADER),i=this.createShader(jS,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,p=t+r,d=e-i,c=t+r;return[s,n,u,o,l,p,d,c]}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/es2024");var Cn="stalls_manager_metrics",Vl="stalls_manager_abr_params",QS="stalls_manager_default_tuning_abr_params",_l=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(Vl):{};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(QS)},{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}={...this.abrParams};this.tuning.enabled&&e===r&&t===s&&i===n||(this.removeStoredData(Vl),this.setStoredData(QS,{bitrateFactorAtEmptyBuffer:r,bitrateFactorAtFullBuffer:s,containerSizeFactor:n}))}updateStoredAbrParams(){let e=[],t=this.getStoredData(Cn,"[]");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(Cn,[]),this.setStoredData(Vl,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),p=this.abrTuningParams;return e<i-r?p={bitrateFactorAtEmptyBuffer:Math.max(p.bitrateFactorAtEmptyBuffer-l,this.abrParams.minBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(p.bitrateFactorAtFullBuffer-l,this.abrParams.minBitrateFactorAtFullBuffer),containerSizeFactor:Math.min(p.containerSizeFactor+l,this.abrParams.maxContainerSizeFactor)}:e>i+r&&(p={bitrateFactorAtEmptyBuffer:Math.min(p.bitrateFactorAtEmptyBuffer+l,this.abrParams.maxBitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.min(p.bitrateFactorAtFullBuffer+l,this.abrParams.maxBitrateFactorAtFullBuffer),containerSizeFactor:Math.max(p.containerSizeFactor-l,this.abrParams.minContainerSizeFactor)}),e>s&&(p={bitrateFactorAtEmptyBuffer:Math.max(p.bitrateFactorAtEmptyBuffer,this.abrParams.bitrateFactorAtEmptyBuffer),bitrateFactorAtFullBuffer:Math.max(p.bitrateFactorAtFullBuffer,this.abrParams.bitrateFactorAtFullBuffer),containerSizeFactor:Math.min(p.containerSizeFactor,this.abrParams.containerSizeFactor)}),p}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(Cn,"[]"),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(Cn,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(),p=(0,he.now)(),d=r&&this.currentStallsCount>=r,c=i&&p-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&p-l>=i+u&&t>=i;(d||c)&&(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}))}},Bn=_l;var Ge=require("@vkontakte/videoplayer-shared/es2024"),Vn=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 V.Subscription;this.videoState=new Z("stopped");this.observableVideo=null;this.droppedFramesManager=new ur;this.stallsManager=new Bn;this.elementSizeManager=new Vn;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.unmuteAfterBrowserResetsHappened=new V.ValueSubject(!1);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,V.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new vr(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=He(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($e(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 $n({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,V.isNullable)(this.observableVideo)&&(this.observableVideo=Qe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:V.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,V.filter)(d=>!!d.length),(0,V.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,V.map)(d=>d.to.state!=="none"),(0,V.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,V.filter)(V.isNonNullable),(0,V.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,V.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(Rt(this.video,t.isLooped,r)),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(t.volume.stateChangeStarted$.pipe((0,V.map)(()=>{let d=t.volume.getTransition(),c=this.params.output.element$.getValue();return!c||!d?!1:!d.to.muted&&c.muted}),(0,V.filter)(d=>!!d),(0,V.once)()).subscribe(()=>{this.unmuteAfterBrowserResetsHappened.next(!0)})),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.playbackRateState$.pipe((0,V.filter)(()=>this.unmuteAfterBrowserResetsHappened.getValue()),(0,V.once)()).subscribe(()=>{let d=this.params.output.element$.getValue(),c=t.playbackRate.getState();d&&c!==d.playbackRate&&(d.playbackRate=c)})),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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),h=this.player.getCodecs();if((0,V.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of c.audio){b.push(Pl(S));let v=[];for(let I of S.representations){let R=DS(I);v.push(R),this.audioTracksMap.set(R,{stream:S,representation:I})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of c.video){m.push(Rl(b));let S=[];for(let v of b.representations){let I=Oa({...v,streamId:b.id});I&&(S.push(I),this.videoTracksMap.set(I,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of c.text)for(let S of b.representations){let v=CS(b,S);this.textTracksMap.set(v,{stream:b,representation:S})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let u=(0,V.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,V.fromEvent)(this.video,"progress")).pipe((0,V.filter)(()=>this.videoTracksMap.size>0)),{abrThrottle:o}=this.params.tuning.dash;o&&(u=u.pipe((0,V.throttle)(o))),this.subscription.add(u.subscribe(async()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[m,b]=h,S=[...this.videoTracksMap.keys()].find(I=>this.videoTracksMap.get(I)?.representation.id===m.id);(0,V.isNonNullable)(S)&&(this.stallsManager.lastVideoTrackSelected=S);let v=this.params.desiredState.autoVideoTrackLimits.getTransition();if(v&&this.params.output.autoVideoTrackLimits$.next(v.to),d==="manifest_ready")await this.player.initRepresentations(m.id,b?.id,this.params.sourceHls);else if(await this.player.switchRepresentation("video",m.id),b){let I=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",b.id,I)}},r)),this.subscription.add((0,V.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,V.merge)((0,V.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,V.map)(d=>d.to)))}).pipe((0,V.map)(({videoState:d,autoVideoTrackState:c})=>d.to!=="stopped"&&c),(0,V.filterChanged)()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),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,V.filterChanged)()).subscribe(d=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:v}])=>v.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=c,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Rl(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,V.filterChanged)()).subscribe(d=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:S}])=>S.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=c,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Pl(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(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 l=t.playbackState.stateChangeStarted$.pipe((0,V.map)(({to:d})=>d==="ready"),(0,V.filterChanged)());this.subscription.add((0,V.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,V.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,V.merge)(l,this.player.state$.stateChangeEnded$,(0,V.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=(0,V.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,V.observableFrom)(["init"])).pipe((0,V.debounce)(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ia:ta,t=this.params.tuning.useNewAutoSelectVideoTrack?un:on,i=this.params.tuning.useNewAutoSelectVideoTrack?kt:nn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=[...this.videoTracksMap.keys()].find(({id:M})=>M===u),l=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let d=[...this.videoStreamsMap.keys()].find(({id:M})=>M===p.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let h=Me(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),I=[...this.audioStreamsMap.keys()].find(({id:M})=>M===v?.id)??this.audioStreamsMap.keys().next().value,R=0;if(I){if(o&&!n){let M=e(o,c,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);R=Math.max(R,M?.bitrate??-1/0)}if(l){let M=e(l,c,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);R=Math.max(R,M?.bitrate??-1/0)}}let w=o;(n||!w)&&(w=i(c,{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:R,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=I&&t(w,c,this.audioStreamsMap.get(I)??[],{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}),_=this.videoTracksMap.get(w)?.representation,O=C&&this.audioTracksMap.get(C)?.representation;if(_&&O)return[_,O];if(_&&!O&&this.audioTracksMap.size===0)return[_,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){We(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:V.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),je(this.video),this.tracer.end()}};var Ha=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 ce=require("@vkontakte/videoplayer-shared/es2024");var ja=class extends ki{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(),p=i.volume$.getValue(),d=!p.volume||p.muted;!o&&!l&&d?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 p=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-c||this.video.paused||(0,ce.isNullable)(p)||(t=o-p)})).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:p})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&p>=1-c||(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=BS(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 H=require("@vkontakte/videoplayer-shared/es2024");var tv=Q(Ue(),1),jl=Q(la(),1);var y=require("@vkontakte/videoplayer-shared/es2024");var qn=Q(Ue(),1),$i=Q(gt(),1),Un=Q(la(),1);var ZS=Q(Ws(),1);var ui=require("@vkontakte/videoplayer-shared/es2024");var oL=18,WS=!1;try{WS=W.browser.isSafari&&!!W.browser.safariVersion&&W.browser.safariVersion<=oL}catch(a){console.error(a)}var Ol=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)};WS&&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)}}},GS=Ol;var P=require("@vkontakte/videoplayer-shared/es2024");var Fl=Q(gt(),1);var _n=require("@vkontakte/videoplayer-shared/es2024"),Qa=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{let u=(s?ii(s):void 0)??(0,_n.videoSizeToQuality)({width:e,height:t});return u&&{id:a,quality:u,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},zS=({id:a,bitrate:e})=>({id:a,bitrate:e}),YS=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),KS=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Nl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Fl.default)(i.split("."),0),isDefault:r}),ql=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Fl.default)(r.split("."),0)}),Ul=a=>"url"in a,it=a=>a.type==="template";var XS=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},Li=(a,e)=>{for(let t of a)if(e(t))return t;return null},JS=a=>{let e=!1,t=(0,_n.throttleFn)(()=>{e=!0},a);return()=>{try{return t(),e}finally{e=!1}}};var Nn=require("@vkontakte/videoplayer-shared/es2024");var On=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 Fn=class{constructor(e,t){this.lastUpdateTs=0;this.lastCallTs=0;this.prevRanges=[];this.subscription=new Nn.Subscription;this.mediaSource=e,this.sourceBuffer=t,this.subscription.add((0,Nn.fromEvent)(this.sourceBuffer,"updateend").subscribe(()=>this.updateend()))}updateend(){if(!K(this.mediaSource,this.sourceBuffer))return;let{prevRanges:e}=this,t=On(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 Wa=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.useSmartRepresentationSwitch=!1;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.sourceBufferBufferedDiff=null;this.startWith=(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 GS(this.sourceBuffer),this.sourceBufferBufferedDiff=new Fn(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||!K(this.mediaSource,this.sourceBuffer))return;let o=Math.min(this.bufferLimit,pr(this.sourceBuffer.buffered)*.8);this.bufferLimit=o;let l=Me(this.sourceBuffer.buffered,u),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(u,n*2,l<p).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,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(!K(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||!K(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(!K(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||!K(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,Un.default)(e,o=>o.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let o of this.representations.keys()){let l=t.find(c=>c.id===o);l&&this.representations.set(o,l);let p=this.representations.get(o);if(!p||!it(p.segmentReference))return;let d=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,d)}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(p=>[p.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(p=>[p.id,p])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!K(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||!K(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)||!K(this.mediaSource,this.sourceBuffer)||(0,P.isNonNullable)(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.representations.get(this.playingRepresentationId),r=this.segments.get(this.downloadingRepresentationId),s=this.segments.get(this.playingRepresentationId);if((0,P.assertNonNullable)(t,`No such representation ${this.downloadingRepresentationId}`),(0,P.assertNonNullable)(i,`No such representation ${this.playingRepresentationId}`),(0,P.isNullable)(r)||(0,P.isNullable)(s))return;let n=r.find(c=>e>=c.time.from&&e<c.time.to);(0,P.isNonNullable)(n)&&isFinite(n.time.from)&&isFinite(n.time.to)&&this.currentSegmentLength$.next(n?.time.to-n.time.from);let u=e,o=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),h=Qa(i),m=Qa(t),b=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useSmartRepresentationSwitch&&(0,P.isNonNullable)(h)&&(0,P.isNonNullable)(m)&&(0,P.isHigher)(h.quality,m.quality),S=this.useSmartRepresentationSwitch&&this.tuning.dash.useNewRepresentationSwitch&&this.tuning.dash.useDelayedRepresentationSwitch;if(b||S?u+=Math.min(c,this.tuning.dash.representationSwitchForwardBufferGap):n&&n.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=n.time.to-e+o&&(u=n?n.time.to+o:-1/0),this.tuning.dash.useNewRepresentationSwitch){let I=[...this.segments.entries()].map(([R,w])=>{let C=w.find(_=>e>=_.time.from&&e<_.time.to);return{representationId:R,status:C?.status}}).find(R=>R.status==="fed")?.representationId;if(!I)return;this.playingRepresentationId=I,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId))}}if(isFinite(this.bufferLimit)&&pr(this.sourceBuffer.buffered)>=this.bufferLimit){let c=Me(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<h).catch(m=>{this.handleAsyncError(m,"pruneBuffer")});return}let p=null;if(!this.activeSegments.size&&(p=this.selectForwardBufferSegments(r,t.segmentReference.type,u),p?.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&n)if((0,qn.default)(p,n))c="high";else{let h=(0,$i.default)(p,0);h&&h.time.from-n.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(p,t,c).catch(h=>{this.handleAsyncError(h,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&n&&n.status==="fed"&&!p?.length&&Me(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let d=(0,$i.default)(r,-1);!this.isLive&&d&&(this.fullyBuffered$.next(d.time.to-e-Me(this.sourceBuffer.buffered,e)<o),this.onLastSegment$.next(e-d.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,Un.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,Un.default)(e?.streams[this.kind],i=>i.representations)??[];if(![...this.segments.values()].every(i=>!i.length))for(let i of t){if(!i||!it(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,$i.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)}}setSmartRepresentationSwitch(e){this.useSmartRepresentationSwitch=e}updateLowLatencyLiveIfNeeded(e){let t=0;for(let i of this.representations.values()){let r=i.segmentReference;if(!it(r))return;let 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:c,time:{from:h,to:m}},b)=>{let S=h<=i&&m>=i,v=h>i||S||b===0&&i===0,I=Math.min(this.forwardBufferTarget,this.bufferLimit),R=this.preloadOnly&&h<=i+I||r<I&&m-h>=I||m<=i+I;return(c==="none"||c==="partially_ejected"&&v&&R&&this.sourceBuffer&&K(this.mediaSource,this.sourceBuffer)&&!(De(this.sourceBuffer.buffered,h)&&De(this.sourceBuffer.buffered,m)))&&v&&R});if(s===-1)return null;if(t!=="byteRange")return e.slice(s,s+1);let n=e,u=0,o=0,l=[],p=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=s;c<n.length&&(u<=p||o<=d);c++){let h=n[c];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"){it(t.segmentReference)?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:u,onProgress:o,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&u&&(await(0,P.abortable)(u,async function*(){let p=(0,P.getExponentialDelay)(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,p))}.bind(this))(),u.aborted&&this.abortActiveSegments([e]));try{let p=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)(),!p)return;let d=new DataView(p),c=Mt(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=c.getChunkEndTime(d,b)}o&&r.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,u);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=c.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(p){this.abortActiveSegments([e]),Dt(p)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())it(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let 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(it(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,$i.default)(e,0).byte.from,to:(0,$i.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:async(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(!it(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,p)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=(0,P.now)();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:p,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:P.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:o,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,qn.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!K(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),p=Mt(n.mime).parseFeedableSegmentChunk(l,this.isLive);p?.byteLength&&(o.status="partially_fed",u.feedingBytes+=p.byteLength,await this.sourceBufferTaskQueue.append(p),u.fedBytes+=p.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!K(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,p=l.byte.from-i,d=l.byte.to-i,c=d-p+1,h=p<r,m=d<=r;if(h){if(l.status==="downloading"&&m){l.status="downloaded";let b=new DataView(e.buffer,e.byteOffset+p,c);await this.sourceBufferTaskQueue.append(b,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(c,r-p),o.loadedBytes>o.feedingBytes)){let b=new DataView(e.buffer,e.byteOffset+p+o.feedingBytes,o.loadedBytes-o.feedingBytes),S=o.loadedBytes===c?b:Mt(u.mime).parseFeedableSegmentChunk(b);S?.byteLength&&(l.status="partially_fed",o.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(o.fedBytes+=S.byteLength,o.fedBytes===c&&this.onSegmentFullyAppended(o,t)):await n())}}}}onSegmentFullyAppended(e,t){if(!((0,P.isNullable)(this.sourceBuffer)||!K(this.mediaSource,this.sourceBuffer))){!this.isLive&&W.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",Ul(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,ZS.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:p}=u,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let c=p;this.isLive&&it(e.segmentReference)&&(c=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,c),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||!K(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=Ul(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,p=o.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||p)&&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,p=0;for(let d of this.segments.values())for(let c of d)(0,qn.default)(["none","partially_ejected"],c.status)&&Math.round(c.time.from)<=Math.round(o)&&Math.round(c.time.to)>=Math.round(l)&&p++;if(p===this.segments.size){let d={time:{from:o,to:l},url:"",status:"none"};n(d)}}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=XS(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||!K(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||!K(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||!K(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||!K(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||(0,P.isNullable)(e)?0:Me(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!this.sourceBuffer||!K(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer,r={representation:e,from:t.time.from,to:t.time.to,persistent:!1};for(let 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||!K(this.mediaSource,this.sourceBuffer))return;let{buffered:i}=this.sourceBuffer;this.gaps=this.gaps.filter(r=>{if(r.persistent)return!0;let s=Math.round(r.from),n=Math.round(r.to);for(let u=0;u<i.length;u++)if(s>=Math.round(i.start(u)*1e3)&&n<=Math.round(i.end(u)*1e3))return!1;return!0}),this.gapDetectionIdleCallback=dr(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:P.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}checkEjectedSegments(){if((0,P.isNullable)(this.sourceBuffer)||!K(this.mediaSource,this.sourceBuffer)||(0,P.isNullable)(this.playingRepresentationId)||this.sourceBufferBufferedDiff&&!this.sourceBufferBufferedDiff.wasUpdated())return;let e=On(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 p=0;p<e.length;p+=2){let d=e[p],c=e[p+1];o||(o=d-t<=n&&c+t>=u),(n>=d&&n<c-t||u>d+t&&u<=c)&&(l+=1)}o||(l===1?r.status="partially_ejected":this.gaps.some(p=>p.from===r.time.from||p.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category: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,$i.default)(e,-1)?.time.to:0)||0}};var z=require("@vkontakte/videoplayer-shared/es2024");var jn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.manifestRequested=new z.Subject;this.manifestReceived=new z.Subject;this.firstBytesRequested=new z.Subject;this.firstBytesReceived=new z.Subject;this.lastConnectionType$=new z.ValueSubject(void 0);this.lastConnectionReused$=new z.ValueSubject(void 0);this.lastRequestFirstBytes$=new z.ValueSubject(void 0);this.recoverableError$=new z.Subject;this.error$=new z.Subject;this.abortAllController=new ue;this.subscription=new z.SubscriptionRemovable;this.fetchManifest=(0,z.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=vn(i)),this.manifestRequested.next();let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Hn);return r?(t.log("success",(0,z.flattenObject)({url:i,message:"Request successfully executed"})),t.end(),this.manifestReceived.next(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",(0,z.flattenObject)({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=(0,z.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 p=e,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let x=new URL(p,location.href);x.searchParams.append("bytes",`${i.from}-${i.to}`),p=x.toString();break}default:(0,z.assertNever)(t)}this.requestQuic&&(p=ni(p));let h=this.abortAllController.signal,m;if(n){let x=new ue;if(m=(0,z.merge)((0,z.fromEvent)(this.abortAllController.signal,"abort"),(0,z.fromEvent)(n,"abort")).subscribe(()=>{try{x.abort()}catch(k){Hn(k)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{x.abort()}catch(k){Hn(k)}h=x.signal}let b=0,S=(0,z.now)();c.log("startRequest",(0,z.flattenObject)({url:p,priority:s,rangeMethod:t,range:i,isLowLatency:o,requestStartedAt:S})),this.firstBytesRequested.next();let v=yield this.doFetch(p,{priority:s,headers:d,signal:h}),I=(0,z.now)();if(!v)return c.error("error",{message:"No response in request"}),c.end(),this.unsubscribeAbortSubscription(m),null;if(this.throughputEstimator?.addRawRtt(I-S),!v.ok||!v.body){this.unsubscribeAbortSubscription(m);let x=`Fetch error ${v.status}: ${v.statusText}`;return c.error("error",{message:x}),c.end(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`))}if(this.onHeadersReceived(v.headers),!r&&!u){this.unsubscribeAbortSubscription(m);let x=(0,z.now)(),k={requestStartedAt:S,requestEndedAt:x,duration:x-S};return c.log("endRequest",(0,z.flattenObject)(k)),c.end(),v.arrayBuffer()}let R=v.body;if(u){let x;[R,x]=v.body.tee(),this.throughputEstimator?.trackStream(x,o)}let w=R.getReader(),C,_=parseInt(v.headers.get("content-length")??"",10);Number.isFinite(_)&&(C=_),!C&&i&&(C=i.to-i.from+1);let O=C?new Uint8Array(C):new Uint8Array(0),M=!1,j=x=>{this.unsubscribeAbortSubscription(m),M=!0,Hn(x)},L=(0,z.abortable)(h,async function*({done:x,value:k}){if(b===0&&(this.lastRequestFirstBytes$.next((0,z.now)()-S),this.firstBytesReceived.next()),h.aborted){this.unsubscribeAbortSubscription(m);return}if(!x&&k){if(l&&C)O.set(k,b),b+=k.byteLength;else{let oe=new Uint8Array(O.length+k.length);oe.set(O),oe.set(k,O.length),O=oe,b+=k.byteLength}r?.(new DataView(O.buffer),b),yield w?.read().then(L,j)}}.bind(this));yield w?.read().then(L,j),this.unsubscribeAbortSubscription(m);let te=(0,z.now)(),F={failed:M,requestStartedAt:S,requestEndedAt:te,duration:te-S};return M?(c.error("endRequest",(0,z.flattenObject)(F)),c.end(),null):(c.log("endRequest",(0,z.flattenObject)(F)),c.end(),O.buffer)}.bind(this));this.fetchByteRangeRepresentation=(0,z.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,p;e.indexRange&&(l=e.indexRange.from,p=e.indexRange.to,o=s+1===l,o&&(n=Math.min(l,r),u=Math.max(p,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:u},priority:i,measureThroughput:!1});if(!d)return null;let c=new DataView(d,r-n,s-n+1);if(!t.validateData(c))throw new Error("Invalid media file");let h=t.parseInit(c),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(o)b=new DataView(d,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=(0,z.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}=Sn(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,z.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:z.ErrorCategory.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:z.ErrorCategory.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:z.ErrorCategory.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:z.ErrorCategory.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:z.ErrorCategory.FATAL})}}unsubscribeAbortSubscription(e){e&&(e.unsubscribe(),this.subscription.remove(e))}},Hn=a=>{if(!Dt(a))throw a};var Qn=require("@vkontakte/videoplayer-shared/es2024");var Ga=class a{constructor(e,t){this.currentRepresentation$=new Qn.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,Qn.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&&it(t.segmentReference))}};var cL=["progress","play","seeked","stalled","waiting"],dL=["timeupdate","progress","loadeddata","playing","seeked"];var Wn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.bufferManagers=[];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.manifestRequested=new y.Subject;this.manifestReceived=new y.Subject;this.firstBytesRequested=new y.Subject;this.firstBytesReceived=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(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:y.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!e)return null;let t=null;try{t=mn(e??"",this.manifestUrlString)}catch(o){let l=hn(e)??{id:"ManifestParsing",category:y.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o};this.error$.next(l)}if(!t)return null;let i=(o,l,p)=>!!(this.element?.canPlayType?.(l)&&Ze()?.isTypeSupported?.(`${l}; codecs="${p}"`)||o==="text");if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:o,latestSegmentPublishTime:l,streamIsUnpublished:p,streamIsAlive:d}=t.live,c=(t.duration??0)/1e3;this.liveSeekableDuration$.next(-1*c),this.liveDuration$.next((l-o)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let h="active";d||(h=p?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(h)}let r={text:t.streams.text,video:[],audio:[]},s,n;for(let o of["video","audio"]){let p=t.streams[o].filter(({mime:c,codecs:h})=>i(o,c,h));r[o]=p;let d;if(this.tuning.dash.codecsPrioritizeEnabled){let c=p.map(({codecs:h})=>h);o==="audio"&&(n=Ln(c),d=n[0]),o==="video"&&(s=kn(c),this.forceVideoCodec&&(0,tv.default)(s,this.forceVideoCodec)?d=this.forceVideoCodec:d=s[0]),d&&(r[o]=p.filter(({codecs:h})=>Sr(h)===d))}else{let c=new Set(p.map(({codecs:h})=>h));d=Rn(c),d&&(r[o]=p.filter(({codecs:h})=>h.startsWith(d)))}if(o==="video"){let c=this.tuning.preferHDR,h=r.video.some(b=>b.hdr),m=r.video.some(b=>!b.hdr);W.display.isHDR&&c&&h?r.video=r.video.filter(b=>b.hdr):m&&(r.video=r.video.filter(b=>!b.hdr))}}let u={...t,streams:r};return this.tuning.dash.codecsPrioritizeEnabled&&(u.codecs={video:s,audio:n}),this.tracer.log("updateManifestEnd",(0,y.flattenObject)(u)),u}.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.representationSubscription=new y.Subscription,this.state$.startTransitionTo("representations_ready");let r=c=>{this.representationSubscription.add((0,y.fromEvent)(c,"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=Ks();let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),ar())if(i){let c=document.createElement("source");r(c),c.type="application/x-mpegurl",c.src=i.url,this.element.appendChild(c)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},u=this.manifest.streams.video.reduce((c,h)=>[...c,...h.representations],[]);if(this.videoBufferManager=new Wa("video",this.source,u,n),this.bufferManagers=[this.videoBufferManager],(0,y.isNonNullable)(t)){let c=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Wa("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}Ga.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ga(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.manifestRequested.subscribe(this.manifestRequested)),this.representationSubscription.add(this.fetcher.manifestReceived.subscribe(this.manifestReceived)),this.representationSubscription.add(this.fetcher.firstBytesRequested.subscribe(this.firstBytesRequested)),this.representationSubscription.add(this.fetcher.firstBytesReceived.subscribe(this.firstBytesReceived)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));let o=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add((0,y.merge)(...dL.map(c=>(0,y.fromEvent)(this.element,c))).pipe((0,y.map)(c=>this.element?Me(this.element.buffered,this.element.currentTime*1e3):0),(0,y.filterChanged)(),(0,y.tap)(c=>{c>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:b})=>m&&b&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(h=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!h)return;let m=this.liveSeekableDuration$.getValue()-h/1e3;this.liveSeekableDuration$.next(Math.max(m,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+h/1e3)})),this.representationSubscription.add((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:b})=>{let S=ei(this.manifestUrlString,2);return(h/2+m+b+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:b})=>{if(!b||!m)return;let S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,v=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,I=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,R=h-S;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(R)>v&&(w=1+Math.sign(R)*I),gr(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let m=0;if(h){let b=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=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 b=this.element.playbackRate,S=ei(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),R=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,w=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,C=isFinite(h)?h:m,_=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),O=v<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(O);let M="none";if(_?M="active_low_latency":this.isLowLatency$.getValue()&&O?(this.bufferManagers.forEach(j=>j.proceedLowLatencyLive()),M="active_low_latency"):S!==0&&C<I?M="live_forward_buffering":C<I+w&&(M="live_with_target_offset"),isFinite(h)&&(c=h>c?h:c),M==="live_forward_buffering"||M==="live_with_target_offset"){let j=c-(I+R),L=this.normolizeLiveOffset(Math.trunc(S+j/b)),te=Math.abs(L-S),F=0;!h||te<=this.tuning.dashCmafLive.offsetCalculationError?F=S:L>0&&te>this.tuning.dashCmafLive.offsetCalculationError&&(F=L),this.manifestUrlString=ye(this.manifestUrlString,F,2)}(M==="live_with_target_offset"||M==="live_forward_buffering")&&(c=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(c=>c.fullyBuffered$)).pipe((0,y.map)(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),p=(0,y.merge)(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe((0,y.map)(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue()))),d=(0,y.combine)({allBuffersFull:l,someBufferEnded:p}).pipe((0,y.filterChanged)(),(0,y.map)(({allBuffersFull:c,someBufferEnded:h})=>c&&h),(0,y.filter)(c=>c));if(this.representationSubscription.add((0,y.merge)(this.forceEnded$,d).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:y.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add((0,y.merge)(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"){let c=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise(h=>{c&&(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 c=[this.manifest.duration??0,...(0,jl.default)((0,jl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),it(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/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.forceVideoCodec=e.forceVideoCodec,this.fetcher=new jn({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()}setSmartRepresentationSwitch(e){this.bufferManagers.forEach(t=>t.setSmartRepresentationSwitch(e))}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");let e=(0,y.fromEvent)(this.element,"timeupdate");this.tuning.dash.timeupdateEventTickThrottle&&(e=e.pipe((0,y.throttle)(this.tuning.dash.timeupdateEventTickThrottle))),this.subscription.add((0,y.merge)(...cL.map(t=>(0,y.fromEvent)(this.element,t)),(0,y.fromEvent)(window,"online"),e).subscribe(()=>this.tick(),t=>{this.error$.next({id:"DashVKPlayer",category:y.ErrorCategory.WTF,message:"Internal logic error",thrown:t})})),this.subscription.add((0,y.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,y.fromEvent)(this.element,"waiting").subscribe(()=>{this.tuning.dash.useVideoElementWaitingCurrentTimeReassign&&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,y.now)(),n=100,u=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(u);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,l=this.videoBufferManager?.getForwardBufferDuration()??0,p=this.audioBufferManager?.getForwardBufferDuration()??0,d=l<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&p<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&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:y.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,y.flattenObject)(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=(0,y.interval)(50).subscribe(t,i=>{this.error$.next({id:"StallWatchdogCallback",category:y.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,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}getCodecs(){return this.manifest?.codecs}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(){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,y.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 ze=require("@vkontakte/videoplayer-shared/es2024"),Gn=class{constructor(){this.subscription=new ze.Subscription;this.pipSize$=new ze.ValueSubject(void 0);this.videoSize$=new ze.ValueSubject(void 0);this.elementSize$=new ze.ValueSubject(void 0);this.pictureInPictureWindowRemoveEventListener=ze.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,ze.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,ze.combine)({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe((0,ze.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 Mi=class{constructor(e){this.subscription=new H.Subscription;this.videoState=new Z("stopped");this.observableVideo=null;this.droppedFramesManager=new ur;this.stallsManager=new Bn;this.elementSizeManager=new Gn;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,H.assertNever)(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new vr(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=He(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($e(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 Wn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer,forceVideoCodec:this.params.forceVideoCodec}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params;(0,H.isNullable)(this.observableVideo)&&(this.observableVideo=Qe(this.video),this.subscription.add(()=>this.observableVideo?.destroy()));let i=this.constructor.name,r=n=>{e.error$.next({id:i,category:H.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,H.filter)(d=>!!d.length),(0,H.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,H.map)(d=>d.to.state!=="none"),(0,H.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,H.filter)(H.isNonNullable),(0,H.once)()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe((0,H.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(Rt(this.video,t.isLooped,r)),this.subscription.add(_e(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(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.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(i.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.player.manifestRequested.subscribe(this.params.output.manifestRequested$)).add(this.player.manifestReceived.subscribe(this.params.output.manifestReceived$)).add(this.player.firstBytesRequested.subscribe(this.params.output.firstBytesRequested$)).add(this.player.firstBytesReceived.subscribe(this.params.output.firstBytesReceived$)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams(),h=this.player.getCodecs();if((0,H.assertNonNullable)(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let b=[];for(let S of c.audio){b.push(Nl(S));let v=[];for(let I of S.representations){let R=zS(I);v.push(R),this.audioTracksMap.set(R,{stream:S,representation:I})}this.audioStreamsMap.set(S,v)}this.params.output.availableAudioStreams$.next(b)}let m=[];for(let b of c.video){m.push(ql(b));let S=[];for(let v of b.representations){let I=Qa({...v,streamId:b.id});I&&(S.push(I),this.videoTracksMap.set(I,{stream:b,representation:v}))}this.videoStreamsMap.set(b,S)}this.params.output.availableVideoStreams$.next(m);for(let b of c.text)for(let S of b.representations){let v=YS(b,S);this.textTracksMap.set(v,{stream:b,representation:S})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),h?.video&&this.params.output.availableVideoCodecs$.next(h.video),h?.audio&&this.params.output.availableAudioCodecs$.next(h.audio),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let{vktvAbrThrottle:u}=this.params.tuning.dash,o=u&&JS(u)||null;this.subscription.add((0,H.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,H.fromEvent)(this.video,"progress")).pipe((0,H.filter)(()=>this.videoTracksMap.size>0)).subscribe(async()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(d!=="manifest_ready"&&d!=="running"||c||d==="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 b=Li(this.videoTracksMap.keys(),v=>this.videoTracksMap.get(v)?.representation.id===h.id);(0,H.isNonNullable)(b)&&(this.stallsManager.lastVideoTrackSelected=b);let S=this.params.desiredState.autoVideoTrackLimits.getTransition();if(S&&this.params.output.autoVideoTrackLimits$.next(S.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 v=!!t.audioStream.getTransition();await this.player.switchRepresentation("audio",m.id,v)}},r)),this.subscription.add((0,H.combine)({videoState:this.videoState.stateChangeEnded$,autoVideoTrackState:(0,H.merge)((0,H.observableFrom)([t.autoVideoTrackSwitching.getState()]),t.autoVideoTrackSwitching.stateChangeEnded$.pipe((0,H.map)(d=>d.to)))}).pipe((0,H.map)(({videoState:d,autoVideoTrackState:c})=>d.to!=="stopped"&&c),(0,H.filterChanged)()).subscribe(d=>this.player.setSmartRepresentationSwitch(d))),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,H.filterChanged)()).subscribe(d=>{let c=Li(this.videoTracksMap.entries(),([,{representation:v}])=>v.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:m}]=c,b=this.params.desiredState.videoStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.videoStream.setState(b.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(ql(m));let S=this.player.calculateDurationFromSegments();S&&this.params.output.duration$.next(S/1e3)},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe((0,H.filterChanged)()).subscribe(d=>{let c=Li(this.audioTracksMap.entries(),([,{representation:S}])=>S.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[h,{stream:m}]=c,b=this.params.desiredState.audioStream.getTransition();b&&b.to&&b.to.id===m.id&&this.params.desiredState.audioStream.setState(b.to),e.currentAudioStream$.next(Nl(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(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 l=t.playbackState.stateChangeStarted$.pipe((0,H.map)(({to:d})=>d==="ready"),(0,H.filterChanged)());this.subscription.add((0,H.merge)(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,(0,H.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,H.merge)(l,this.player.state$.stateChangeEnded$,(0,H.observableFrom)(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let p=(0,H.merge)(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,(0,H.observableFrom)(["init"])).pipe((0,H.debounce)(0));this.subscription.add(p.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){if(this.player.isStreamEnded)return;let e=this.params.tuning.useNewAutoSelectVideoTrack?ia:ta,t=this.params.tuning.useNewAutoSelectVideoTrack?un:on,i=this.params.tuning.useNewAutoSelectVideoTrack?kt:nn,{desiredState:r,output:s}=this.params,n=r.autoVideoTrackSwitching.getState(),u=r.videoTrack.getState()?.id,o=Li(this.videoTracksMap.keys(),M=>M.id===u),l=s.currentVideoTrack$.getValue(),p=r.videoStream.getState()??(o&&this.videoTracksMap.get(o)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!p)return;let d=Li(this.videoStreamsMap.keys(),M=>M.id===p.id),c=d&&this.videoStreamsMap.get(d);if(!c)return;let h=Me(this.video.buffered,this.video.currentTime*1e3),m;this.player.isActiveLive$.getValue()?m=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?m=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:m=n?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let b=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,S=Math.min(h/Math.min(m,b||1/0),1),v=r.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),I=v?.id&&Li(this.audioStreamsMap.keys(),M=>M.id===v.id)||this.audioStreamsMap.keys().next().value,R=0;if(I){if(o&&!n){let M=e(o,c,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);R=Math.max(R,M?.bitrate??-1/0)}if(l){let M=e(l,c,this.audioStreamsMap.get(I)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);R=Math.max(R,M?.bitrate??-1/0)}}let w=o;(n||!w)&&(w=i(c,{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:R,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=I&&t(w,c,this.audioStreamsMap.get(I)??[],{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}),_=this.videoTracksMap.get(w)?.representation,O=C&&this.audioTracksMap.get(C)?.representation;_&&O?(this.selectedRepresentations.video=_,this.selectedRepresentations.audio=O):_&&!O&&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(){We(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:H.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),je(this.video),this.tracer.end()}};var za=class extends Mi{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/es2024");var Ya=class extends Mi{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(),p=i.volume$.getValue(),d=!p.volume||p.muted;!o&&!l&&d?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 p=i.liveBufferTime$.getValue(),d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;d||l<1-c||this.video.paused||(0,de.isNullable)(p)||(t=o-p)})).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:p})=>{let d=i.position$.getValue(),{playbackCatchupSpeedup:c}=this.params.tuning.dashCmafLive.lowLatency;if(!d&&!this.video.paused&&p>=1-c||(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=KS(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 iv="X-Playback-Duration",Ql=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(iv)?parseInt(e.headers.get(iv),10):void 0};var re=require("@vkontakte/videoplayer-shared/es2024");var Gl=Q(nu(),1);var zn=require("@vkontakte/videoplayer-shared/es2024");var hL=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,zn.videoSizeToQuality)({width:t,height:i})}return e??null},fL=(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,Gl.default)(u[1].split(",").map(S=>S.split("="))),p=l.QUALITY??`stream-${l.BANDWIDTH}`,d=hL(l),c;l.BANDWIDTH&&(c=parseInt(l.BANDWIDTH,10)/1e3||void 0),!c&&l["AVERAGE-BANDWIDTH"]&&(c=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,v]=l.RESOLUTION.split("x").map(I=>parseInt(I,10));S&&v&&(m={width:S,height:v})}let b=new URL(t[++s],e).toString();d&&i.push({id:p,quality:d,url:b,bandwidth:c,size:m,fps:h})}if(o){let l=(0,Gl.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,"")])),p=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,c=l.NAME;p&&d&&r.push({type:"internal",id:d,label:c,language:d,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},mL=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Wl=0,rv=async(a,e=a,t,i)=>{let s=await(await lt(a,i)).text();Wl+=1;try{let{qualityManifests:n,textTracks:u}=fL(s,e);return{qualityManifests:n,textTracks:u}}catch{if(Wl<=t.manifestRetryMaxCount)return await mL((0,zn.getExponentialDelay)(Wl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),rv(a,e,t)}return{qualityManifests:[],textTracks:[]}},Yn=rv;var rt=require("@vkontakte/videoplayer-shared/es2024");var Kn=class{constructor(e,t,i,r,s){this.subscription=new rt.Subscription;this.abortControllers={destroy:new ue,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new rt.ValueSubject(null);this.getCurrentTime$=new rt.ValueSubject(null);this.error$=new rt.Subject;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe((0,rt.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(),p=Number(this.extractPlaylistRowValue("#EXTINF:",u))*1e3;if(i.segments.push({time:{from:s,to:s+p},url:l}),s=s+p,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),c=new Date(i.programDateTime).valueOf();i.segmentStartTime=c-d}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,rt.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:rt.ErrorCategory.WTF,thrown:t,message:e})}};var Ka=class{constructor(e){this.subscription=new re.Subscription;this.videoState=new Z("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new re.ValueSubject([]);this.liveOffset=new Ei;this.manifestStartTime$=new re.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 p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p),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 p=this.liveOffset.getTotalOffset();p>=this.maxSeekBackTime$.getValue()&&(p=0,this.liveOffset.resetTo(p)),this.liveOffset.resume(),this.params.output.position$.next(-p/1e3),this.prepare()}else r?.to==="paused"&&(B(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return(0,re.assertNever)(t)}};this.params=e,this.video=He(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:re.VideoQuality.INVARIANT,url:this.params.source.url};let t=(i,r)=>Yn(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 Kn(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:re.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:re.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($e(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new re.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:re.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:u})},r=Qe(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(_e(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,re.filterChanged)(),(0,re.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(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,re.isNonNullable)(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let c=this.manifests$.getValue().find(h=>h.id===d);c&&(this.params.output.currentVideoTrack$.next(c),this.params.output.hostname$.next($e(c.url)))}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.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,re.combine)({startTime:this.manifestStartTime$.pipe((0,re.filter)(re.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,re.map)(u=>u.map(({id:o,quality:l,size:p,bandwidth:d,fps:c})=>({id:o,quality:l,size:p,fps:c,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=(0,re.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,re.observableFrom)(["init"])).pipe((0,re.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),je(this.video)}prepare(){let e=this.selectManifest();if((0,re.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,p]of[[u,"mq"],[o,"lq"]]){let d=String(parseFloat(l||""));p&&l&&r.searchParams.set(p,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(),Ql(n).then(u=>{if(!(0,re.isNullable)(u))this.maxSeekBackTime$.next(u);else{let o=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();((0,re.isNullable)(o)||!isFinite(o))&<(n).then(l=>l.text()).then(l=>{let p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(p){let d=new URL(p,n).toString();Ql(d).then(c=>{(0,re.isNullable)(c)||this.maxSeekBackTime$.next(c)})}}).catch(()=>{})}})}playIfAllowed(){We(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:re.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 ee=require("@vkontakte/videoplayer-shared/es2024");var Xa=class{constructor(e){this.subscription=new ee.Subscription;this.videoState=new Z("stopped");this.manifests$=new ee.ValueSubject([]);this.unmuteAfterBrowserResetsHappened=new ee.ValueSubject(!1);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),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 p=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(p);let{currentTime:d}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.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"?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,ee.assertNever)(t)}};this.textTracksManager=new ot(e.source.url),this.params=e,this.video=He(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ee.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($e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.manifestRequested$.next(),Yn(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.params.output.manifestReceived$.next(),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:ee.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:ee.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:u})},r=Qe(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,ee.map)(u=>u.to)),this.params.output.playbackState$),this.subscription.add(Rt(this.video,t.isLooped,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(nt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(t.volume.stateChangeStarted$.pipe((0,ee.map)(()=>{let u=t.volume.getTransition(),o=this.params.output.element$.getValue();return!o||!u?!1:!u.to.muted&&o.muted}),(0,ee.filter)(u=>!!u),(0,ee.once)()).subscribe(()=>{this.unmuteAfterBrowserResetsHappened.next(!0)})),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.playbackRateState$.pipe((0,ee.filter)(()=>this.unmuteAfterBrowserResetsHappened.getValue()),(0,ee.once)()).subscribe(()=>{let u=this.params.output.element$.getValue(),o=t.playbackRate.getState();u&&o!==u.playbackRate&&(u.playbackRate=o)})),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(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(0,ee.isNonNullable)(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let m=this.manifests$.getValue().find(b=>b.id===h);m&&(this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next($e(m.url)))}let d=this.params.desiredState.playbackRate.getState(),c=this.params.output.element$.getValue()?.playbackRate;if(d!==c){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to),o&&o.from==="changing_manifest"&&this.videoState.setState(o.to),u.state==="requested"&&this.seek(u.position)},i))),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),this.subscription.add(this.manifests$.pipe((0,ee.map)(u=>u.map(({id:o,quality:l,size:p,bandwidth:d,fps:c})=>({id:o,quality:l,size:p,fps:c,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!W.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:u}=this.video;this.subscription.add((0,ee.merge)((0,ee.fromEvent)(u,"addtrack"),(0,ee.fromEvent)(u,"removetrack"),(0,ee.fromEvent)(u,"change"),(0,ee.observableFrom)(["init"])).subscribe(()=>{for(let o=0;o<u.length;o++)u[o].mode="hidden"},i))}let n=(0,ee.merge)(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,(0,ee.observableFrom)(["init"])).pipe((0,ee.debounce)(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),je(this.video)}prepare(){let e=this.selectManifest();if((0,ee.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(){We(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:ee.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var av=Q(Gi(),1),zl=Q(gi(),1),sv=Q(gt(),1);var fe=require("@vkontakte/videoplayer-shared/es2024");var Ja=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=He(e.container,e.tuning),this.params.output.element$.next(this.video),(0,av.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,zl.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=Qe(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(Rt(this.video,t.isLooped,i)),this.subscription.add(_e(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(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 p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(o),p.playbackRate=o)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.params.tuning.changePlaybackStateToPausedWhenEnded&&this.subscription.add(r.ended$.subscribe(()=>{this.videoState.setState("paused"),B(t.playbackState,"paused")})),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),je(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($e(t))}playIfAllowed(){We(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 p=kt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:l,abrLogger:this.params.dependencies.abrLogger});t(p)},r=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,zl.default)(this.trackUrls).map(l=>l.track);if(!r||!s||sr(e,n[0].quality,(0,sv.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/es2024");var ov=require("@vkontakte/videoplayer-shared/es2024"),nv=["stun:videostun.mycdn.me:80"],bL=1e3,gL=3,Yl=()=>null,Xn=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=Yl;this.externalStopCallback=Yl;this.externalErrorCallback=Yl;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:nv}]};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:ov.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),bL)}normalizeOptions(e={}){let t={stunServerList:nv,maxRetryNumber:gL,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=He(e.container,e.tuning),this.liveStreamClient=new Xn(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),je(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=Qe(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(_e(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return(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($e(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(){We(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 yr=class{constructor(e){this.length=e.length,this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next(),this.index=this.index===void 0?0:this.index+1}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}isLast(){return this.index===this.length-1}};var E=require("@vkontakte/videoplayer-shared/es2024");var Qt=require("@vkontakte/videoplayer-shared/es2024"),uv=a=>new Qt.Observable(e=>{let t=new Qt.Subscription,i=a.desiredPlaybackState$.stateChangeStarted$.pipe((0,Qt.map)(({from:l,to:p})=>`${l}-${p}`)),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/es2024");function lv(){return new(window.AudioContext||window.webkitAudioContext)}var Tr=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){W.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=lv();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 SL={chunkDuration:5e3,maxParallelRequests:5},es=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),availableVideoCodecs$:new E.ValueSubject([]),availableAudioStreams$:new E.ValueSubject([]),currentAudioStream$:new E.ValueSubject(void 0),availableAudioTracks$:new E.ValueSubject([]),availableAudioCodecs$: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,manifestRequested$:new E.Subject,manifestReceived$:new E.Subject,firstBytesRequested$:new E.Subject,firstBytesReceived$: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),canPlayLiveTailBuffer$:new E.ValueSubject(!1),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=Yu([...FS(this.params.tuning),...OS(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,Kl.default)(r,l)),...t.filter(l=>(0,Kl.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",(0,E.flattenObject)(s)),this.screenFormatsIterator=new yr(s);let n=[...Dl(!0),...Dl(!1)];this.chromecastFormatsIterator=new yr(n.filter(l=>(0,E.isNonNullable)(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:u=1,tuning:{useVolumeMultiplier:o}}=this.params;o&&u!==1&&Tr.isSupported()&&(this.volumeMultiplierManager=new Tr(this.providerOutput,this.current$,this.volumeMultiplierError$,u))}init(){this.subscription.add(this.initProviderErrorHandling()).add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()})).add(this.providerOutput.availableVideoCodecs$.subscribe(e=>{!this.videoCodecsIterator&&e.length>1&&(this.videoCodecsIterator=new yr(e))}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if((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()}switchToNextVideoCodec(){this.params.tuning.dash.codecsPrioritizeEnabled&&!this.videoCodecsIterator.isLast()&&(this.tracer.log("switchToNextVideoCodec"),this.destroyProvider(),this.videoCodecsIterator.next(),this.initProvider())}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider"),e.destroy();let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}let 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,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,E.assertNonNullable)(o),this.params.tuning.useNewDashProvider?new za({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()}):new Ha({...u,source:o,sourceHls:l,forceVideoCodec:this.videoCodecsIterator?.getValue()})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),this.params.tuning.useNewDashProvider?new Ya({...u,source:o}):new ja({...u,source:o})}case"HLS":case"HLS_ONDEMAND":case"HLS_FMP4":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new Xa({...u,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new Ka({...u,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new Ja({...u,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,E.assertNonNullable)(o),new _b({...u,source:o,config:{...SL,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return(0,E.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,E.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,E.assertNonNullable)(u),new Jr({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,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,dv.default)((0,cv.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))),uv({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 u=r.category===E.ErrorCategory.NETWORK,o=r.category===E.ErrorCategory.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),p=i<this.params.tuning.providerErrorLimit&&!o,d=this.videoCodecsIterator&&!this.videoCodecsIterator.isLast()&&this.params.tuning.dash.codecsPrioritizeEnabled,c=l&&!o&&(u&&t||!p);n={...n,isNetworkError:u,isFatalError:o,haveFailoverHost:l,tryFailover:c,canReinitProvider:p},p?(i++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?this.switchToNextVideoCodec():(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 X=require("@vkontakte/videoplayer-shared/es2024");var vL=5e3,pv="one_video_throughput",hv="one_video_rtt",ts=window.navigator.connection,fv=()=>{let a=ts?.downlink;if((0,X.isNonNullable)(a)&&a!==10)return a*1e3},mv=()=>{let a=ts?.rtt;if((0,X.isNonNullable)(a)&&a!==3e3)return a},bv=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Xl=class a{constructor(e){this.subscription=new X.Subscription;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=a.load(pv)||(e.useBrowserEstimation?fv():void 0)||vL,i=a.load(hv)??(e.useBrowserEstimation?mv():void 0)??0;if(this.throughput$=new X.ValueSubject(t),this.rtt$=new X.ValueSubject(i),this.rttAdjustedThroughput$=new X.ValueSubject(bv(t,i,e.rttPenaltyRequestSize)),this.throughput=jt.getSmoothedValue(t,-1,e),this.rtt=jt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let r=()=>{let n=fv();n&&this.throughput.next(n);let u=mv();(0,X.isNonNullable)(u)&&this.rtt.next(u)};ts&&"onchange"in ts&&this.subscription.add((0,X.fromEvent)(ts,"change").subscribe(r)),r()}this.subscription.add(this.throughput.smoothed$.subscribe(r=>{X.safeStorage.set(pv,r.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(r=>{X.safeStorage.set(hv,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,X.combine)({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe((0,X.map)(({throughput:r,rtt:s})=>bv(r,s,e.rttPenaltyRequestSize)),(0,X.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,X.now)(),r=new X.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add((0,X.fromEvent)(e,"progress").pipe((0,X.once)()).subscribe(s=>{t=s.loaded,i=(0,X.now)()}));break;case 1:case 0:r.add((0,X.fromEvent)(e,"loadstart").subscribe(()=>{t=0,i=(0,X.now)()}));break}r.add((0,X.fromEvent)(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,u=(0,X.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,X.now)(),n=0,u=(0,X.now)(),o=p=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${p}`).catch(()=>{})},l=async({done:p,value:d})=>{if(p)!t&&this.addRawSpeed(r,(0,X.now)()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let c=(0,X.now)();if(c-u>this.tuningConfig.lowLatency.continuesByteSequenceInterval||c-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=u-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=(0,X.now)()}else n+=d.byteLength;u=(0,X.now)()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&(0,X.now)()-u>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,(0,X.now)()-u,this.concurrentDownloads.size),n=0,u=(0,X.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=X.safeStorage.get(e);if((0,X.isNonNullable)(t))return parseInt(t,10)??void 0}},gv=Xl;var Di=require("@vkontakte/videoplayer-shared/es2024"),Sv={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:Di.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Di.VideoQuality.Q_720P,trafficSavingLimit:Di.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:Di.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:15e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useNewRepresentationSwitch:!1,useDelayedRepresentationSwitch:!1,useSmartRepresentationSwitch:!1,useFetchPriorityHints:!0,enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,vktvAbrThrottle:0,timeupdateEventTickThrottle:300,fetcherBufferOptimisation:!0,codecsPrioritizeEnabled:!1,usePersistentGaps:!1,abrThrottle:0,useVideoElementWaitingCurrentTimeReassign:!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",iosPreferredFormat:"hls",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,useNativeHLSTextTracks:!1,useNewSwitchTo:!1,useNewDashProvider:!1,useNewAutoSelectVideoTrack:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1,changePlaybackStateToPausedWhenEnded:!1,suppressExceptionsInObservables:!0},vv=a=>({...(0,Di.fillWithDefault)(a,Sv),configName:[...a.configName??[],...Sv.configName]});var f=require("@vkontakte/videoplayer-shared/es2024");var Wt=require("@vkontakte/videoplayer-shared/es2024"),Jl=({seekState:a,position$:e})=>(0,Wt.merge)(a.stateChangeEnded$.pipe((0,Wt.map)(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),(0,Wt.filter)(Wt.isNonNullable)),e.pipe((0,Wt.filter)(()=>a.getState().state==="none")));var yv=require("@vkontakte/videoplayer-shared/es2024"),Tv=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return(0,yv.assertNonNullable)(e,`Wrong container or containerId {${a.container}}`),e};var Jn=require("@vkontakte/videoplayer-shared/es2024"),Iv=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe((0,Jn.filter)(r=>r.length>0),(0,Jn.once)()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t?.getValue().find(i))&&e.startTransitionTo(a)};var is=class{constructor(e={configName:[]},t=f.TracerFactory.createRootTracer(!1),i){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,manifestRequested$:new f.Subject,manifestReceived$:new f.Subject,firstBytesRequested$:new f.Subject,firstBytesReceived$: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:vb,getCurrentTime$:new f.ValueSubject(null)};if(this.initLogs(),this.tuning=vv(e),this.tracer=t,this.tuning.suppressExceptionsInObservables&&((0,Zl.default)(this.info).forEach(r=>r.setSuppressErrors(!0)),(0,Zl.default)(this.events).forEach(r=>r.setSuppressErrors(!0))),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ts({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new gv(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new f.InternalsExposure("core",(0,f.getPlayerId)(i?.playerId)),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,s,n)=>{let u=Reflect.get(r,s,n);return typeof u!="function"?u:(...o)=>{try{return u.apply(r,o)}catch(l){let p=o.map(h=>JSON.stringify(h,(m,b)=>{let S=typeof b;return(0,Ev.default)(["number","string","boolean"],S)?b:b===null?null:`<${S}>`})),d=`Player.${String(s)}`,c=`Exception calling ${d} (${p.join(", ")})`;throw this.events.fatalError$.next({id:d,category:f.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}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=Tv(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new es({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?W.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(()=>{this.desiredState.playbackRate.startTransitionTo(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(()=>{Iv(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(yb(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:Jl({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(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.manifestRequested$.pipe((0,f.once)()).subscribe(this.events.manifestRequested$)).add(e.providerOutput.manifestReceived$.pipe((0,f.once)()).subscribe(this.events.manifestReceived$)).add(e.providerOutput.firstBytesRequested$.pipe((0,f.once)()).subscribe(this.events.firstBytesRequested$)).add(e.providerOutput.firstBytesReceived$.pipe((0,f.once)()).subscribe(this.events.firstBytesReceived$)).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(),p=this.chromecastInitializer.castState$.getValue(),d;p==="CONNECTED"?d="second_screen":o?l?n?d="pip":u?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=kt(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),Sb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>gb(t)),this.providerContainer.current$.subscribe(({type:t})=>ea("provider",t)),e.duration$.subscribe(t=>ea("duration",t)),e.availableVideoTracks$.pipe((0,f.filter)(t=>!!t.length),(0,f.once)()).subscribe(t=>ea("tracks",t)),this.events.fatalError$.subscribe(new Oe("fatalError")),this.events.managedError$.subscribe(new Oe("managedError")),e.position$.subscribe(new Oe("position")),e.currentVideoTrack$.pipe((0,f.map)(t=>t?.quality)).subscribe(new Oe("quality")),this.info.currentBuffer$.subscribe(new Oe("buffer")),e.isBuffering$.subscribe(new Oe("isBuffering"))].forEach(t=>this.subscription.add(t)),ea("codecs",W.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&&!na()}};var Ct=require("@vkontakte/videoplayer-shared/es2024"),yL=`@vkontakte/videoplayer-core@${to}`;
|