@vkontakte/videoplayer-core 2.0.117-dev.d9cc3d97.0 → 2.0.118-beta.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 +26 -26
- package/es2015.esm.js +27 -27
- package/es2018.cjs.js +31 -31
- package/es2018.esm.js +28 -28
- package/esnext.cjs.js +24 -24
- package/esnext.esm.js +22 -22
- package/evergreen.esm.js +20 -21
- package/package.json +2 -2
- package/types/player/Player.d.ts +1 -1
- package/types/player/types.d.ts +5 -2
- package/types/providers/DashProvider/lib/buffer.d.ts +1 -3
- package/types/providers/DashProvider/lib/parsers/mpeg/boxes/uuid.d.ts +8 -3
- package/types/providers/DashProvider/lib/player.d.ts +2 -1
- package/types/providers/DashProvider/lib/types.d.ts +7 -1
- package/types/providers/DashProvider/lib/utils.d.ts +1 -1
- package/types/providers/HlsLiveProvider/index.d.ts +0 -2
- package/types/providers/HlsProvider/manifestDataExtractor.d.ts +1 -1
- package/types/providers/types.d.ts +1 -1
- package/types/utils/smoothedValue/smoothedValueFactory.d.ts +1 -1
- package/types/utils/tuningConfig.d.ts +1 -8
- package/types/providers/HlsLiveProvider/LiveTextManager.d.ts +0 -42
package/esnext.esm.js
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
* Thu,
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.118-beta.0
|
|
3
|
+
* Thu, 21 Nov 2024 21:19:06 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-118/doc/
|
|
5
5
|
*/
|
|
6
|
-
var rS=Object.create;var Zu=Object.defineProperty;var aS=Object.getOwnPropertyDescriptor;var sS=Object.getOwnPropertyNames;var nS=Object.getPrototypeOf,oS=Object.prototype.hasOwnProperty;var f=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var uS=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of sS(e))!oS.call(r,a)&&a!==t&&Zu(r,a,{get:()=>e[a],enumerable:!(i=aS(e,a))||i.enumerable});return r};var Oe=(r,e,t)=>(t=r!=null?rS(nS(r)):{},uS(e||!r||!r.__esModule?Zu(t,"default",{value:r,enumerable:!0}):t,r));var ye=f((v$,ol)=>{"use strict";ol.exports=function(r){try{return!!r()}catch{return!0}}});var Fi=f((y$,ul)=>{"use strict";var bS=ye();ul.exports=!bS(function(){var r=function(){}.bind();return typeof r!="function"||r.hasOwnProperty("prototype")})});var le=f((T$,dl)=>{"use strict";var ll=Fi(),cl=Function.prototype,Zs=cl.call,gS=ll&&cl.bind.bind(Zs,Zs);dl.exports=ll?gS:function(r){return function(){return Zs.apply(r,arguments)}}});var oi=f((I$,hl)=>{"use strict";var pl=le(),SS=pl({}.toString),vS=pl("".slice);hl.exports=function(r){return vS(SS(r),8,-1)}});var fl=f((E$,ml)=>{"use strict";var yS=le(),TS=ye(),IS=oi(),en=Object,ES=yS("".split);ml.exports=TS(function(){return!en("z").propertyIsEnumerable(0)})?function(r){return IS(r)==="String"?ES(r,""):en(r)}:en});var ui=f((x$,bl)=>{"use strict";bl.exports=function(r){return r==null}});var qi=f((P$,gl)=>{"use strict";var xS=ui(),PS=TypeError;gl.exports=function(r){if(xS(r))throw new PS("Can't call method on "+r);return r}});var li=f((k$,Sl)=>{"use strict";var kS=fl(),wS=qi();Sl.exports=function(r){return kS(wS(r))}});var tn=f((w$,vl)=>{"use strict";vl.exports=function(){}});var Vt=f((A$,yl)=>{"use strict";yl.exports={}});var G=f((rn,Tl)=>{"use strict";var Ui=function(r){return r&&r.Math===Math&&r};Tl.exports=Ui(typeof globalThis=="object"&&globalThis)||Ui(typeof window=="object"&&window)||Ui(typeof self=="object"&&self)||Ui(typeof global=="object"&&global)||Ui(typeof rn=="object"&&rn)||function(){return this}()||Function("return this")()});var j=f((R$,Il)=>{"use strict";var an=typeof document=="object"&&document.all;Il.exports=typeof an>"u"&&an!==void 0?function(r){return typeof r=="function"||r===an}:function(r){return typeof r=="function"}});var Pl=f(($$,xl)=>{"use strict";var AS=G(),RS=j(),El=AS.WeakMap;xl.exports=RS(El)&&/native code/.test(String(El))});var we=f((L$,kl)=>{"use strict";var $S=j();kl.exports=function(r){return typeof r=="object"?r!==null:$S(r)}});var Ae=f((M$,wl)=>{"use strict";var LS=ye();wl.exports=!LS(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var ka=f((D$,Rl)=>{"use strict";var MS=G(),Al=we(),sn=MS.document,DS=Al(sn)&&Al(sn.createElement);Rl.exports=function(r){return DS?sn.createElement(r):{}}});var nn=f((C$,$l)=>{"use strict";var CS=Ae(),VS=ye(),BS=ka();$l.exports=!CS&&!VS(function(){return Object.defineProperty(BS("div"),"a",{get:function(){return 7}}).a!==7})});var on=f((V$,Ll)=>{"use strict";var OS=Ae(),_S=ye();Ll.exports=OS&&_S(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=f((B$,Ml)=>{"use strict";var NS=we(),FS=String,qS=TypeError;Ml.exports=function(r){if(NS(r))return r;throw new qS(FS(r)+" is not an object")}});var Te=f((O$,Dl)=>{"use strict";var US=Fi(),wa=Function.prototype.call;Dl.exports=US?wa.bind(wa):function(){return wa.apply(wa,arguments)}});var Aa=f((_$,Cl)=>{"use strict";Cl.exports={}});var rt=f((N$,Bl)=>{"use strict";var un=Aa(),ln=G(),HS=j(),Vl=function(r){return HS(r)?r:void 0};Bl.exports=function(r,e){return arguments.length<2?Vl(un[r])||Vl(ln[r]):un[r]&&un[r][e]||ln[r]&&ln[r][e]}});var Hi=f((F$,Ol)=>{"use strict";var jS=le();Ol.exports=jS({}.isPrototypeOf)});var ci=f((q$,Fl)=>{"use strict";var GS=G(),_l=GS.navigator,Nl=_l&&_l.userAgent;Fl.exports=Nl?String(Nl):""});var dn=f((U$,Ql)=>{"use strict";var Gl=G(),cn=ci(),ql=Gl.process,Ul=Gl.Deno,Hl=ql&&ql.versions||Ul&&Ul.version,jl=Hl&&Hl.v8,_e,Ra;jl&&(_e=jl.split("."),Ra=_e[0]>0&&_e[0]<4?1:+(_e[0]+_e[1]));!Ra&&cn&&(_e=cn.match(/Edge\/(\d+)/),(!_e||_e[1]>=74)&&(_e=cn.match(/Chrome\/(\d+)/),_e&&(Ra=+_e[1])));Ql.exports=Ra});var pn=f((H$,Yl)=>{"use strict";var Wl=dn(),QS=ye(),WS=G(),YS=WS.String;Yl.exports=!!Object.getOwnPropertySymbols&&!QS(function(){var r=Symbol("symbol detection");return!YS(r)||!(Object(r)instanceof Symbol)||!Symbol.sham&&Wl&&Wl<41})});var hn=f((j$,zl)=>{"use strict";var zS=pn();zl.exports=zS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var mn=f((G$,Kl)=>{"use strict";var KS=rt(),XS=j(),JS=Hi(),ZS=hn(),ev=Object;Kl.exports=ZS?function(r){return typeof r=="symbol"}:function(r){var e=KS("Symbol");return XS(e)&&JS(e.prototype,ev(r))}});var ji=f((Q$,Xl)=>{"use strict";var tv=String;Xl.exports=function(r){try{return tv(r)}catch{return"Object"}}});var at=f((W$,Jl)=>{"use strict";var iv=j(),rv=ji(),av=TypeError;Jl.exports=function(r){if(iv(r))return r;throw new av(rv(r)+" is not a function")}});var Gi=f((Y$,Zl)=>{"use strict";var sv=at(),nv=ui();Zl.exports=function(r,e){var t=r[e];return nv(t)?void 0:sv(t)}});var tc=f((z$,ec)=>{"use strict";var fn=Te(),bn=j(),gn=we(),ov=TypeError;ec.exports=function(r,e){var t,i;if(e==="string"&&bn(t=r.toString)&&!gn(i=fn(t,r))||bn(t=r.valueOf)&&!gn(i=fn(t,r))||e!=="string"&&bn(t=r.toString)&&!gn(i=fn(t,r)))return i;throw new ov("Can't convert object to primitive value")}});var Ne=f((K$,ic)=>{"use strict";ic.exports=!0});var sc=f((X$,ac)=>{"use strict";var rc=G(),uv=Object.defineProperty;ac.exports=function(r,e){try{uv(rc,r,{value:e,configurable:!0,writable:!0})}catch{rc[r]=e}return e}});var Qi=f((J$,uc)=>{"use strict";var lv=Ne(),cv=G(),dv=sc(),nc="__core-js_shared__",oc=uc.exports=cv[nc]||dv(nc,{});(oc.versions||(oc.versions=[])).push({version:"3.38.0",mode:lv?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Sn=f((Z$,cc)=>{"use strict";var lc=Qi();cc.exports=function(r,e){return lc[r]||(lc[r]=e||{})}});var Wi=f((eL,dc)=>{"use strict";var pv=qi(),hv=Object;dc.exports=function(r){return hv(pv(r))}});var Fe=f((tL,pc)=>{"use strict";var mv=le(),fv=Wi(),bv=mv({}.hasOwnProperty);pc.exports=Object.hasOwn||function(e,t){return bv(fv(e),t)}});var vn=f((iL,hc)=>{"use strict";var gv=le(),Sv=0,vv=Math.random(),yv=gv(1 .toString);hc.exports=function(r){return"Symbol("+(r===void 0?"":r)+")_"+yv(++Sv+vv,36)}});var ae=f((rL,fc)=>{"use strict";var Tv=G(),Iv=Sn(),mc=Fe(),Ev=vn(),xv=pn(),Pv=hn(),di=Tv.Symbol,yn=Iv("wks"),kv=Pv?di.for||di:di&&di.withoutSetter||Ev;fc.exports=function(r){return mc(yn,r)||(yn[r]=xv&&mc(di,r)?di[r]:kv("Symbol."+r)),yn[r]}});var vc=f((aL,Sc)=>{"use strict";var wv=Te(),bc=we(),gc=mn(),Av=Gi(),Rv=tc(),$v=ae(),Lv=TypeError,Mv=$v("toPrimitive");Sc.exports=function(r,e){if(!bc(r)||gc(r))return r;var t=Av(r,Mv),i;if(t){if(e===void 0&&(e="default"),i=wv(t,r,e),!bc(i)||gc(i))return i;throw new Lv("Can't convert object to primitive value")}return e===void 0&&(e="number"),Rv(r,e)}});var Tn=f((sL,yc)=>{"use strict";var Dv=vc(),Cv=mn();yc.exports=function(r){var e=Dv(r,"string");return Cv(e)?e:e+""}});var Bt=f(Ic=>{"use strict";var Vv=Ae(),Bv=nn(),Ov=on(),$a=ze(),Tc=Tn(),_v=TypeError,In=Object.defineProperty,Nv=Object.getOwnPropertyDescriptor,En="enumerable",xn="configurable",Pn="writable";Ic.f=Vv?Ov?function(e,t,i){if($a(e),t=Tc(t),$a(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Pn in i&&!i[Pn]){var a=Nv(e,t);a&&a[Pn]&&(e[t]=i.value,i={configurable:xn in i?i[xn]:a[xn],enumerable:En in i?i[En]:a[En],writable:!1})}return In(e,t,i)}:In:function(e,t,i){if($a(e),t=Tc(t),$a(i),Bv)try{return In(e,t,i)}catch{}if("get"in i||"set"in i)throw new _v("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Yi=f((oL,Ec)=>{"use strict";Ec.exports=function(r,e){return{enumerable:!(r&1),configurable:!(r&2),writable:!(r&4),value:e}}});var pi=f((uL,xc)=>{"use strict";var Fv=Ae(),qv=Bt(),Uv=Yi();xc.exports=Fv?function(r,e,t){return qv.f(r,e,Uv(1,t))}:function(r,e,t){return r[e]=t,r}});var La=f((lL,kc)=>{"use strict";var Hv=Sn(),jv=vn(),Pc=Hv("keys");kc.exports=function(r){return Pc[r]||(Pc[r]=jv(r))}});var Ma=f((cL,wc)=>{"use strict";wc.exports={}});var Rn=f((dL,$c)=>{"use strict";var Gv=Pl(),Rc=G(),Qv=we(),Wv=pi(),kn=Fe(),wn=Qi(),Yv=La(),zv=Ma(),Ac="Object already initialized",An=Rc.TypeError,Kv=Rc.WeakMap,Da,zi,Ca,Xv=function(r){return Ca(r)?zi(r):Da(r,{})},Jv=function(r){return function(e){var t;if(!Qv(e)||(t=zi(e)).type!==r)throw new An("Incompatible receiver, "+r+" required");return t}};Gv||wn.state?(qe=wn.state||(wn.state=new Kv),qe.get=qe.get,qe.has=qe.has,qe.set=qe.set,Da=function(r,e){if(qe.has(r))throw new An(Ac);return e.facade=r,qe.set(r,e),e},zi=function(r){return qe.get(r)||{}},Ca=function(r){return qe.has(r)}):(Ot=Yv("state"),zv[Ot]=!0,Da=function(r,e){if(kn(r,Ot))throw new An(Ac);return e.facade=r,Wv(r,Ot,e),e},zi=function(r){return kn(r,Ot)?r[Ot]:{}},Ca=function(r){return kn(r,Ot)});var qe,Ot;$c.exports={set:Da,get:zi,has:Ca,enforce:Xv,getterFor:Jv}});var $n=f((pL,Cc)=>{"use strict";var Zv=Fi(),Dc=Function.prototype,Lc=Dc.apply,Mc=Dc.call;Cc.exports=typeof Reflect=="object"&&Reflect.apply||(Zv?Mc.bind(Lc):function(){return Mc.apply(Lc,arguments)})});var Ln=f((hL,Vc)=>{"use strict";var ey=oi(),ty=le();Vc.exports=function(r){if(ey(r)==="Function")return ty(r)}});var Nc=f(_c=>{"use strict";var Bc={}.propertyIsEnumerable,Oc=Object.getOwnPropertyDescriptor,iy=Oc&&!Bc.call({1:2},1);_c.f=iy?function(e){var t=Oc(this,e);return!!t&&t.enumerable}:Bc});var Uc=f(qc=>{"use strict";var ry=Ae(),ay=Te(),sy=Nc(),ny=Yi(),oy=li(),uy=Tn(),ly=Fe(),cy=nn(),Fc=Object.getOwnPropertyDescriptor;qc.f=ry?Fc:function(e,t){if(e=oy(e),t=uy(t),cy)try{return Fc(e,t)}catch{}if(ly(e,t))return ny(!ay(sy.f,e,t),e[t])}});var Mn=f((bL,Hc)=>{"use strict";var dy=ye(),py=j(),hy=/#|\.prototype\./,Ki=function(r,e){var t=fy[my(r)];return t===gy?!0:t===by?!1:py(e)?dy(e):!!e},my=Ki.normalize=function(r){return String(r).replace(hy,".").toLowerCase()},fy=Ki.data={},by=Ki.NATIVE="N",gy=Ki.POLYFILL="P";Hc.exports=Ki});var Xi=f((gL,Gc)=>{"use strict";var jc=Ln(),Sy=at(),vy=Fi(),yy=jc(jc.bind);Gc.exports=function(r,e){return Sy(r),e===void 0?r:vy?yy(r,e):function(){return r.apply(e,arguments)}}});var Re=f((SL,Wc)=>{"use strict";var Ji=G(),Ty=$n(),Iy=Ln(),Ey=j(),xy=Uc().f,Py=Mn(),hi=Aa(),ky=Xi(),mi=pi(),Qc=Fe();Qi();var wy=function(r){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new r;case 1:return new r(t);case 2:return new r(t,i)}return new r(t,i,a)}return Ty(r,this,arguments)};return e.prototype=r.prototype,e};Wc.exports=function(r,e){var t=r.target,i=r.global,a=r.stat,s=r.proto,n=i?Ji:a?Ji[t]:Ji[t]&&Ji[t].prototype,o=i?hi:hi[t]||mi(hi,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,S;for(p in e)l=Py(i?p:t+(a?".":"#")+p,r.forced),c=!l&&n&&Qc(n,p),m=o[p],c&&(r.dontCallGetSet?(S=xy(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof m==typeof h)&&(r.bind&&c?g=ky(h,Ji):r.wrap&&c?g=wy(h):s&&Ey(h)?g=Iy(h):g=h,(r.sham||h&&h.sham||m&&m.sham)&&mi(g,"sham",!0),mi(o,p,g),s&&(d=t+"Prototype",Qc(hi,d)||mi(hi,d,{}),mi(hi[d],p,h),r.real&&u&&(l||!u[p])&&mi(u,p,h)))}});var Kc=f((vL,zc)=>{"use strict";var Dn=Ae(),Ay=Fe(),Yc=Function.prototype,Ry=Dn&&Object.getOwnPropertyDescriptor,Cn=Ay(Yc,"name"),$y=Cn&&function(){}.name==="something",Ly=Cn&&(!Dn||Dn&&Ry(Yc,"name").configurable);zc.exports={EXISTS:Cn,PROPER:$y,CONFIGURABLE:Ly}});var Jc=f((yL,Xc)=>{"use strict";var My=Math.ceil,Dy=Math.floor;Xc.exports=Math.trunc||function(e){var t=+e;return(t>0?Dy:My)(t)}});var Va=f((TL,Zc)=>{"use strict";var Cy=Jc();Zc.exports=function(r){var e=+r;return e!==e||e===0?0:Cy(e)}});var td=f((IL,ed)=>{"use strict";var Vy=Va(),By=Math.max,Oy=Math.min;ed.exports=function(r,e){var t=Vy(r);return t<0?By(t+e,0):Oy(t,e)}});var rd=f((EL,id)=>{"use strict";var _y=Va(),Ny=Math.min;id.exports=function(r){var e=_y(r);return e>0?Ny(e,9007199254740991):0}});var Ba=f((xL,ad)=>{"use strict";var Fy=rd();ad.exports=function(r){return Fy(r.length)}});var od=f((PL,nd)=>{"use strict";var qy=li(),Uy=td(),Hy=Ba(),sd=function(r){return function(e,t,i){var a=qy(e),s=Hy(a);if(s===0)return!r&&-1;var n=Uy(i,s),o;if(r&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((r||n in a)&&a[n]===t)return r||n||0;return!r&&-1}};nd.exports={includes:sd(!0),indexOf:sd(!1)}});var cd=f((kL,ld)=>{"use strict";var jy=le(),Vn=Fe(),Gy=li(),Qy=od().indexOf,Wy=Ma(),ud=jy([].push);ld.exports=function(r,e){var t=Gy(r),i=0,a=[],s;for(s in t)!Vn(Wy,s)&&Vn(t,s)&&ud(a,s);for(;e.length>i;)Vn(t,s=e[i++])&&(~Qy(a,s)||ud(a,s));return a}});var Bn=f((wL,dd)=>{"use strict";dd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var hd=f((AL,pd)=>{"use strict";var Yy=cd(),zy=Bn();pd.exports=Object.keys||function(e){return Yy(e,zy)}});var fd=f(md=>{"use strict";var Ky=Ae(),Xy=on(),Jy=Bt(),Zy=ze(),eT=li(),tT=hd();md.f=Ky&&!Xy?Object.defineProperties:function(e,t){Zy(e);for(var i=eT(t),a=tT(t),s=a.length,n=0,o;s>n;)Jy.f(e,o=a[n++],i[o]);return e}});var On=f(($L,bd)=>{"use strict";var iT=rt();bd.exports=iT("document","documentElement")});var qn=f((LL,Ed)=>{"use strict";var rT=ze(),aT=fd(),gd=Bn(),sT=Ma(),nT=On(),oT=ka(),uT=La(),Sd=">",vd="<",Nn="prototype",Fn="script",Td=uT("IE_PROTO"),_n=function(){},Id=function(r){return vd+Fn+Sd+r+vd+"/"+Fn+Sd},yd=function(r){r.write(Id("")),r.close();var e=r.parentWindow.Object;return r=null,e},lT=function(){var r=oT("iframe"),e="java"+Fn+":",t;return r.style.display="none",nT.appendChild(r),r.src=String(e),t=r.contentWindow.document,t.open(),t.write(Id("document.F=Object")),t.close(),t.F},Oa,_a=function(){try{Oa=new ActiveXObject("htmlfile")}catch{}_a=typeof document<"u"?document.domain&&Oa?yd(Oa):lT():yd(Oa);for(var r=gd.length;r--;)delete _a[Nn][gd[r]];return _a()};sT[Td]=!0;Ed.exports=Object.create||function(e,t){var i;return e!==null?(_n[Nn]=rT(e),i=new _n,_n[Nn]=null,i[Td]=e):i=_a(),t===void 0?i:aT.f(i,t)}});var Pd=f((ML,xd)=>{"use strict";var cT=ye();xd.exports=!cT(function(){function r(){}return r.prototype.constructor=null,Object.getPrototypeOf(new r)!==r.prototype})});var Hn=f((DL,wd)=>{"use strict";var dT=Fe(),pT=j(),hT=Wi(),mT=La(),fT=Pd(),kd=mT("IE_PROTO"),Un=Object,bT=Un.prototype;wd.exports=fT?Un.getPrototypeOf:function(r){var e=hT(r);if(dT(e,kd))return e[kd];var t=e.constructor;return pT(t)&&e instanceof t?t.prototype:e instanceof Un?bT:null}});var fi=f((CL,Ad)=>{"use strict";var gT=pi();Ad.exports=function(r,e,t,i){return i&&i.enumerable?r[e]=t:gT(r,e,t),r}});var Wn=f((VL,Ld)=>{"use strict";var ST=ye(),vT=j(),yT=we(),TT=qn(),Rd=Hn(),IT=fi(),ET=ae(),xT=Ne(),Qn=ET("iterator"),$d=!1,st,jn,Gn;[].keys&&(Gn=[].keys(),"next"in Gn?(jn=Rd(Rd(Gn)),jn!==Object.prototype&&(st=jn)):$d=!0);var PT=!yT(st)||ST(function(){var r={};return st[Qn].call(r)!==r});PT?st={}:xT&&(st=TT(st));vT(st[Qn])||IT(st,Qn,function(){return this});Ld.exports={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:$d}});var Na=f((BL,Dd)=>{"use strict";var kT=ae(),wT=kT("toStringTag"),Md={};Md[wT]="z";Dd.exports=String(Md)==="[object z]"});var Zi=f((OL,Cd)=>{"use strict";var AT=Na(),RT=j(),Fa=oi(),$T=ae(),LT=$T("toStringTag"),MT=Object,DT=Fa(function(){return arguments}())==="Arguments",CT=function(r,e){try{return r[e]}catch{}};Cd.exports=AT?Fa:function(r){var e,t,i;return r===void 0?"Undefined":r===null?"Null":typeof(t=CT(e=MT(r),LT))=="string"?t:DT?Fa(e):(i=Fa(e))==="Object"&&RT(e.callee)?"Arguments":i}});var Bd=f((_L,Vd)=>{"use strict";var VT=Na(),BT=Zi();Vd.exports=VT?{}.toString:function(){return"[object "+BT(this)+"]"}});var er=f((NL,_d)=>{"use strict";var OT=Na(),_T=Bt().f,NT=pi(),FT=Fe(),qT=Bd(),UT=ae(),Od=UT("toStringTag");_d.exports=function(r,e,t,i){var a=t?r:r&&r.prototype;a&&(FT(a,Od)||_T(a,Od,{configurable:!0,value:e}),i&&!OT&&NT(a,"toString",qT))}});var Fd=f((FL,Nd)=>{"use strict";var HT=Wn().IteratorPrototype,jT=qn(),GT=Yi(),QT=er(),WT=Vt(),YT=function(){return this};Nd.exports=function(r,e,t,i){var a=e+" Iterator";return r.prototype=jT(HT,{next:GT(+!i,t)}),QT(r,a,!1,!0),WT[a]=YT,r}});var Ud=f((qL,qd)=>{"use strict";var zT=le(),KT=at();qd.exports=function(r,e,t){try{return zT(KT(Object.getOwnPropertyDescriptor(r,e)[t]))}catch{}}});var jd=f((UL,Hd)=>{"use strict";var XT=we();Hd.exports=function(r){return XT(r)||r===null}});var Qd=f((HL,Gd)=>{"use strict";var JT=jd(),ZT=String,eI=TypeError;Gd.exports=function(r){if(JT(r))return r;throw new eI("Can't set "+ZT(r)+" as a prototype")}});var Yn=f((jL,Wd)=>{"use strict";var tI=Ud(),iI=we(),rI=qi(),aI=Qd();Wd.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r=!1,e={},t;try{t=tI(Object.prototype,"__proto__","set"),t(e,[]),r=e instanceof Array}catch{}return function(a,s){return rI(a),aI(s),iI(a)&&(r?t(a,s):a.__proto__=s),a}}():void 0)});var ap=f((GL,rp)=>{"use strict";var sI=Re(),nI=Te(),qa=Ne(),tp=Kc(),oI=j(),uI=Fd(),Yd=Hn(),zd=Yn(),lI=er(),cI=pi(),zn=fi(),dI=ae(),Kd=Vt(),ip=Wn(),pI=tp.PROPER,hI=tp.CONFIGURABLE,Xd=ip.IteratorPrototype,Ua=ip.BUGGY_SAFARI_ITERATORS,tr=dI("iterator"),Jd="keys",ir="values",Zd="entries",ep=function(){return this};rp.exports=function(r,e,t,i,a,s,n){uI(t,e,i);var o=function(S){if(S===a&&p)return p;if(!Ua&&S&&S in c)return c[S];switch(S){case Jd:return function(){return new t(this,S)};case ir:return function(){return new t(this,S)};case Zd:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=r.prototype,d=c[tr]||c["@@iterator"]||a&&c[a],p=!Ua&&d||o(a),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=Yd(h.call(new r)),m!==Object.prototype&&m.next&&(!qa&&Yd(m)!==Xd&&(zd?zd(m,Xd):oI(m[tr])||zn(m,tr,ep)),lI(m,u,!0,!0),qa&&(Kd[u]=ep))),pI&&a===ir&&d&&d.name!==ir&&(!qa&&hI?cI(c,"name",ir):(l=!0,p=function(){return nI(d,this)})),a)if(b={values:o(ir),keys:s?p:o(Jd),entries:o(Zd)},n)for(g in b)(Ua||l||!(g in c))&&zn(c,g,b[g]);else sI({target:e,proto:!0,forced:Ua||l},b);return(!qa||n)&&c[tr]!==p&&zn(c,tr,p,{name:a}),Kd[e]=p,b}});var np=f((QL,sp)=>{"use strict";sp.exports=function(r,e){return{value:r,done:e}}});var Xn=f((WL,dp)=>{"use strict";var mI=li(),Kn=tn(),op=Vt(),lp=Rn(),fI=Bt().f,bI=ap(),Ha=np(),gI=Ne(),SI=Ae(),cp="Array Iterator",vI=lp.set,yI=lp.getterFor(cp);dp.exports=bI(Array,"Array",function(r,e){vI(this,{type:cp,target:mI(r),index:0,kind:e})},function(){var r=yI(this),e=r.target,t=r.index++;if(!e||t>=e.length)return r.target=void 0,Ha(void 0,!0);switch(r.kind){case"keys":return Ha(t,!1);case"values":return Ha(e[t],!1)}return Ha([t,e[t]],!1)},"values");var up=op.Arguments=op.Array;Kn("keys");Kn("values");Kn("entries");if(!gI&&SI&&up.name!=="values")try{fI(up,"name",{value:"values"})}catch{}});var hp=f((YL,pp)=>{"use strict";var TI=ae(),II=Vt(),EI=TI("iterator"),xI=Array.prototype;pp.exports=function(r){return r!==void 0&&(II.Array===r||xI[EI]===r)}});var Jn=f((zL,fp)=>{"use strict";var PI=Zi(),mp=Gi(),kI=ui(),wI=Vt(),AI=ae(),RI=AI("iterator");fp.exports=function(r){if(!kI(r))return mp(r,RI)||mp(r,"@@iterator")||wI[PI(r)]}});var gp=f((KL,bp)=>{"use strict";var $I=Te(),LI=at(),MI=ze(),DI=ji(),CI=Jn(),VI=TypeError;bp.exports=function(r,e){var t=arguments.length<2?CI(r):e;if(LI(t))return MI($I(t,r));throw new VI(DI(r)+" is not iterable")}});var yp=f((XL,vp)=>{"use strict";var BI=Te(),Sp=ze(),OI=Gi();vp.exports=function(r,e,t){var i,a;Sp(r);try{if(i=OI(r,"return"),!i){if(e==="throw")throw t;return t}i=BI(i,r)}catch(s){a=!0,i=s}if(e==="throw")throw t;if(a)throw i;return Sp(i),t}});var Ga=f((JL,xp)=>{"use strict";var _I=Xi(),NI=Te(),FI=ze(),qI=ji(),UI=hp(),HI=Ba(),Tp=Hi(),jI=gp(),GI=Jn(),Ip=yp(),QI=TypeError,ja=function(r,e){this.stopped=r,this.result=e},Ep=ja.prototype;xp.exports=function(r,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=_I(e,i),l,c,d,p,h,m,b,g=function(T){return l&&Ip(l,"normal",T),new ja(!0,T)},S=function(T){return a?(FI(T),o?u(T[0],T[1],g):u(T[0],T[1])):o?u(T,g):u(T)};if(s)l=r.iterator;else if(n)l=r;else{if(c=GI(r),!c)throw new QI(qI(r)+" is not iterable");if(UI(c)){for(d=0,p=HI(r);p>d;d++)if(h=S(r[d]),h&&Tp(Ep,h))return h;return new ja(!1)}l=jI(r,c)}for(m=s?r.next:l.next;!(b=NI(m,l)).done;){try{h=S(b.value)}catch(T){Ip(l,"throw",T)}if(typeof h=="object"&&h&&Tp(Ep,h))return h}return new ja(!1)}});var kp=f((ZL,Pp)=>{"use strict";var WI=Ae(),YI=Bt(),zI=Yi();Pp.exports=function(r,e,t){WI?YI.f(r,e,zI(0,t)):r[e]=t}});var wp=f(()=>{"use strict";var KI=Re(),XI=Ga(),JI=kp();KI({target:"Object",stat:!0},{fromEntries:function(e){var t={};return XI(e,function(i,a){JI(t,i,a)},{AS_ENTRIES:!0}),t}})});var Rp=f((iM,Ap)=>{"use strict";Xn();wp();var ZI=Aa();Ap.exports=ZI.Object.fromEntries});var Lp=f((rM,$p)=>{"use strict";$p.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 Dp=f(()=>{"use strict";Xn();var eE=Lp(),tE=G(),iE=er(),Mp=Vt();for(Qa in eE)iE(tE[Qa],Qa),Mp[Qa]=Mp.Array;var Qa});var Vp=f((nM,Cp)=>{"use strict";var rE=Rp();Dp();Cp.exports=rE});var Zn=f((oM,Bp)=>{"use strict";var aE=Vp();Bp.exports=aE});var Op=f(()=>{"use strict"});var eo=f((cM,_p)=>{"use strict";var rr=G(),sE=ci(),nE=oi(),Wa=function(r){return sE.slice(0,r.length)===r};_p.exports=function(){return Wa("Bun/")?"BUN":Wa("Cloudflare-Workers")?"CLOUDFLARE":Wa("Deno/")?"DENO":Wa("Node.js/")?"NODE":rr.Bun&&typeof Bun.version=="string"?"BUN":rr.Deno&&typeof Deno.version=="object"?"DENO":nE(rr.process)==="process"?"NODE":rr.window&&rr.document?"BROWSER":"REST"}()});var Ya=f((dM,Np)=>{"use strict";var oE=eo();Np.exports=oE==="NODE"});var qp=f((pM,Fp)=>{"use strict";var uE=Bt();Fp.exports=function(r,e,t){return uE.f(r,e,t)}});var jp=f((hM,Hp)=>{"use strict";var lE=rt(),cE=qp(),dE=ae(),pE=Ae(),Up=dE("species");Hp.exports=function(r){var e=lE(r);pE&&e&&!e[Up]&&cE(e,Up,{configurable:!0,get:function(){return this}})}});var Qp=f((mM,Gp)=>{"use strict";var hE=Hi(),mE=TypeError;Gp.exports=function(r,e){if(hE(e,r))return r;throw new mE("Incorrect invocation")}});var io=f((fM,Wp)=>{"use strict";var fE=le(),bE=j(),to=Qi(),gE=fE(Function.toString);bE(to.inspectSource)||(to.inspectSource=function(r){return gE(r)});Wp.exports=to.inspectSource});var Zp=f((bM,Jp)=>{"use strict";var SE=le(),vE=ye(),Yp=j(),yE=Zi(),TE=rt(),IE=io(),zp=function(){},Kp=TE("Reflect","construct"),ro=/^\s*(?:class|function)\b/,EE=SE(ro.exec),xE=!ro.test(zp),ar=function(e){if(!Yp(e))return!1;try{return Kp(zp,[],e),!0}catch{return!1}},Xp=function(e){if(!Yp(e))return!1;switch(yE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return xE||!!EE(ro,IE(e))}catch{return!0}};Xp.sham=!0;Jp.exports=!Kp||vE(function(){var r;return ar(ar.call)||!ar(Object)||!ar(function(){r=!0})||r})?Xp:ar});var th=f((gM,eh)=>{"use strict";var PE=Zp(),kE=ji(),wE=TypeError;eh.exports=function(r){if(PE(r))return r;throw new wE(kE(r)+" is not a constructor")}});var ao=f((SM,rh)=>{"use strict";var ih=ze(),AE=th(),RE=ui(),$E=ae(),LE=$E("species");rh.exports=function(r,e){var t=ih(r).constructor,i;return t===void 0||RE(i=ih(t)[LE])?e:AE(i)}});var sh=f((vM,ah)=>{"use strict";var ME=le();ah.exports=ME([].slice)});var oh=f((yM,nh)=>{"use strict";var DE=TypeError;nh.exports=function(r,e){if(r<e)throw new DE("Not enough arguments");return r}});var so=f((TM,uh)=>{"use strict";var CE=ci();uh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(CE)});var fo=f((IM,gh)=>{"use strict";var Ie=G(),VE=$n(),BE=Xi(),lh=j(),OE=Fe(),bh=ye(),ch=On(),_E=sh(),dh=ka(),NE=oh(),FE=so(),qE=Ya(),po=Ie.setImmediate,ho=Ie.clearImmediate,UE=Ie.process,no=Ie.Dispatch,HE=Ie.Function,ph=Ie.MessageChannel,jE=Ie.String,oo=0,sr={},hh="onreadystatechange",nr,_t,uo,lo;bh(function(){nr=Ie.location});var mo=function(r){if(OE(sr,r)){var e=sr[r];delete sr[r],e()}},co=function(r){return function(){mo(r)}},mh=function(r){mo(r.data)},fh=function(r){Ie.postMessage(jE(r),nr.protocol+"//"+nr.host)};(!po||!ho)&&(po=function(e){NE(arguments.length,1);var t=lh(e)?e:HE(e),i=_E(arguments,1);return sr[++oo]=function(){VE(t,void 0,i)},_t(oo),oo},ho=function(e){delete sr[e]},qE?_t=function(r){UE.nextTick(co(r))}:no&&no.now?_t=function(r){no.now(co(r))}:ph&&!FE?(uo=new ph,lo=uo.port2,uo.port1.onmessage=mh,_t=BE(lo.postMessage,lo)):Ie.addEventListener&&lh(Ie.postMessage)&&!Ie.importScripts&&nr&&nr.protocol!=="file:"&&!bh(fh)?(_t=fh,Ie.addEventListener("message",mh,!1)):hh in dh("script")?_t=function(r){ch.appendChild(dh("script"))[hh]=function(){ch.removeChild(this),mo(r)}}:_t=function(r){setTimeout(co(r),0)});gh.exports={set:po,clear:ho}});var yh=f((EM,vh)=>{"use strict";var Sh=G(),GE=Ae(),QE=Object.getOwnPropertyDescriptor;vh.exports=function(r){if(!GE)return Sh[r];var e=QE(Sh,r);return e&&e.value}});var bo=f((xM,Ih)=>{"use strict";var Th=function(){this.head=null,this.tail=null};Th.prototype={add:function(r){var e={item:r,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var r=this.head;if(r){var e=this.head=r.next;return e===null&&(this.tail=null),r.item}}};Ih.exports=Th});var xh=f((PM,Eh)=>{"use strict";var WE=ci();Eh.exports=/ipad|iphone|ipod/i.test(WE)&&typeof Pebble<"u"});var kh=f((kM,Ph)=>{"use strict";var YE=ci();Ph.exports=/web0s(?!.*chrome)/i.test(YE)});var Dh=f((wM,Mh)=>{"use strict";var gi=G(),zE=yh(),wh=Xi(),go=fo().set,KE=bo(),XE=so(),JE=xh(),ZE=kh(),So=Ya(),Ah=gi.MutationObserver||gi.WebKitMutationObserver,Rh=gi.document,$h=gi.process,za=gi.Promise,To=zE("queueMicrotask"),bi,vo,yo,Ka,Lh;To||(or=new KE,ur=function(){var r,e;for(So&&(r=$h.domain)&&r.exit();e=or.get();)try{e()}catch(t){throw or.head&&bi(),t}r&&r.enter()},!XE&&!So&&!ZE&&Ah&&Rh?(vo=!0,yo=Rh.createTextNode(""),new Ah(ur).observe(yo,{characterData:!0}),bi=function(){yo.data=vo=!vo}):!JE&&za&&za.resolve?(Ka=za.resolve(void 0),Ka.constructor=za,Lh=wh(Ka.then,Ka),bi=function(){Lh(ur)}):So?bi=function(){$h.nextTick(ur)}:(go=wh(go,gi),bi=function(){go(ur)}),To=function(r){or.head||bi(),or.add(r)});var or,ur;Mh.exports=To});var Vh=f((AM,Ch)=>{"use strict";Ch.exports=function(r,e){try{arguments.length===1?console.error(r):console.error(r,e)}catch{}}});var Xa=f((RM,Bh)=>{"use strict";Bh.exports=function(r){try{return{error:!1,value:r()}}catch(e){return{error:!0,value:e}}}});var Nt=f(($M,Oh)=>{"use strict";var ex=G();Oh.exports=ex.Promise});var Si=f((LM,qh)=>{"use strict";var tx=G(),lr=Nt(),ix=j(),rx=Mn(),ax=io(),sx=ae(),_h=eo(),nx=Ne(),Io=dn(),Nh=lr&&lr.prototype,ox=sx("species"),Eo=!1,Fh=ix(tx.PromiseRejectionEvent),ux=rx("Promise",function(){var r=ax(lr),e=r!==String(lr);if(!e&&Io===66||nx&&!(Nh.catch&&Nh.finally))return!0;if(!Io||Io<51||!/native code/.test(r)){var t=new lr(function(s){s(1)}),i=function(s){s(function(){},function(){})},a=t.constructor={};if(a[ox]=i,Eo=t.then(function(){})instanceof i,!Eo)return!0}return!e&&(_h==="BROWSER"||_h==="DENO")&&!Fh});qh.exports={CONSTRUCTOR:ux,REJECTION_EVENT:Fh,SUBCLASSING:Eo}});var vi=f((MM,Hh)=>{"use strict";var Uh=at(),lx=TypeError,cx=function(r){var e,t;this.promise=new r(function(i,a){if(e!==void 0||t!==void 0)throw new lx("Bad Promise constructor");e=i,t=a}),this.resolve=Uh(e),this.reject=Uh(t)};Hh.exports.f=function(r){return new cx(r)}});var um=f(()=>{"use strict";var dx=Re(),px=Ne(),ts=Ya(),ft=G(),Ei=Te(),jh=fi(),Gh=Yn(),hx=er(),mx=jp(),fx=at(),es=j(),bx=we(),gx=Qp(),Sx=ao(),Kh=fo().set,Ao=Dh(),vx=Vh(),yx=Xa(),Tx=bo(),Xh=Rn(),is=Nt(),Ro=Si(),Jh=vi(),rs="Promise",Zh=Ro.CONSTRUCTOR,Ix=Ro.REJECTION_EVENT,Ex=Ro.SUBCLASSING,xo=Xh.getterFor(rs),xx=Xh.set,yi=is&&is.prototype,Ft=is,Ja=yi,em=ft.TypeError,Po=ft.document,$o=ft.process,ko=Jh.f,Px=ko,kx=!!(Po&&Po.createEvent&&ft.dispatchEvent),tm="unhandledrejection",wx="rejectionhandled",Qh=0,im=1,Ax=2,Lo=1,rm=2,Za,Wh,Rx,Yh,am=function(r){var e;return bx(r)&&es(e=r.then)?e:!1},sm=function(r,e){var t=e.value,i=e.state===im,a=i?r.ok:r.fail,s=r.resolve,n=r.reject,o=r.domain,u,l,c;try{a?(i||(e.rejection===rm&&Lx(e),e.rejection=Lo),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===r.promise?n(new em("Promise-chain cycle")):(l=am(u))?Ei(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},nm=function(r,e){r.notified||(r.notified=!0,Ao(function(){for(var t=r.reactions,i;i=t.get();)sm(i,r);r.notified=!1,e&&!r.rejection&&$x(r)}))},om=function(r,e,t){var i,a;kx?(i=Po.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(r,!1,!0),ft.dispatchEvent(i)):i={promise:e,reason:t},!Ix&&(a=ft["on"+r])?a(i):r===tm&&vx("Unhandled promise rejection",t)},$x=function(r){Ei(Kh,ft,function(){var e=r.facade,t=r.value,i=zh(r),a;if(i&&(a=yx(function(){ts?$o.emit("unhandledRejection",t,e):om(tm,e,t)}),r.rejection=ts||zh(r)?rm:Lo,a.error))throw a.value})},zh=function(r){return r.rejection!==Lo&&!r.parent},Lx=function(r){Ei(Kh,ft,function(){var e=r.facade;ts?$o.emit("rejectionHandled",e):om(wx,e,r.value)})},Ti=function(r,e,t){return function(i){r(e,i,t)}},Ii=function(r,e,t){r.done||(r.done=!0,t&&(r=t),r.value=e,r.state=Ax,nm(r,!0))},wo=function(r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(r.facade===e)throw new em("Promise can't be resolved itself");var i=am(e);i?Ao(function(){var a={done:!1};try{Ei(i,e,Ti(wo,a,r),Ti(Ii,a,r))}catch(s){Ii(a,s,r)}}):(r.value=e,r.state=im,nm(r,!1))}catch(a){Ii({done:!1},a,r)}}};if(Zh&&(Ft=function(e){gx(this,Ja),fx(e),Ei(Za,this);var t=xo(this);try{e(Ti(wo,t),Ti(Ii,t))}catch(i){Ii(t,i)}},Ja=Ft.prototype,Za=function(e){xx(this,{type:rs,done:!1,notified:!1,parent:!1,reactions:new Tx,rejection:!1,state:Qh,value:void 0})},Za.prototype=jh(Ja,"then",function(e,t){var i=xo(this),a=ko(Sx(this,Ft));return i.parent=!0,a.ok=es(e)?e:!0,a.fail=es(t)&&t,a.domain=ts?$o.domain:void 0,i.state===Qh?i.reactions.add(a):Ao(function(){sm(a,i)}),a.promise}),Wh=function(){var r=new Za,e=xo(r);this.promise=r,this.resolve=Ti(wo,e),this.reject=Ti(Ii,e)},Jh.f=ko=function(r){return r===Ft||r===Rx?new Wh(r):Px(r)},!px&&es(is)&&yi!==Object.prototype)){Yh=yi.then,Ex||jh(yi,"then",function(e,t){var i=this;return new Ft(function(a,s){Ei(Yh,i,a,s)}).then(e,t)},{unsafe:!0});try{delete yi.constructor}catch{}Gh&&Gh(yi,Ja)}dx({global:!0,constructor:!0,wrap:!0,forced:Zh},{Promise:Ft});hx(Ft,rs,!1,!0);mx(rs)});var hm=f((VM,pm)=>{"use strict";var Mx=ae(),cm=Mx("iterator"),dm=!1;try{lm=0,Mo={next:function(){return{done:!!lm++}},return:function(){dm=!0}},Mo[cm]=function(){return this},Array.from(Mo,function(){throw 2})}catch{}var lm,Mo;pm.exports=function(r,e){try{if(!e&&!dm)return!1}catch{return!1}var t=!1;try{var i={};i[cm]=function(){return{next:function(){return{done:t=!0}}}},r(i)}catch{}return t}});var Do=f((BM,mm)=>{"use strict";var Dx=Nt(),Cx=hm(),Vx=Si().CONSTRUCTOR;mm.exports=Vx||!Cx(function(r){Dx.all(r).then(void 0,function(){})})});var fm=f(()=>{"use strict";var Bx=Re(),Ox=Te(),_x=at(),Nx=vi(),Fx=Xa(),qx=Ga(),Ux=Do();Bx({target:"Promise",stat:!0,forced:Ux},{all:function(e){var t=this,i=Nx.f(t),a=i.resolve,s=i.reject,n=Fx(function(){var o=_x(t.resolve),u=[],l=0,c=1;qx(e,function(d){var p=l++,h=!1;c++,Ox(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),i.promise}})});var gm=f(()=>{"use strict";var Hx=Re(),jx=Ne(),Gx=Si().CONSTRUCTOR,Vo=Nt(),Qx=rt(),Wx=j(),Yx=fi(),bm=Vo&&Vo.prototype;Hx({target:"Promise",proto:!0,forced:Gx,real:!0},{catch:function(r){return this.then(void 0,r)}});!jx&&Wx(Vo)&&(Co=Qx("Promise").prototype.catch,bm.catch!==Co&&Yx(bm,"catch",Co,{unsafe:!0}));var Co});var Sm=f(()=>{"use strict";var zx=Re(),Kx=Te(),Xx=at(),Jx=vi(),Zx=Xa(),eP=Ga(),tP=Do();zx({target:"Promise",stat:!0,forced:tP},{race:function(e){var t=this,i=Jx.f(t),a=i.reject,s=Zx(function(){var n=Xx(t.resolve);eP(e,function(o){Kx(n,t,o).then(i.resolve,a)})});return s.error&&a(s.value),i.promise}})});var vm=f(()=>{"use strict";var iP=Re(),rP=vi(),aP=Si().CONSTRUCTOR;iP({target:"Promise",stat:!0,forced:aP},{reject:function(e){var t=rP.f(this),i=t.reject;return i(e),t.promise}})});var Bo=f((GM,ym)=>{"use strict";var sP=ze(),nP=we(),oP=vi();ym.exports=function(r,e){if(sP(r),nP(e)&&e.constructor===r)return e;var t=oP.f(r),i=t.resolve;return i(e),t.promise}});var Em=f(()=>{"use strict";var uP=Re(),lP=rt(),Tm=Ne(),cP=Nt(),Im=Si().CONSTRUCTOR,dP=Bo(),pP=lP("Promise"),hP=Tm&&!Im;uP({target:"Promise",stat:!0,forced:Tm||Im},{resolve:function(e){return dP(hP&&this===pP?cP:this,e)}})});var xm=f(()=>{"use strict";um();fm();gm();Sm();vm();Em()});var Am=f(()=>{"use strict";var mP=Re(),fP=Ne(),as=Nt(),bP=ye(),km=rt(),wm=j(),gP=ao(),Pm=Bo(),SP=fi(),_o=as&&as.prototype,vP=!!as&&bP(function(){_o.finally.call({then:function(){}},function(){})});mP({target:"Promise",proto:!0,real:!0,forced:vP},{finally:function(r){var e=gP(this,km("Promise")),t=wm(r);return this.then(t?function(i){return Pm(e,r()).then(function(){return i})}:r,t?function(i){return Pm(e,r()).then(function(){throw i})}:r)}});!fP&&wm(as)&&(Oo=km("Promise").prototype.finally,_o.finally!==Oo&&SP(_o,"finally",Oo,{unsafe:!0}));var Oo});var ss=f((JM,Rm)=>{"use strict";var yP=rt();Rm.exports=yP});var Lm=f((ZM,$m)=>{"use strict";Op();xm();Am();var TP=ss();$m.exports=TP("Promise","finally")});var Dm=f((eD,Mm)=>{"use strict";var IP=Lm();Mm.exports=IP});var ns=f((tD,Cm)=>{"use strict";var EP=Dm();Cm.exports=EP});var nf=f(()=>{"use strict";var JP=Re(),ZP=Wi(),ek=Ba(),tk=Va(),ik=tn();JP({target:"Array",proto:!0},{at:function(e){var t=ZP(this),i=ek(t),a=tk(e),s=a>=0?a:i+a;return s<0||s>=i?void 0:t[s]}});ik("at")});var uf=f((cC,of)=>{"use strict";nf();var rk=ss();of.exports=rk("Array","at")});var cf=f((dC,lf)=>{"use strict";var ak=uf();lf.exports=ak});var ki=f((pC,df)=>{"use strict";var sk=cf();df.exports=sk});var nb=f(()=>{"use strict"});var ob=f(()=>{"use strict"});var lb=f((bO,ub)=>{"use strict";var mw=we(),fw=oi(),bw=ae(),gw=bw("match");ub.exports=function(r){var e;return mw(r)&&((e=r[gw])!==void 0?!!e:fw(r)==="RegExp")}});var db=f((gO,cb)=>{"use strict";var Sw=Zi(),vw=String;cb.exports=function(r){if(Sw(r)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return vw(r)}});var hb=f((SO,pb)=>{"use strict";var yw=ze();pb.exports=function(){var r=yw(this),e="";return r.hasIndices&&(e+="d"),r.global&&(e+="g"),r.ignoreCase&&(e+="i"),r.multiline&&(e+="m"),r.dotAll&&(e+="s"),r.unicode&&(e+="u"),r.unicodeSets&&(e+="v"),r.sticky&&(e+="y"),e}});var bb=f((vO,fb)=>{"use strict";var Tw=Te(),Iw=Fe(),Ew=Hi(),xw=hb(),mb=RegExp.prototype;fb.exports=function(r){var e=r.flags;return e===void 0&&!("flags"in mb)&&!Iw(r,"flags")&&Ew(mb,r)?Tw(xw,r):e}});var Sb=f((yO,gb)=>{"use strict";var fu=le(),Pw=Wi(),kw=Math.floor,hu=fu("".charAt),ww=fu("".replace),mu=fu("".slice),Aw=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Rw=/\$([$&'`]|\d{1,2})/g;gb.exports=function(r,e,t,i,a,s){var n=t+r.length,o=i.length,u=Rw;return a!==void 0&&(a=Pw(a),u=Aw),ww(s,u,function(l,c){var d;switch(hu(c,0)){case"$":return"$";case"&":return r;case"`":return mu(e,0,t);case"'":return mu(e,n);case"<":d=a[mu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=kw(p/10);return h===0?l:h<=o?i[h-1]===void 0?hu(c,1):i[h-1]+hu(c,1):l}d=i[p-1]}return d===void 0?"":d})}});var Tb=f(()=>{"use strict";var $w=Re(),Lw=Te(),gu=le(),vb=qi(),Mw=j(),Dw=ui(),Cw=lb(),Mi=db(),Vw=Gi(),Bw=bb(),Ow=Sb(),_w=ae(),Nw=Ne(),Fw=_w("replace"),qw=TypeError,bu=gu("".indexOf),Uw=gu("".replace),yb=gu("".slice),Hw=Math.max;$w({target:"String",proto:!0},{replaceAll:function(e,t){var i=vb(this),a,s,n,o,u,l,c,d,p,h,m=0,b="";if(!Dw(e)){if(a=Cw(e),a&&(s=Mi(vb(Bw(e))),!~bu(s,"g")))throw new qw("`.replaceAll` does not allow non-global regexes");if(n=Vw(e,Fw),n)return Lw(n,e,i,t);if(Nw&&a)return Uw(Mi(i),e,t)}for(o=Mi(i),u=Mi(e),l=Mw(t),l||(t=Mi(t)),c=u.length,d=Hw(1,c),p=bu(o,u);p!==-1;)h=l?Mi(t(u,p,o)):Ow(u,o,p,[],void 0,t),b+=yb(o,m,p)+h,m=p+c,p=p+d>o.length?-1:bu(o,u,p+d);return m<o.length&&(b+=yb(o,m)),b}})});var Eb=f((EO,Ib)=>{"use strict";nb();ob();Tb();var jw=ss();Ib.exports=jw("String","replaceAll")});var Pb=f((xO,xb)=>{"use strict";var Gw=Eb();xb.exports=Gw});var wb=f((PO,kb)=>{"use strict";var Qw=Pb();kb.exports=Qw});var el="2.0.117-dev.d9cc3d97.0";var ue=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(ue||{}),mt=(I=>(I.MPEG="MPEG",I.DASH="DASH",I.DASH_SEP="DASH_SEP",I.DASH_SEP_VK="DASH_SEP",I.DASH_WEBM="DASH_WEBM",I.DASH_WEBM_AV1="DASH_WEBM_AV1",I.DASH_STREAMS="DASH_STREAMS",I.DASH_WEBM_VK="DASH_WEBM",I.DASH_ONDEMAND="DASH_ONDEMAND",I.DASH_ONDEMAND_VK="DASH_ONDEMAND",I.DASH_LIVE="DASH_LIVE",I.DASH_LIVE_CMAF="DASH_LIVE_CMAF",I.DASH_LIVE_WEBM="DASH_LIVE_WEBM",I.HLS="HLS",I.HLS_ONDEMAND="HLS_ONDEMAND",I.HLS_JS="HLS",I.HLS_LIVE="HLS_LIVE",I.HLS_LIVE_CMAF="HLS_LIVE_CMAF",I.WEB_RTC_LIVE="WEB_RTC_LIVE",I))(mt||{});var Ea=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Ea||{}),zs=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(zs||{});var Ks=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ks||{});import{assertNever as nl,assertNonNullable as lS,isNonNullable as xa,ValueSubject as Xs,Subject as cS,Subscription as dS,merge as pS,observableFrom as hS,fromEvent as il,map as rl,tap as al,filterChanged as mS,isNullable as Js,ErrorCategory as sl}from"@vkontakte/videoplayer-shared";var tl=r=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",r),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Pa=class{constructor(e){this.connection$=new Xs(void 0);this.castState$=new Xs("NOT_AVAILABLE");this.errorEvent$=new cS;this.realCastState$=new Xs("NOT_AVAILABLE");this.subscription=new dS;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=xa(window.chrome?.cast),a=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||tl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:sl.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(){xa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Js(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Js(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(il(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.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 nl(a.sessionState)}})).add(pS(il(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(al(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),rl(a=>a.castState)),hS([i.getCastState()])).pipe(mS(),rl(fS),al(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=xa(this.connection$.getValue());if(s&&!n){let o=i.getCurrentSession();lS(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(Js(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?xa(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}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(a){this.errorEvent$.next({id:"ChromecastInitializer",category:sl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},fS=r=>{switch(r){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 nl(r)}};var Cg=Oe(Zn(),1);var jm=Oe(ns(),1);import{assertNever as Vm}from"@vkontakte/videoplayer-shared";var te=(r,e=0,t=0)=>{switch(t){case 0:return r.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return r;let i=new URL(r);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(r);return!i.searchParams.get("offset_p")&&e===0?r:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:Vm(t)}return r},No=(r,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(r);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(r);return Number(t.searchParams.get("offset_p")??0)}default:Vm(e)}};var x=(r,e,t=!1)=>{let i=r.getTransition();(t||!i||i.to===e)&&r.setState(e)};import{isNonNullable as xP,Subject as os,merge as Bm}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new os;this.transitionEnded$=new os;this.transitionUpdated$=new os;this.forceChanged$=new os;this.stateChangeStarted$=Bm(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Bm(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||xP(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as PP}from"@vkontakte/videoplayer-shared";var Om=r=>{switch(r){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return PP(r)}};import{assertNever as xi,assertNonNullable as qt,debounce as _m,ErrorCategory as Nm,fromEvent as Ut,isNonNullable as Fm,map as qm,merge as Um,observableFrom as kP,Subject as wP,Subscription as Fo,timeout as AP,getHighestQuality as RP}from"@vkontakte/videoplayer-shared";var $P=5,LP=5,MP=500,Hm=7e3,cr=class{constructor(e){this.subscription=new Fo;this.loadMediaTimeoutSubscription=new Fo;this.videoState=new $("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),a=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(a?.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:xi(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:xi(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:xi(e)}break}default:xi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Om(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 Fo;this.subscription.add(e),this.subscription.add(Um(this.videoState.stateChangeStarted$.pipe(qm(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(qm(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new wP;e.add(a.pipe(_m(MP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>$P)&&a.next(o),s=o})),e.add(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<LP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(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:xi(n)}}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Ut(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let i=Um(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,kP(["init"])).pipe(_m(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"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(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"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&x(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,a,s;switch(e){case"MPEG":{let l=t[e];qt(l);let c=RP(Object.keys(l));qt(c);let d=l[c];qt(d),i=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];qt(l),i=l.url,a="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];qt(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];qt(l),i=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];qt(l),i=te(l.url),a="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:Nm.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return xi(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??i,a);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Fm(o)&&(n.metadata.title=o),Fm(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(AP(Hm).subscribe(()=>s(`timeout(${Hm})`)))});(0,jm.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()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Nm.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};import{clearVideoElement as Qm}from"@vkontakte/videoplayer-shared";import{clearVideoElement as DP}from"@vkontakte/videoplayer-shared";var Gm=r=>{try{r.pause(),r.playbackRate=0,DP(r),r.remove()}catch(e){console.error(e)}};import{fromEvent as CP,Subscription as VP}from"@vkontakte/videoplayer-shared";var qo=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)}},Uo=window.WeakMap?new WeakMap:new qo,Ho=window.WeakMap?new WeakMap:new Map,BP=(r,e=20)=>{let t=0;return CP(r,"ratechange").subscribe(i=>{t++,t>=e&&(r.currentTime=r.currentTime,t=0)})},ce=(r,{audioVideoSyncRate:e})=>{let t=r.querySelector("video"),i=!!t;t?Qm(t):(t=document.createElement("video"),r.appendChild(t)),Uo.set(t,i);let a=new VP;return a.add(BP(t,e)),Ho.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},de=r=>{Ho.get(r)?.unsubscribe(),Ho.delete(r);let t=Uo.get(r);Uo.delete(r),t?Qm(r):Gm(r)};import{assertNonNullable as dr,isNonNullable as Xe,isNullable as NP,fromEvent as Pi,merge as Wm,observableFrom as Ym,filterChanged as zm,map as pr,Subject as Km,Subscription as FP,ValueSubject as qP,ErrorCategory as UP}from"@vkontakte/videoplayer-shared";import{isNonNullable as jo,isNullable as OP,Subscription as _P}from"@vkontakte/videoplayer-shared";var us=(r,e,t,{equal:i=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=r.getState(),o=e(),u=OP(a),l=new _P;return a&&l.add(a.subscribe(c=>{let d=r.getState();i(c,d)&&r.setState(c)},s)),i(o,n)||(t(n),u&&r.setState(n)),l.add(r.stateChangeStarted$.subscribe(c=>{t(c.to),u&&r.setState(c.to)},s)),l},Ke=(r,e,t)=>us(e,()=>r.loop,i=>{jo(i)&&(r.loop=i)},{onError:t}),pe=(r,e,t,i)=>us(e,()=>({muted:r.muted,volume:r.volume}),a=>{jo(a)&&(r.muted=a.muted,r.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:i}),$e=(r,e,t,i)=>us(e,()=>r.playbackRate,a=>{jo(a)&&(r.playbackRate=a)},{changed$:t,onError:i}),bt=us;var HP=r=>["__",r.language,r.label].join("|"),jP=(r,e)=>{if(r.id===e)return!0;let[t,i,a]=e.split("|");return r.language===i&&r.label===a},Go=class r{constructor(){this.available$=new Km;this.current$=new qP(void 0);this.error$=new Km;this.subscription=new FP;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:UP.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(bt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Xe(s)&&this.setInternal(s)},{equal:(s,n)=>Xe(s)&&Xe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(pr(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(bt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Xe(s)&&this.setExternal(s)},{equal:(s,n)=>Xe(s)&&Xe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(pr(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(bt(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:a})),this.subscription.add(bt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){dr(this.video);let{textTracks:e}=this.video;this.subscription.add(Pi(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Wm(Pi(e,"addtrack"),Pi(e,"removetrack"),Ym(["init"])).pipe(pr(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),zm((i,a)=>i.length===a.length&&i.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Wm(Pi(e,"change"),Ym(["init"])).pipe(pr(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),pr(i=>i&&this.htmlTextTrackToITextTrack(i).id),zm()).subscribe(this.current$));let t=i=>this.applyCueSettings(i.target?.activeCues??null);this.subscription.add(Pi(e,"addtrack").subscribe(i=>{i.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};i.track?.addEventListener("cuechange",a)})),this.subscription.add(Pi(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 a=i;Xe(t.align)&&(a.align=t.align),Xe(t.position)&&(a.position=t.position),Xe(t.size)&&(a.size=t.size),Xe(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){dr(this.video);let t=[...this.video.textTracks];return e?t:t.filter(r.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:i}=e,a=e.id?e.id:HP(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)??a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(a)?.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:a,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}select(e){dr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(NP(e)||!jP(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){dr(this.video);let t=document.createElement("track");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){dr(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)}},Le=Go;var ot=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 Xm=r=>{let e=r;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Qo=r=>{let e=Xm(r);return!!(e&&e.fullscreenElement&&e.fullscreenElement===r)},Jm=r=>{let e=Xm(r);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===r)};import{fromEvent as Me,map as gt,merge as ef,filterChanged as QP,isNonNullable as tf,Subject as WP,filter as rf,mapTo as af,combine as YP,once as zP,ErrorCategory as KP,ValueSubject as sf,clientChecker as XP}from"@vkontakte/videoplayer-shared";var GP=3,Zm=(r,e,t=GP)=>{let i=0,a=0;for(let s=0;s<r.length;s++){let n=r.start(s),o=r.end(s);if(n<=e&&e<=o){if(i=n,a=o,!t)return{from:i,to:a};for(let u=s-1;u>=0;u--)r.end(u)+t>=i&&(i=r.start(u));for(let u=s+1;u<r.length;u++)r.start(u)-t<=a&&(a=r.end(u))}}return{from:i,to:a}};var he=r=>{let e=I=>Me(r,I).pipe(af(void 0)),i=ef(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(I=>Me(r,I))).pipe(gt(I=>I.type==="ended"?r.readyState<2:r.readyState<3),QP()),a=ef(Me(r,"progress"),Me(r,"timeupdate")).pipe(gt(()=>Zm(r.buffered,r.currentTime))),s=XP.isSafari?YP({play:e("play").pipe(zP()),playing:e("playing")}).pipe(af(void 0)):e("playing"),n=Me(r,"volumechange").pipe(gt(()=>({muted:r.muted,volume:r.volume}))),o=Me(r,"ratechange").pipe(gt(()=>r.playbackRate)),u=Me(r,"error").pipe(rf(()=>!!(r.error||r.played.length)),gt(()=>{let I=r.error;return{id:I?`MediaError#${I.code}`:"HtmlVideoError",category:KP.VIDEO_PIPELINE,message:I?I.message:"Error event from HTML video element",thrown:r.error??void 0}})),l=Me(r,"timeupdate").pipe(gt(()=>r.currentTime)),c=new WP,d=.3,p;l.subscribe(I=>{r.loop&&tf(p)&&tf(I)&&p>=r.duration-d&&I<=d&&c.next(p),p=I});let h=e("pause").pipe(rf(()=>!r.error&&p!==r.duration)),m=Me(r,"enterpictureinpicture"),b=Me(r,"leavepictureinpicture"),g=new sf(Jm(r));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new sf(Qo(r));return Me(r,"fullscreenchange").pipe(gt(()=>Qo(r))).subscribe(S),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Me(r,"durationchange").pipe(gt(()=>r.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as St}from"@vkontakte/videoplayer-shared";var vt=r=>{switch(r){case"mobile":return St.Q_144P;case"lowest":return St.Q_240P;case"low":return St.Q_360P;case"sd":case"medium":return St.Q_480P;case"hd":case"high":return St.Q_720P;case"fullhd":case"full":return St.Q_1080P;case"quadhd":case"quad":return St.Q_1440P;case"ultrahd":case"ultra":return St.Q_2160P}};var yt=Oe(ki(),1);import{isNonNullable as z,isNullable as Yo,now as Sf,isHigher as zo,isHigherOrEqual as Ko,isInvariantQuality as ff,isLower as bf,isLowerOrEqual as Xo,videoSizeToQuality as nk,assertNotEmptyArray as vf,assertNonNullable as ok}from"@vkontakte/videoplayer-shared";var Wo=!1,ut={},pf=r=>{Wo=r},hf=()=>{ut={}},mf=r=>{r(ut)},hr=(r,e)=>{Wo&&(ut.meta=ut.meta??{},ut.meta[r]=e)},se=class{constructor(e){this.name=e}next(e){if(!Wo)return;ut.series=ut.series??{};let t=ut.series[this.name]??[];t.push([Date.now(),e]),ut.series[this.name]=t}};var uk=new se("best_bitrate"),yf=(r,e,t)=>(e-t)*Math.pow(2,-10*r)+t;var Jo=r=>(e,t)=>r*(Number(e.bitrate)-Number(t.bitrate)),mr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Sf()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Tf='Assertion "ABR Tracks is empty array" failed',ls=(r,e,t,i)=>{let a=[...e].sort(Jo(1)),s=[...t].sort(Jo(1)),n=s.filter(u=>z(u.bitrate)&&z(r.bitrate)?r.bitrate/u.bitrate>i:!0),o=(0,yt.default)(s,Math.round(s.length*a.indexOf(r)/(a.length+1)))??(0,yt.default)(s,-1);return o&&n.includes(o)?o:n.length?(0,yt.default)(n,-1):(0,yt.default)(s,0)},gf=r=>"quality"in r,If=(r,e,t,i)=>{let a=z(i?.last?.bitrate)&&z(t?.bitrate)&&i.last.bitrate<t.bitrate?r.trackCooldownIncreaseQuality:r.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&Sf()-i.history[t.id]<=a&&(!i.last||t.id!==i.last.id);if(t?.id&&i&&!s&&i.recordSelection(t),s&&i?.last){let n=i.last;i?.recordSwitch(n);let o=gf(n)?"video":"audio",u=gf(n)?n.quality:n.bitrate;return e({message:`
|
|
6
|
+
var uy=Object.create;var Rl=Object.defineProperty;var ly=Object.getOwnPropertyDescriptor;var cy=Object.getOwnPropertyNames;var dy=Object.getPrototypeOf,py=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var hy=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of cy(e))!py.call(i,a)&&a!==t&&Rl(i,a,{get:()=>e[a],enumerable:!(r=ly(e,a))||r.enumerable});return i};var $=(i,e,t)=>(t=i!=null?uy(dy(i)):{},hy(e||!i||!i.__esModule?Rl(t,"default",{value:i,enumerable:!0}):t,i));var Q=m((hn,Ll)=>{"use strict";var Jr=function(i){return i&&i.Math===Math&&i};Ll.exports=Jr(typeof globalThis=="object"&&globalThis)||Jr(typeof window=="object"&&window)||Jr(typeof self=="object"&&self)||Jr(typeof global=="object"&&global)||Jr(typeof hn=="object"&&hn)||function(){return this}()||Function("return this")()});var ie=m((MC,Ml)=>{"use strict";Ml.exports=function(i){try{return!!i()}catch{return!0}}});var Xr=m((CC,Cl)=>{"use strict";var my=ie();Cl.exports=!my(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var mn=m((DC,Bl)=>{"use strict";var fy=Xr(),Vl=Function.prototype,Dl=Vl.apply,Ol=Vl.call;Bl.exports=typeof Reflect=="object"&&Reflect.apply||(fy?Ol.bind(Dl):function(){return Ol.apply(Dl,arguments)})});var J=m((OC,Fl)=>{"use strict";var _l=Xr(),Nl=Function.prototype,fn=Nl.call,by=_l&&Nl.bind.bind(fn,fn);Fl.exports=_l?by:function(i){return function(){return fn.apply(i,arguments)}}});var Ut=m((VC,Ul)=>{"use strict";var ql=J(),gy=ql({}.toString),Sy=ql("".slice);Ul.exports=function(i){return Sy(gy(i),8,-1)}});var bn=m((BC,Hl)=>{"use strict";var vy=Ut(),yy=J();Hl.exports=function(i){if(vy(i)==="Function")return yy(i)}});var G=m((_C,jl)=>{"use strict";var gn=typeof document=="object"&&document.all;jl.exports=typeof gn>"u"&&gn!==void 0?function(i){return typeof i=="function"||i===gn}:function(i){return typeof i=="function"}});var Ie=m((NC,Gl)=>{"use strict";var Ty=ie();Gl.exports=!Ty(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ee=m((FC,Ql)=>{"use strict";var Iy=Xr(),_a=Function.prototype.call;Ql.exports=Iy?_a.bind(_a):function(){return _a.apply(_a,arguments)}});var Sn=m(zl=>{"use strict";var Wl={}.propertyIsEnumerable,Yl=Object.getOwnPropertyDescriptor,Ey=Yl&&!Wl.call({1:2},1);zl.f=Ey?function(e){var t=Yl(this,e);return!!t&&t.enumerable}:Wl});var Zr=m((UC,Kl)=>{"use strict";Kl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Xl=m((HC,Jl)=>{"use strict";var xy=J(),Py=ie(),ky=Ut(),vn=Object,Ay=xy("".split);Jl.exports=Py(function(){return!vn("z").propertyIsEnumerable(0)})?function(i){return ky(i)==="String"?Ay(i,""):vn(i)}:vn});var br=m((jC,Zl)=>{"use strict";Zl.exports=function(i){return i==null}});var yt=m((GC,ec)=>{"use strict";var wy=br(),Ry=TypeError;ec.exports=function(i){if(wy(i))throw new Ry("Can't call method on "+i);return i}});var Ht=m((QC,tc)=>{"use strict";var $y=Xl(),Ly=yt();tc.exports=function(i){return $y(Ly(i))}});var xe=m((WC,rc)=>{"use strict";var My=G();rc.exports=function(i){return typeof i=="object"?i!==null:My(i)}});var gr=m((YC,ic)=>{"use strict";ic.exports={}});var st=m((zC,sc)=>{"use strict";var yn=gr(),Tn=Q(),Cy=G(),ac=function(i){return Cy(i)?i:void 0};sc.exports=function(i,e){return arguments.length<2?ac(yn[i])||ac(Tn[i]):yn[i]&&yn[i][e]||Tn[i]&&Tn[i][e]}});var ei=m((KC,nc)=>{"use strict";var Dy=J();nc.exports=Dy({}.isPrototypeOf)});var jt=m((JC,lc)=>{"use strict";var Oy=Q(),oc=Oy.navigator,uc=oc&&oc.userAgent;lc.exports=uc?String(uc):""});var En=m((XC,fc)=>{"use strict";var mc=Q(),In=jt(),cc=mc.process,dc=mc.Deno,pc=cc&&cc.versions||dc&&dc.version,hc=pc&&pc.v8,_e,Na;hc&&(_e=hc.split("."),Na=_e[0]>0&&_e[0]<4?1:+(_e[0]+_e[1]));!Na&&In&&(_e=In.match(/Edge\/(\d+)/),(!_e||_e[1]>=74)&&(_e=In.match(/Chrome\/(\d+)/),_e&&(Na=+_e[1])));fc.exports=Na});var xn=m((ZC,gc)=>{"use strict";var bc=En(),Vy=ie(),By=Q(),_y=By.String;gc.exports=!!Object.getOwnPropertySymbols&&!Vy(function(){var i=Symbol("symbol detection");return!_y(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&bc&&bc<41})});var Pn=m((e0,Sc)=>{"use strict";var Ny=xn();Sc.exports=Ny&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var kn=m((t0,vc)=>{"use strict";var Fy=st(),qy=G(),Uy=ei(),Hy=Pn(),jy=Object;vc.exports=Hy?function(i){return typeof i=="symbol"}:function(i){var e=Fy("Symbol");return qy(e)&&Uy(e.prototype,jy(i))}});var ti=m((r0,yc)=>{"use strict";var Gy=String;yc.exports=function(i){try{return Gy(i)}catch{return"Object"}}});var Ye=m((i0,Tc)=>{"use strict";var Qy=G(),Wy=ti(),Yy=TypeError;Tc.exports=function(i){if(Qy(i))return i;throw new Yy(Wy(i)+" is not a function")}});var ri=m((a0,Ic)=>{"use strict";var zy=Ye(),Ky=br();Ic.exports=function(i,e){var t=i[e];return Ky(t)?void 0:zy(t)}});var xc=m((s0,Ec)=>{"use strict";var An=Ee(),wn=G(),Rn=xe(),Jy=TypeError;Ec.exports=function(i,e){var t,r;if(e==="string"&&wn(t=i.toString)&&!Rn(r=An(t,i))||wn(t=i.valueOf)&&!Rn(r=An(t,i))||e!=="string"&&wn(t=i.toString)&&!Rn(r=An(t,i)))return r;throw new Jy("Can't convert object to primitive value")}});var Ne=m((n0,Pc)=>{"use strict";Pc.exports=!0});var wc=m((o0,Ac)=>{"use strict";var kc=Q(),Xy=Object.defineProperty;Ac.exports=function(i,e){try{Xy(kc,i,{value:e,configurable:!0,writable:!0})}catch{kc[i]=e}return e}});var ii=m((u0,Lc)=>{"use strict";var Zy=Ne(),eT=Q(),tT=wc(),Rc="__core-js_shared__",$c=Lc.exports=eT[Rc]||tT(Rc,{});($c.versions||($c.versions=[])).push({version:"3.38.0",mode:Zy?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var $n=m((l0,Cc)=>{"use strict";var Mc=ii();Cc.exports=function(i,e){return Mc[i]||(Mc[i]=e||{})}});var Sr=m((c0,Dc)=>{"use strict";var rT=yt(),iT=Object;Dc.exports=function(i){return iT(rT(i))}});var Fe=m((d0,Oc)=>{"use strict";var aT=J(),sT=Sr(),nT=aT({}.hasOwnProperty);Oc.exports=Object.hasOwn||function(e,t){return nT(sT(e),t)}});var Ln=m((p0,Vc)=>{"use strict";var oT=J(),uT=0,lT=Math.random(),cT=oT(1 .toString);Vc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+cT(++uT+lT,36)}});var ae=m((h0,_c)=>{"use strict";var dT=Q(),pT=$n(),Bc=Fe(),hT=Ln(),mT=xn(),fT=Pn(),vr=dT.Symbol,Mn=pT("wks"),bT=fT?vr.for||vr:vr&&vr.withoutSetter||hT;_c.exports=function(i){return Bc(Mn,i)||(Mn[i]=mT&&Bc(vr,i)?vr[i]:bT("Symbol."+i)),Mn[i]}});var Uc=m((m0,qc)=>{"use strict";var gT=Ee(),Nc=xe(),Fc=kn(),ST=ri(),vT=xc(),yT=ae(),TT=TypeError,IT=yT("toPrimitive");qc.exports=function(i,e){if(!Nc(i)||Fc(i))return i;var t=ST(i,IT),r;if(t){if(e===void 0&&(e="default"),r=gT(t,i,e),!Nc(r)||Fc(r))return r;throw new TT("Can't convert object to primitive value")}return e===void 0&&(e="number"),vT(i,e)}});var Cn=m((f0,Hc)=>{"use strict";var ET=Uc(),xT=kn();Hc.exports=function(i){var e=ET(i,"string");return xT(e)?e:e+""}});var Fa=m((b0,Gc)=>{"use strict";var PT=Q(),jc=xe(),Dn=PT.document,kT=jc(Dn)&&jc(Dn.createElement);Gc.exports=function(i){return kT?Dn.createElement(i):{}}});var On=m((g0,Qc)=>{"use strict";var AT=Ie(),wT=ie(),RT=Fa();Qc.exports=!AT&&!wT(function(){return Object.defineProperty(RT("div"),"a",{get:function(){return 7}}).a!==7})});var zc=m(Yc=>{"use strict";var $T=Ie(),LT=Ee(),MT=Sn(),CT=Zr(),DT=Ht(),OT=Cn(),VT=Fe(),BT=On(),Wc=Object.getOwnPropertyDescriptor;Yc.f=$T?Wc:function(e,t){if(e=DT(e),t=OT(t),BT)try{return Wc(e,t)}catch{}if(VT(e,t))return CT(!LT(MT.f,e,t),e[t])}});var Vn=m((v0,Kc)=>{"use strict";var _T=ie(),NT=G(),FT=/#|\.prototype\./,ai=function(i,e){var t=UT[qT(i)];return t===jT?!0:t===HT?!1:NT(e)?_T(e):!!e},qT=ai.normalize=function(i){return String(i).replace(FT,".").toLowerCase()},UT=ai.data={},HT=ai.NATIVE="N",jT=ai.POLYFILL="P";Kc.exports=ai});var yr=m((y0,Xc)=>{"use strict";var Jc=bn(),GT=Ye(),QT=Xr(),WT=Jc(Jc.bind);Xc.exports=function(i,e){return GT(i),e===void 0?i:QT?WT(i,e):function(){return i.apply(e,arguments)}}});var Bn=m((T0,Zc)=>{"use strict";var YT=Ie(),zT=ie();Zc.exports=YT&&zT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=m((I0,ed)=>{"use strict";var KT=xe(),JT=String,XT=TypeError;ed.exports=function(i){if(KT(i))return i;throw new XT(JT(i)+" is not an object")}});var Gt=m(rd=>{"use strict";var ZT=Ie(),eI=On(),tI=Bn(),qa=ze(),td=Cn(),rI=TypeError,_n=Object.defineProperty,iI=Object.getOwnPropertyDescriptor,Nn="enumerable",Fn="configurable",qn="writable";rd.f=ZT?tI?function(e,t,r){if(qa(e),t=td(t),qa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&qn in r&&!r[qn]){var a=iI(e,t);a&&a[qn]&&(e[t]=r.value,r={configurable:Fn in r?r[Fn]:a[Fn],enumerable:Nn in r?r[Nn]:a[Nn],writable:!1})}return _n(e,t,r)}:_n:function(e,t,r){if(qa(e),t=td(t),qa(r),eI)try{return _n(e,t,r)}catch{}if("get"in r||"set"in r)throw new rI("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Tr=m((x0,id)=>{"use strict";var aI=Ie(),sI=Gt(),nI=Zr();id.exports=aI?function(i,e,t){return sI.f(i,e,nI(1,t))}:function(i,e,t){return i[e]=t,i}});var z=m((P0,sd)=>{"use strict";var si=Q(),oI=mn(),uI=bn(),lI=G(),cI=zc().f,dI=Vn(),Ir=gr(),pI=yr(),Er=Tr(),ad=Fe();ii();var hI=function(i){var e=function(t,r,a){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,a)}return oI(i,this,arguments)};return e.prototype=i.prototype,e};sd.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?si:a?si[t]:si[t]&&si[t].prototype,o=r?Ir:Ir[t]||Er(Ir,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=dI(r?p:t+(a?".":"#")+p,i.forced),c=!l&&n&&ad(n,p),f=o[p],c&&(i.dontCallGetSet?(S=cI(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(i.bind&&c?g=pI(h,si):i.wrap&&c?g=hI(h):s&&lI(h)?g=uI(h):g=h,(i.sham||h&&h.sham||f&&f.sham)&&Er(g,"sham",!0),Er(o,p,g),s&&(d=t+"Prototype",ad(Ir,d)||Er(Ir,d,{}),Er(Ir[d],p,h),i.real&&u&&(l||!u[p])&&Er(u,p,h)))}});var od=m((k0,nd)=>{"use strict";var mI=Math.ceil,fI=Math.floor;nd.exports=Math.trunc||function(e){var t=+e;return(t>0?fI:mI)(t)}});var ni=m((A0,ud)=>{"use strict";var bI=od();ud.exports=function(i){var e=+i;return e!==e||e===0?0:bI(e)}});var cd=m((w0,ld)=>{"use strict";var gI=ni(),SI=Math.max,vI=Math.min;ld.exports=function(i,e){var t=gI(i);return t<0?SI(t+e,0):vI(t,e)}});var Un=m((R0,dd)=>{"use strict";var yI=ni(),TI=Math.min;dd.exports=function(i){var e=yI(i);return e>0?TI(e,9007199254740991):0}});var xr=m(($0,pd)=>{"use strict";var II=Un();pd.exports=function(i){return II(i.length)}});var Hn=m((L0,md)=>{"use strict";var EI=Ht(),xI=cd(),PI=xr(),hd=function(i){return function(e,t,r){var a=EI(e),s=PI(a);if(s===0)return!i&&-1;var n=xI(r,s),o;if(i&&t!==t){for(;s>n;)if(o=a[n++],o!==o)return!0}else for(;s>n;n++)if((i||n in a)&&a[n]===t)return i||n||0;return!i&&-1}};md.exports={includes:hd(!0),indexOf:hd(!1)}});var oi=m((M0,fd)=>{"use strict";fd.exports=function(){}});var bd=m(()=>{"use strict";var kI=z(),AI=Hn().includes,wI=ie(),RI=oi(),$I=wI(function(){return!Array(1).includes()});kI({target:"Array",proto:!0,forced:$I},{includes:function(e){return AI(this,e,arguments.length>1?arguments[1]:void 0)}});RI("includes")});var Tt=m((O0,gd)=>{"use strict";var LI=st();gd.exports=LI});var vd=m((V0,Sd)=>{"use strict";bd();var MI=Tt();Sd.exports=MI("Array","includes")});var Td=m((B0,yd)=>{"use strict";var CI=vd();yd.exports=CI});var Ke=m((_0,Id)=>{"use strict";var DI=Td();Id.exports=DI});var ja=m((K0,$d)=>{"use strict";var UI=$n(),HI=Ln(),Rd=UI("keys");$d.exports=function(i){return Rd[i]||(Rd[i]=HI(i))}});var Md=m((J0,Ld)=>{"use strict";var jI=ie();Ld.exports=!jI(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Ga=m((X0,Dd)=>{"use strict";var GI=Fe(),QI=G(),WI=Sr(),YI=ja(),zI=Md(),Cd=YI("IE_PROTO"),Qn=Object,KI=Qn.prototype;Dd.exports=zI?Qn.getPrototypeOf:function(i){var e=WI(i);if(GI(e,Cd))return e[Cd];var t=e.constructor;return QI(t)&&e instanceof t?t.prototype:e instanceof Qn?KI:null}});var Qa=m((Z0,Od)=>{"use strict";Od.exports={}});var _d=m((eD,Bd)=>{"use strict";var JI=J(),Wn=Fe(),XI=Ht(),ZI=Hn().indexOf,eE=Qa(),Vd=JI([].push);Bd.exports=function(i,e){var t=XI(i),r=0,a=[],s;for(s in t)!Wn(eE,s)&&Wn(t,s)&&Vd(a,s);for(;e.length>r;)Wn(t,s=e[r++])&&(~ZI(a,s)||Vd(a,s));return a}});var Yn=m((tD,Nd)=>{"use strict";Nd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var zn=m((rD,Fd)=>{"use strict";var tE=_d(),rE=Yn();Fd.exports=Object.keys||function(e){return tE(e,rE)}});var Kn=m((iD,Gd)=>{"use strict";var Ud=Ie(),iE=ie(),Hd=J(),aE=Ga(),sE=zn(),nE=Ht(),oE=Sn().f,jd=Hd(oE),uE=Hd([].push),lE=Ud&&iE(function(){var i=Object.create(null);return i[2]=2,!jd(i,2)}),qd=function(i){return function(e){for(var t=nE(e),r=sE(t),a=lE&&aE(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Ud||(a?u in t:jd(t,u)))&&uE(o,i?[u,t[u]]:t[u]);return o}};Gd.exports={entries:qd(!0),values:qd(!1)}});var Qd=m(()=>{"use strict";var cE=z(),dE=Kn().entries;cE({target:"Object",stat:!0},{entries:function(e){return dE(e)}})});var Yd=m((nD,Wd)=>{"use strict";Qd();var pE=gr();Wd.exports=pE.Object.entries});var Kd=m((oD,zd)=>{"use strict";var hE=Yd();zd.exports=hE});var It=m((uD,Jd)=>{"use strict";var mE=Kd();Jd.exports=mE});var Qt=m((lD,Xd)=>{"use strict";Xd.exports={}});var tp=m((cD,ep)=>{"use strict";var fE=Q(),bE=G(),Zd=fE.WeakMap;ep.exports=bE(Zd)&&/native code/.test(String(Zd))});var eo=m((dD,ap)=>{"use strict";var gE=tp(),ip=Q(),SE=xe(),vE=Tr(),Jn=Fe(),Xn=ii(),yE=ja(),TE=Qa(),rp="Object already initialized",Zn=ip.TypeError,IE=ip.WeakMap,Wa,ui,Ya,EE=function(i){return Ya(i)?ui(i):Wa(i,{})},xE=function(i){return function(e){var t;if(!SE(e)||(t=ui(e)).type!==i)throw new Zn("Incompatible receiver, "+i+" required");return t}};gE||Xn.state?(qe=Xn.state||(Xn.state=new IE),qe.get=qe.get,qe.has=qe.has,qe.set=qe.set,Wa=function(i,e){if(qe.has(i))throw new Zn(rp);return e.facade=i,qe.set(i,e),e},ui=function(i){return qe.get(i)||{}},Ya=function(i){return qe.has(i)}):(Wt=yE("state"),TE[Wt]=!0,Wa=function(i,e){if(Jn(i,Wt))throw new Zn(rp);return e.facade=i,vE(i,Wt,e),e},ui=function(i){return Jn(i,Wt)?i[Wt]:{}},Ya=function(i){return Jn(i,Wt)});var qe,Wt;ap.exports={set:Wa,get:ui,has:Ya,enforce:EE,getterFor:xE}});var io=m((pD,np)=>{"use strict";var to=Ie(),PE=Fe(),sp=Function.prototype,kE=to&&Object.getOwnPropertyDescriptor,ro=PE(sp,"name"),AE=ro&&function(){}.name==="something",wE=ro&&(!to||to&&kE(sp,"name").configurable);np.exports={EXISTS:ro,PROPER:AE,CONFIGURABLE:wE}});var up=m(op=>{"use strict";var RE=Ie(),$E=Bn(),LE=Gt(),ME=ze(),CE=Ht(),DE=zn();op.f=RE&&!$E?Object.defineProperties:function(e,t){ME(e);for(var r=CE(t),a=DE(t),s=a.length,n=0,o;s>n;)LE.f(e,o=a[n++],r[o]);return e}});var ao=m((mD,lp)=>{"use strict";var OE=st();lp.exports=OE("document","documentElement")});var uo=m((fD,bp)=>{"use strict";var VE=ze(),BE=up(),cp=Yn(),_E=Qa(),NE=ao(),FE=Fa(),qE=ja(),dp=">",pp="<",no="prototype",oo="script",mp=qE("IE_PROTO"),so=function(){},fp=function(i){return pp+oo+dp+i+pp+"/"+oo+dp},hp=function(i){i.write(fp("")),i.close();var e=i.parentWindow.Object;return i=null,e},UE=function(){var i=FE("iframe"),e="java"+oo+":",t;return i.style.display="none",NE.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(fp("document.F=Object")),t.close(),t.F},za,Ka=function(){try{za=new ActiveXObject("htmlfile")}catch{}Ka=typeof document<"u"?document.domain&&za?hp(za):UE():hp(za);for(var i=cp.length;i--;)delete Ka[no][cp[i]];return Ka()};_E[mp]=!0;bp.exports=Object.create||function(e,t){var r;return e!==null?(so[no]=VE(e),r=new so,so[no]=null,r[mp]=e):r=Ka(),t===void 0?r:BE.f(r,t)}});var Pr=m((bD,gp)=>{"use strict";var HE=Tr();gp.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:HE(i,e,t),i}});var ho=m((gD,yp)=>{"use strict";var jE=ie(),GE=G(),QE=xe(),WE=uo(),Sp=Ga(),YE=Pr(),zE=ae(),KE=Ne(),po=zE("iterator"),vp=!1,nt,lo,co;[].keys&&(co=[].keys(),"next"in co?(lo=Sp(Sp(co)),lo!==Object.prototype&&(nt=lo)):vp=!0);var JE=!QE(nt)||jE(function(){var i={};return nt[po].call(i)!==i});JE?nt={}:KE&&(nt=WE(nt));GE(nt[po])||YE(nt,po,function(){return this});yp.exports={IteratorPrototype:nt,BUGGY_SAFARI_ITERATORS:vp}});var Ja=m((SD,Ip)=>{"use strict";var XE=ae(),ZE=XE("toStringTag"),Tp={};Tp[ZE]="z";Ip.exports=String(Tp)==="[object z]"});var li=m((vD,Ep)=>{"use strict";var ex=Ja(),tx=G(),Xa=Ut(),rx=ae(),ix=rx("toStringTag"),ax=Object,sx=Xa(function(){return arguments}())==="Arguments",nx=function(i,e){try{return i[e]}catch{}};Ep.exports=ex?Xa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=nx(e=ax(i),ix))=="string"?t:sx?Xa(e):(r=Xa(e))==="Object"&&tx(e.callee)?"Arguments":r}});var Pp=m((yD,xp)=>{"use strict";var ox=Ja(),ux=li();xp.exports=ox?{}.toString:function(){return"[object "+ux(this)+"]"}});var ci=m((TD,Ap)=>{"use strict";var lx=Ja(),cx=Gt().f,dx=Tr(),px=Fe(),hx=Pp(),mx=ae(),kp=mx("toStringTag");Ap.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(px(a,kp)||cx(a,kp,{configurable:!0,value:e}),r&&!lx&&dx(a,"toString",hx))}});var Rp=m((ID,wp)=>{"use strict";var fx=ho().IteratorPrototype,bx=uo(),gx=Zr(),Sx=ci(),vx=Qt(),yx=function(){return this};wp.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=bx(fx,{next:gx(+!r,t)}),Sx(i,a,!1,!0),vx[a]=yx,i}});var Lp=m((ED,$p)=>{"use strict";var Tx=J(),Ix=Ye();$p.exports=function(i,e,t){try{return Tx(Ix(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Cp=m((xD,Mp)=>{"use strict";var Ex=xe();Mp.exports=function(i){return Ex(i)||i===null}});var Op=m((PD,Dp)=>{"use strict";var xx=Cp(),Px=String,kx=TypeError;Dp.exports=function(i){if(xx(i))return i;throw new kx("Can't set "+Px(i)+" as a prototype")}});var mo=m((kD,Vp)=>{"use strict";var Ax=Lp(),wx=xe(),Rx=yt(),$x=Op();Vp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=Ax(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return Rx(a),$x(s),wx(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Wp=m((AD,Qp)=>{"use strict";var Lx=z(),Mx=Ee(),Za=Ne(),jp=io(),Cx=G(),Dx=Rp(),Bp=Ga(),_p=mo(),Ox=ci(),Vx=Tr(),fo=Pr(),Bx=ae(),Np=Qt(),Gp=ho(),_x=jp.PROPER,Nx=jp.CONFIGURABLE,Fp=Gp.IteratorPrototype,es=Gp.BUGGY_SAFARI_ITERATORS,di=Bx("iterator"),qp="keys",pi="values",Up="entries",Hp=function(){return this};Qp.exports=function(i,e,t,r,a,s,n){Dx(t,e,r);var o=function(S){if(S===a&&p)return p;if(!es&&S&&S in c)return c[S];switch(S){case qp:return function(){return new t(this,S)};case pi:return function(){return new t(this,S)};case Up:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[di]||c["@@iterator"]||a&&c[a],p=!es&&d||o(a),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=Bp(h.call(new i)),f!==Object.prototype&&f.next&&(!Za&&Bp(f)!==Fp&&(_p?_p(f,Fp):Cx(f[di])||fo(f,di,Hp)),Ox(f,u,!0,!0),Za&&(Np[u]=Hp))),_x&&a===pi&&d&&d.name!==pi&&(!Za&&Nx?Vx(c,"name",pi):(l=!0,p=function(){return Mx(d,this)})),a)if(b={values:o(pi),keys:s?p:o(qp),entries:o(Up)},n)for(g in b)(es||l||!(g in c))&&fo(c,g,b[g]);else Lx({target:e,proto:!0,forced:es||l},b);return(!Za||n)&&c[di]!==p&&fo(c,di,p,{name:a}),Np[e]=p,b}});var zp=m((wD,Yp)=>{"use strict";Yp.exports=function(i,e){return{value:i,done:e}}});var go=m((RD,eh)=>{"use strict";var Fx=Ht(),bo=oi(),Kp=Qt(),Xp=eo(),qx=Gt().f,Ux=Wp(),ts=zp(),Hx=Ne(),jx=Ie(),Zp="Array Iterator",Gx=Xp.set,Qx=Xp.getterFor(Zp);eh.exports=Ux(Array,"Array",function(i,e){Gx(this,{type:Zp,target:Fx(i),index:0,kind:e})},function(){var i=Qx(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,ts(void 0,!0);switch(i.kind){case"keys":return ts(t,!1);case"values":return ts(e[t],!1)}return ts([t,e[t]],!1)},"values");var Jp=Kp.Arguments=Kp.Array;bo("keys");bo("values");bo("entries");if(!Hx&&jx&&Jp.name!=="values")try{qx(Jp,"name",{value:"values"})}catch{}});var rh=m(($D,th)=>{"use strict";var Wx=ae(),Yx=Qt(),zx=Wx("iterator"),Kx=Array.prototype;th.exports=function(i){return i!==void 0&&(Yx.Array===i||Kx[zx]===i)}});var So=m((LD,ah)=>{"use strict";var Jx=li(),ih=ri(),Xx=br(),Zx=Qt(),eP=ae(),tP=eP("iterator");ah.exports=function(i){if(!Xx(i))return ih(i,tP)||ih(i,"@@iterator")||Zx[Jx(i)]}});var nh=m((MD,sh)=>{"use strict";var rP=Ee(),iP=Ye(),aP=ze(),sP=ti(),nP=So(),oP=TypeError;sh.exports=function(i,e){var t=arguments.length<2?nP(i):e;if(iP(t))return aP(rP(t,i));throw new oP(sP(i)+" is not iterable")}});var lh=m((CD,uh)=>{"use strict";var uP=Ee(),oh=ze(),lP=ri();uh.exports=function(i,e,t){var r,a;oh(i);try{if(r=lP(i,"return"),!r){if(e==="throw")throw t;return t}r=uP(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return oh(r),t}});var is=m((DD,hh)=>{"use strict";var cP=yr(),dP=Ee(),pP=ze(),hP=ti(),mP=rh(),fP=xr(),ch=ei(),bP=nh(),gP=So(),dh=lh(),SP=TypeError,rs=function(i,e){this.stopped=i,this.result=e},ph=rs.prototype;hh.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=cP(e,r),l,c,d,p,h,f,b,g=function(k){return l&&dh(l,"normal",k),new rs(!0,k)},S=function(k){return a?(pP(k),o?u(k[0],k[1],g):u(k[0],k[1])):o?u(k,g):u(k)};if(s)l=i.iterator;else if(n)l=i;else{if(c=gP(i),!c)throw new SP(hP(i)+" is not iterable");if(mP(c)){for(d=0,p=fP(i);p>d;d++)if(h=S(i[d]),h&&ch(ph,h))return h;return new rs(!1)}l=bP(i,c)}for(f=s?i.next:l.next;!(b=dP(f,l)).done;){try{h=S(b.value)}catch(k){dh(l,"throw",k)}if(typeof h=="object"&&h&&ch(ph,h))return h}return new rs(!1)}});var fh=m((OD,mh)=>{"use strict";var vP=Ie(),yP=Gt(),TP=Zr();mh.exports=function(i,e,t){vP?yP.f(i,e,TP(0,t)):i[e]=t}});var bh=m(()=>{"use strict";var IP=z(),EP=is(),xP=fh();IP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return EP(e,function(r,a){xP(t,r,a)},{AS_ENTRIES:!0}),t}})});var Sh=m((_D,gh)=>{"use strict";go();bh();var PP=gr();gh.exports=PP.Object.fromEntries});var yh=m((ND,vh)=>{"use strict";vh.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 Ih=m(()=>{"use strict";go();var kP=yh(),AP=Q(),wP=ci(),Th=Qt();for(as in kP)wP(AP[as],as),Th[as]=Th.Array;var as});var xh=m((UD,Eh)=>{"use strict";var RP=Sh();Ih();Eh.exports=RP});var vo=m((HD,Ph)=>{"use strict";var $P=xh();Ph.exports=$P});var kh=m(()=>{"use strict"});var yo=m((QD,Ah)=>{"use strict";var hi=Q(),LP=jt(),MP=Ut(),ss=function(i){return LP.slice(0,i.length)===i};Ah.exports=function(){return ss("Bun/")?"BUN":ss("Cloudflare-Workers")?"CLOUDFLARE":ss("Deno/")?"DENO":ss("Node.js/")?"NODE":hi.Bun&&typeof Bun.version=="string"?"BUN":hi.Deno&&typeof Deno.version=="object"?"DENO":MP(hi.process)==="process"?"NODE":hi.window&&hi.document?"BROWSER":"REST"}()});var ns=m((WD,wh)=>{"use strict";var CP=yo();wh.exports=CP==="NODE"});var $h=m((YD,Rh)=>{"use strict";var DP=Gt();Rh.exports=function(i,e,t){return DP.f(i,e,t)}});var Ch=m((zD,Mh)=>{"use strict";var OP=st(),VP=$h(),BP=ae(),_P=Ie(),Lh=BP("species");Mh.exports=function(i){var e=OP(i);_P&&e&&!e[Lh]&&VP(e,Lh,{configurable:!0,get:function(){return this}})}});var Oh=m((KD,Dh)=>{"use strict";var NP=ei(),FP=TypeError;Dh.exports=function(i,e){if(NP(e,i))return i;throw new FP("Incorrect invocation")}});var Io=m((JD,Vh)=>{"use strict";var qP=J(),UP=G(),To=ii(),HP=qP(Function.toString);UP(To.inspectSource)||(To.inspectSource=function(i){return HP(i)});Vh.exports=To.inspectSource});var xo=m((XD,qh)=>{"use strict";var jP=J(),GP=ie(),Bh=G(),QP=li(),WP=st(),YP=Io(),_h=function(){},Nh=WP("Reflect","construct"),Eo=/^\s*(?:class|function)\b/,zP=jP(Eo.exec),KP=!Eo.test(_h),mi=function(e){if(!Bh(e))return!1;try{return Nh(_h,[],e),!0}catch{return!1}},Fh=function(e){if(!Bh(e))return!1;switch(QP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return KP||!!zP(Eo,YP(e))}catch{return!0}};Fh.sham=!0;qh.exports=!Nh||GP(function(){var i;return mi(mi.call)||!mi(Object)||!mi(function(){i=!0})||i})?Fh:mi});var Hh=m((ZD,Uh)=>{"use strict";var JP=xo(),XP=ti(),ZP=TypeError;Uh.exports=function(i){if(JP(i))return i;throw new ZP(XP(i)+" is not a constructor")}});var Po=m((eO,Gh)=>{"use strict";var jh=ze(),ek=Hh(),tk=br(),rk=ae(),ik=rk("species");Gh.exports=function(i,e){var t=jh(i).constructor,r;return t===void 0||tk(r=jh(t)[ik])?e:ek(r)}});var Wh=m((tO,Qh)=>{"use strict";var ak=J();Qh.exports=ak([].slice)});var zh=m((rO,Yh)=>{"use strict";var sk=TypeError;Yh.exports=function(i,e){if(i<e)throw new sk("Not enough arguments");return i}});var ko=m((iO,Kh)=>{"use strict";var nk=jt();Kh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(nk)});var Oo=m((aO,sm)=>{"use strict";var Pe=Q(),ok=mn(),uk=yr(),Jh=G(),lk=Fe(),am=ie(),Xh=ao(),ck=Wh(),Zh=Fa(),dk=zh(),pk=ko(),hk=ns(),Mo=Pe.setImmediate,Co=Pe.clearImmediate,mk=Pe.process,Ao=Pe.Dispatch,fk=Pe.Function,em=Pe.MessageChannel,bk=Pe.String,wo=0,fi={},tm="onreadystatechange",bi,Yt,Ro,$o;am(function(){bi=Pe.location});var Do=function(i){if(lk(fi,i)){var e=fi[i];delete fi[i],e()}},Lo=function(i){return function(){Do(i)}},rm=function(i){Do(i.data)},im=function(i){Pe.postMessage(bk(i),bi.protocol+"//"+bi.host)};(!Mo||!Co)&&(Mo=function(e){dk(arguments.length,1);var t=Jh(e)?e:fk(e),r=ck(arguments,1);return fi[++wo]=function(){ok(t,void 0,r)},Yt(wo),wo},Co=function(e){delete fi[e]},hk?Yt=function(i){mk.nextTick(Lo(i))}:Ao&&Ao.now?Yt=function(i){Ao.now(Lo(i))}:em&&!pk?(Ro=new em,$o=Ro.port2,Ro.port1.onmessage=rm,Yt=uk($o.postMessage,$o)):Pe.addEventListener&&Jh(Pe.postMessage)&&!Pe.importScripts&&bi&&bi.protocol!=="file:"&&!am(im)?(Yt=im,Pe.addEventListener("message",rm,!1)):tm in Zh("script")?Yt=function(i){Xh.appendChild(Zh("script"))[tm]=function(){Xh.removeChild(this),Do(i)}}:Yt=function(i){setTimeout(Lo(i),0)});sm.exports={set:Mo,clear:Co}});var um=m((sO,om)=>{"use strict";var nm=Q(),gk=Ie(),Sk=Object.getOwnPropertyDescriptor;om.exports=function(i){if(!gk)return nm[i];var e=Sk(nm,i);return e&&e.value}});var Vo=m((nO,cm)=>{"use strict";var lm=function(){this.head=null,this.tail=null};lm.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};cm.exports=lm});var pm=m((oO,dm)=>{"use strict";var vk=jt();dm.exports=/ipad|iphone|ipod/i.test(vk)&&typeof Pebble<"u"});var mm=m((uO,hm)=>{"use strict";var yk=jt();hm.exports=/web0s(?!.*chrome)/i.test(yk)});var Tm=m((lO,ym)=>{"use strict";var Ar=Q(),Tk=um(),fm=yr(),Bo=Oo().set,Ik=Vo(),Ek=ko(),xk=pm(),Pk=mm(),_o=ns(),bm=Ar.MutationObserver||Ar.WebKitMutationObserver,gm=Ar.document,Sm=Ar.process,os=Ar.Promise,qo=Tk("queueMicrotask"),kr,No,Fo,us,vm;qo||(gi=new Ik,Si=function(){var i,e;for(_o&&(i=Sm.domain)&&i.exit();e=gi.get();)try{e()}catch(t){throw gi.head&&kr(),t}i&&i.enter()},!Ek&&!_o&&!Pk&&bm&&gm?(No=!0,Fo=gm.createTextNode(""),new bm(Si).observe(Fo,{characterData:!0}),kr=function(){Fo.data=No=!No}):!xk&&os&&os.resolve?(us=os.resolve(void 0),us.constructor=os,vm=fm(us.then,us),kr=function(){vm(Si)}):_o?kr=function(){Sm.nextTick(Si)}:(Bo=fm(Bo,Ar),kr=function(){Bo(Si)}),qo=function(i){gi.head||kr(),gi.add(i)});var gi,Si;ym.exports=qo});var Em=m((cO,Im)=>{"use strict";Im.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var ls=m((dO,xm)=>{"use strict";xm.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var zt=m((pO,Pm)=>{"use strict";var kk=Q();Pm.exports=kk.Promise});var wr=m((hO,Rm)=>{"use strict";var Ak=Q(),vi=zt(),wk=G(),Rk=Vn(),$k=Io(),Lk=ae(),km=yo(),Mk=Ne(),Uo=En(),Am=vi&&vi.prototype,Ck=Lk("species"),Ho=!1,wm=wk(Ak.PromiseRejectionEvent),Dk=Rk("Promise",function(){var i=$k(vi),e=i!==String(vi);if(!e&&Uo===66||Mk&&!(Am.catch&&Am.finally))return!0;if(!Uo||Uo<51||!/native code/.test(i)){var t=new vi(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Ck]=r,Ho=t.then(function(){})instanceof r,!Ho)return!0}return!e&&(km==="BROWSER"||km==="DENO")&&!wm});Rm.exports={CONSTRUCTOR:Dk,REJECTION_EVENT:wm,SUBCLASSING:Ho}});var Rr=m((mO,Lm)=>{"use strict";var $m=Ye(),Ok=TypeError,Vk=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new Ok("Bad Promise constructor");e=r,t=a}),this.resolve=$m(e),this.reject=$m(t)};Lm.exports.f=function(i){return new Vk(i)}});var Km=m(()=>{"use strict";var Bk=z(),_k=Ne(),hs=ns(),Et=Q(),Cr=Ee(),Mm=Pr(),Cm=mo(),Nk=ci(),Fk=Ch(),qk=Ye(),ps=G(),Uk=xe(),Hk=Oh(),jk=Po(),_m=Oo().set,Yo=Tm(),Gk=Em(),Qk=ls(),Wk=Vo(),Nm=eo(),ms=zt(),zo=wr(),Fm=Rr(),fs="Promise",qm=zo.CONSTRUCTOR,Yk=zo.REJECTION_EVENT,zk=zo.SUBCLASSING,jo=Nm.getterFor(fs),Kk=Nm.set,$r=ms&&ms.prototype,Kt=ms,cs=$r,Um=Et.TypeError,Go=Et.document,Ko=Et.process,Qo=Fm.f,Jk=Qo,Xk=!!(Go&&Go.createEvent&&Et.dispatchEvent),Hm="unhandledrejection",Zk="rejectionhandled",Dm=0,jm=1,eA=2,Jo=1,Gm=2,ds,Om,tA,Vm,Qm=function(i){var e;return Uk(i)&&ps(e=i.then)?e:!1},Wm=function(i,e){var t=e.value,r=e.state===jm,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===Gm&&iA(e),e.rejection=Jo),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(new Um("Promise-chain cycle")):(l=Qm(u))?Cr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Ym=function(i,e){i.notified||(i.notified=!0,Yo(function(){for(var t=i.reactions,r;r=t.get();)Wm(r,i);i.notified=!1,e&&!i.rejection&&rA(i)}))},zm=function(i,e,t){var r,a;Xk?(r=Go.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Et.dispatchEvent(r)):r={promise:e,reason:t},!Yk&&(a=Et["on"+i])?a(r):i===Hm&&Gk("Unhandled promise rejection",t)},rA=function(i){Cr(_m,Et,function(){var e=i.facade,t=i.value,r=Bm(i),a;if(r&&(a=Qk(function(){hs?Ko.emit("unhandledRejection",t,e):zm(Hm,e,t)}),i.rejection=hs||Bm(i)?Gm:Jo,a.error))throw a.value})},Bm=function(i){return i.rejection!==Jo&&!i.parent},iA=function(i){Cr(_m,Et,function(){var e=i.facade;hs?Ko.emit("rejectionHandled",e):zm(Zk,e,i.value)})},Lr=function(i,e,t){return function(r){i(e,r,t)}},Mr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=eA,Ym(i,!0))},Wo=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new Um("Promise can't be resolved itself");var r=Qm(e);r?Yo(function(){var a={done:!1};try{Cr(r,e,Lr(Wo,a,i),Lr(Mr,a,i))}catch(s){Mr(a,s,i)}}):(i.value=e,i.state=jm,Ym(i,!1))}catch(a){Mr({done:!1},a,i)}}};if(qm&&(Kt=function(e){Hk(this,cs),qk(e),Cr(ds,this);var t=jo(this);try{e(Lr(Wo,t),Lr(Mr,t))}catch(r){Mr(t,r)}},cs=Kt.prototype,ds=function(e){Kk(this,{type:fs,done:!1,notified:!1,parent:!1,reactions:new Wk,rejection:!1,state:Dm,value:void 0})},ds.prototype=Mm(cs,"then",function(e,t){var r=jo(this),a=Qo(jk(this,Kt));return r.parent=!0,a.ok=ps(e)?e:!0,a.fail=ps(t)&&t,a.domain=hs?Ko.domain:void 0,r.state===Dm?r.reactions.add(a):Yo(function(){Wm(a,r)}),a.promise}),Om=function(){var i=new ds,e=jo(i);this.promise=i,this.resolve=Lr(Wo,e),this.reject=Lr(Mr,e)},Fm.f=Qo=function(i){return i===Kt||i===tA?new Om(i):Jk(i)},!_k&&ps(ms)&&$r!==Object.prototype)){Vm=$r.then,zk||Mm($r,"then",function(e,t){var r=this;return new Kt(function(a,s){Cr(Vm,r,a,s)}).then(e,t)},{unsafe:!0});try{delete $r.constructor}catch{}Cm&&Cm($r,cs)}Bk({global:!0,constructor:!0,wrap:!0,forced:qm},{Promise:Kt});Nk(Kt,fs,!1,!0);Fk(fs)});var tf=m((gO,ef)=>{"use strict";var aA=ae(),Xm=aA("iterator"),Zm=!1;try{Jm=0,Xo={next:function(){return{done:!!Jm++}},return:function(){Zm=!0}},Xo[Xm]=function(){return this},Array.from(Xo,function(){throw 2})}catch{}var Jm,Xo;ef.exports=function(i,e){try{if(!e&&!Zm)return!1}catch{return!1}var t=!1;try{var r={};r[Xm]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var Zo=m((SO,rf)=>{"use strict";var sA=zt(),nA=tf(),oA=wr().CONSTRUCTOR;rf.exports=oA||!nA(function(i){sA.all(i).then(void 0,function(){})})});var af=m(()=>{"use strict";var uA=z(),lA=Ee(),cA=Ye(),dA=Rr(),pA=ls(),hA=is(),mA=Zo();uA({target:"Promise",stat:!0,forced:mA},{all:function(e){var t=this,r=dA.f(t),a=r.resolve,s=r.reject,n=pA(function(){var o=cA(t.resolve),u=[],l=0,c=1;hA(e,function(d){var p=l++,h=!1;c++,lA(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var nf=m(()=>{"use strict";var fA=z(),bA=Ne(),gA=wr().CONSTRUCTOR,tu=zt(),SA=st(),vA=G(),yA=Pr(),sf=tu&&tu.prototype;fA({target:"Promise",proto:!0,forced:gA,real:!0},{catch:function(i){return this.then(void 0,i)}});!bA&&vA(tu)&&(eu=SA("Promise").prototype.catch,sf.catch!==eu&&yA(sf,"catch",eu,{unsafe:!0}));var eu});var of=m(()=>{"use strict";var TA=z(),IA=Ee(),EA=Ye(),xA=Rr(),PA=ls(),kA=is(),AA=Zo();TA({target:"Promise",stat:!0,forced:AA},{race:function(e){var t=this,r=xA.f(t),a=r.reject,s=PA(function(){var n=EA(t.resolve);kA(e,function(o){IA(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var uf=m(()=>{"use strict";var wA=z(),RA=Rr(),$A=wr().CONSTRUCTOR;wA({target:"Promise",stat:!0,forced:$A},{reject:function(e){var t=RA.f(this),r=t.reject;return r(e),t.promise}})});var ru=m((AO,lf)=>{"use strict";var LA=ze(),MA=xe(),CA=Rr();lf.exports=function(i,e){if(LA(i),MA(e)&&e.constructor===i)return e;var t=CA.f(i),r=t.resolve;return r(e),t.promise}});var pf=m(()=>{"use strict";var DA=z(),OA=st(),cf=Ne(),VA=zt(),df=wr().CONSTRUCTOR,BA=ru(),_A=OA("Promise"),NA=cf&&!df;DA({target:"Promise",stat:!0,forced:cf||df},{resolve:function(e){return BA(NA&&this===_A?VA:this,e)}})});var hf=m(()=>{"use strict";Km();af();nf();of();uf();pf()});var gf=m(()=>{"use strict";var FA=z(),qA=Ne(),bs=zt(),UA=ie(),ff=st(),bf=G(),HA=Po(),mf=ru(),jA=Pr(),au=bs&&bs.prototype,GA=!!bs&&UA(function(){au.finally.call({then:function(){}},function(){})});FA({target:"Promise",proto:!0,real:!0,forced:GA},{finally:function(i){var e=HA(this,ff("Promise")),t=bf(i);return this.then(t?function(r){return mf(e,i()).then(function(){return r})}:i,t?function(r){return mf(e,i()).then(function(){throw r})}:i)}});!qA&&bf(bs)&&(iu=ff("Promise").prototype.finally,au.finally!==iu&&jA(au,"finally",iu,{unsafe:!0}));var iu});var vf=m((DO,Sf)=>{"use strict";kh();hf();gf();var QA=Tt();Sf.exports=QA("Promise","finally")});var Tf=m((OO,yf)=>{"use strict";var WA=vf();yf.exports=WA});var gs=m((VO,If)=>{"use strict";var YA=Tf();If.exports=YA});var Of=m(()=>{"use strict";var uw=z(),lw=Kn().values;uw({target:"Object",stat:!0},{values:function(e){return lw(e)}})});var Bf=m((yV,Vf)=>{"use strict";Of();var cw=gr();Vf.exports=cw.Object.values});var Nf=m((TV,_f)=>{"use strict";var dw=Bf();_f.exports=dw});var ut=m((IV,Ff)=>{"use strict";var pw=Nf();Ff.exports=pw});var Zf=m(()=>{"use strict";var ww=z(),Rw=Sr(),$w=xr(),Lw=ni(),Mw=oi();ww({target:"Array",proto:!0},{at:function(e){var t=Rw(this),r=$w(t),a=Lw(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});Mw("at")});var tb=m((KV,eb)=>{"use strict";Zf();var Cw=Tt();eb.exports=Cw("Array","at")});var ib=m((JV,rb)=>{"use strict";var Dw=tb();rb.exports=Dw});var Vr=m((XV,ab)=>{"use strict";var Ow=ib();ab.exports=Ow});var Au=m((x_,Db)=>{"use strict";var bR=Ut();Db.exports=Array.isArray||function(e){return bR(e)==="Array"}});var Vb=m((P_,Ob)=>{"use strict";var gR=TypeError,SR=9007199254740991;Ob.exports=function(i){if(i>SR)throw gR("Maximum allowed index exceeded");return i}});var Nb=m((k_,_b)=>{"use strict";var vR=Au(),yR=xr(),TR=Vb(),IR=yr(),Bb=function(i,e,t,r,a,s,n,o){for(var u=a,l=0,c=n?IR(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&vR(d)?(p=yR(d),u=Bb(i,e,d,p,u,s-1)-1):(TR(u+1),i[u]=d),u++),l++;return u};_b.exports=Bb});var Hb=m((A_,Ub)=>{"use strict";var Fb=Au(),ER=xo(),xR=xe(),PR=ae(),kR=PR("species"),qb=Array;Ub.exports=function(i){var e;return Fb(i)&&(e=i.constructor,ER(e)&&(e===qb||Fb(e.prototype))?e=void 0:xR(e)&&(e=e[kR],e===null&&(e=void 0))),e===void 0?qb:e}});var Gb=m((w_,jb)=>{"use strict";var AR=Hb();jb.exports=function(i,e){return new(AR(i))(e===0?0:e)}});var Qb=m(()=>{"use strict";var wR=z(),RR=Nb(),$R=Ye(),LR=Sr(),MR=xr(),CR=Gb();wR({target:"Array",proto:!0},{flatMap:function(e){var t=LR(this),r=MR(t),a;return $R(e),a=CR(t,0),a.length=RR(a,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var Wb=m(()=>{"use strict";var DR=oi();DR("flatMap")});var zb=m((C_,Yb)=>{"use strict";Qb();Wb();var OR=Tt();Yb.exports=OR("Array","flatMap")});var Jb=m((D_,Kb)=>{"use strict";var VR=zb();Kb.exports=VR});var wu=m((O_,Xb)=>{"use strict";var BR=Jb();Xb.exports=BR});var Di=m((G_,ug)=>{"use strict";var GR=li(),QR=String;ug.exports=function(i){if(GR(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return QR(i)}});var Lu=m((Q_,lg)=>{"use strict";lg.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 pg=m((W_,dg)=>{"use strict";var WR=J(),YR=yt(),zR=Di(),Cu=Lu(),cg=WR("".replace),KR=RegExp("^["+Cu+"]+"),JR=RegExp("(^|[^"+Cu+"])["+Cu+"]+$"),Mu=function(i){return function(e){var t=zR(YR(e));return i&1&&(t=cg(t,KR,"")),i&2&&(t=cg(t,JR,"$1")),t}};dg.exports={start:Mu(1),end:Mu(2),trim:Mu(3)}});var bg=m((Y_,fg)=>{"use strict";var XR=io().PROPER,ZR=ie(),hg=Lu(),mg="\u200B\x85\u180E";fg.exports=function(i){return ZR(function(){return!!hg[i]()||mg[i]()!==mg||XR&&hg[i].name!==i})}});var Du=m((z_,gg)=>{"use strict";var e$=pg().start,t$=bg();gg.exports=t$("trimStart")?function(){return e$(this)}:"".trimStart});var vg=m(()=>{"use strict";var r$=z(),Sg=Du();r$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Sg},{trimLeft:Sg})});var Tg=m(()=>{"use strict";vg();var i$=z(),yg=Du();i$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==yg},{trimStart:yg})});var Eg=m((eN,Ig)=>{"use strict";Tg();var a$=Tt();Ig.exports=a$("String","trimLeft")});var Pg=m((tN,xg)=>{"use strict";var s$=Eg();xg.exports=s$});var Ag=m((rN,kg)=>{"use strict";var n$=Pg();kg.exports=n$});var Hg=m(()=>{"use strict"});var jg=m(()=>{"use strict"});var Qg=m((kq,Gg)=>{"use strict";var R$=xe(),$$=Ut(),L$=ae(),M$=L$("match");Gg.exports=function(i){var e;return R$(i)&&((e=i[M$])!==void 0?!!e:$$(i)==="RegExp")}});var Yg=m((Aq,Wg)=>{"use strict";var C$=ze();Wg.exports=function(){var i=C$(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e}});var Jg=m((wq,Kg)=>{"use strict";var D$=Ee(),O$=Fe(),V$=ei(),B$=Yg(),zg=RegExp.prototype;Kg.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in zg)&&!O$(i,"flags")&&V$(zg,i)?D$(B$,i):e}});var Zg=m((Rq,Xg)=>{"use strict";var Hu=J(),_$=Sr(),N$=Math.floor,qu=Hu("".charAt),F$=Hu("".replace),Uu=Hu("".slice),q$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,U$=/\$([$&'`]|\d{1,2})/g;Xg.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=U$;return a!==void 0&&(a=_$(a),u=q$),F$(s,u,function(l,c){var d;switch(qu(c,0)){case"$":return"$";case"&":return i;case"`":return Uu(e,0,t);case"'":return Uu(e,n);case"<":d=a[Uu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=N$(p/10);return h===0?l:h<=o?r[h-1]===void 0?qu(c,1):r[h-1]+qu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var rS=m(()=>{"use strict";var H$=z(),j$=Ee(),Gu=J(),eS=yt(),G$=G(),Q$=br(),W$=Qg(),Ur=Di(),Y$=ri(),z$=Jg(),K$=Zg(),J$=ae(),X$=Ne(),Z$=J$("replace"),eL=TypeError,ju=Gu("".indexOf),tL=Gu("".replace),tS=Gu("".slice),rL=Math.max;H$({target:"String",proto:!0},{replaceAll:function(e,t){var r=eS(this),a,s,n,o,u,l,c,d,p,h,f=0,b="";if(!Q$(e)){if(a=W$(e),a&&(s=Ur(eS(z$(e))),!~ju(s,"g")))throw new eL("`.replaceAll` does not allow non-global regexes");if(n=Y$(e,Z$),n)return j$(n,e,r,t);if(X$&&a)return tL(Ur(r),e,t)}for(o=Ur(r),u=Ur(e),l=G$(t),l||(t=Ur(t)),c=u.length,d=rL(1,c),p=ju(o,u);p!==-1;)h=l?Ur(t(u,p,o)):K$(u,o,p,[],void 0,t),b+=tS(o,f,p)+h,f=p+c,p=p+d>o.length?-1:ju(o,u,p+d);return f<o.length&&(b+=tS(o,f)),b}})});var aS=m((Mq,iS)=>{"use strict";Hg();jg();rS();var iL=Tt();iS.exports=iL("String","replaceAll")});var nS=m((Cq,sS)=>{"use strict";var aL=aS();sS.exports=aL});var uS=m((Dq,oS)=>{"use strict";var sL=nS();oS.exports=sL});var cS=m((Oq,lS)=>{"use strict";var nL=ni(),oL=Di(),uL=yt(),lL=RangeError;lS.exports=function(e){var t=oL(uL(this)),r="",a=nL(e);if(a<0||a===1/0)throw new lL("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(r+=t);return r}});var fS=m((Vq,mS)=>{"use strict";var hS=J(),cL=Un(),dS=Di(),dL=cS(),pL=yt(),hL=hS(dL),mL=hS("".slice),fL=Math.ceil,pS=function(i){return function(e,t,r){var a=dS(pL(e)),s=cL(t),n=a.length,o=r===void 0?" ":dS(r),u,l;return s<=n||o===""?a:(u=s-n,l=hL(o,fL(u/o.length)),l.length>u&&(l=mL(l,0,u)),i?a+l:l+a)}};mS.exports={start:pS(!1),end:pS(!0)}});var gS=m((Bq,bS)=>{"use strict";var bL=jt();bS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(bL)});var SS=m(()=>{"use strict";var gL=z(),SL=fS().start,vL=gS();gL({target:"String",proto:!0,forced:vL},{padStart:function(e){return SL(this,e,arguments.length>1?arguments[1]:void 0)}})});var yS=m((Fq,vS)=>{"use strict";SS();var yL=Tt();vS.exports=yL("String","padStart")});var IS=m((qq,TS)=>{"use strict";var TL=yS();TS.exports=TL});var xS=m((Uq,ES)=>{"use strict";var IL=IS();ES.exports=IL});var $l="2.0.118-beta.0";var de=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(de||{}),vt=(E=>(E.MPEG="MPEG",E.DASH="DASH",E.DASH_SEP="DASH_SEP",E.DASH_SEP_VK="DASH_SEP",E.DASH_WEBM="DASH_WEBM",E.DASH_WEBM_AV1="DASH_WEBM_AV1",E.DASH_STREAMS="DASH_STREAMS",E.DASH_WEBM_VK="DASH_WEBM",E.DASH_ONDEMAND="DASH_ONDEMAND",E.DASH_ONDEMAND_VK="DASH_ONDEMAND",E.DASH_LIVE="DASH_LIVE",E.DASH_LIVE_CMAF="DASH_LIVE_CMAF",E.DASH_LIVE_WEBM="DASH_LIVE_WEBM",E.HLS="HLS",E.HLS_ONDEMAND="HLS_ONDEMAND",E.HLS_JS="HLS",E.HLS_LIVE="HLS_LIVE",E.HLS_LIVE_CMAF="HLS_LIVE_CMAF",E.WEB_RTC_LIVE="WEB_RTC_LIVE",E))(vt||{});var Ba=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Ba||{}),dn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(dn||{});var pn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(pn||{});var iy=$(Ke(),1);import{assertNever as wd,assertNonNullable as OI,isNonNullable as Ua,ValueSubject as jn,Subject as VI,Subscription as BI,merge as _I,observableFrom as NI,fromEvent as xd,map as Pd,tap as kd,filterChanged as FI,isNullable as Gn,ErrorCategory as Ad}from"@vkontakte/videoplayer-shared";var Ed=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Ha=class{constructor(e){this.connection$=new jn(void 0);this.castState$=new jn("NOT_AVAILABLE");this.errorEvent$=new VI;this.realCastState$=new jn("NOT_AVAILABLE");this.subscription=new BI;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 r=Ua(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||Ed("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Ad.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(){Ua(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Gn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Gn(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(xd(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=r.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 wd(a.sessionState)}})).add(_I(xd(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(kd(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),Pd(a=>a.castState)),NI([r.getCastState()])).pipe(FI(),Pd(qI),kd(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Ua(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();OI(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(Gn(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:o,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?Ua(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch{return}try{e.setOptions({receiverApplicationId:this.params.receiverApplicationId??t,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:Ad.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},qI=i=>{switch(i){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 wd(i)}};var Tl=$(Ke(),1),Bv=$(It(),1),_v=$(vo(),1);var Mf=$(gs(),1);import{assertNever as Ef}from"@vkontakte/videoplayer-shared";var se=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Ef(t)}return i},Ss=(i,e)=>{switch(e){case 0:return NaN;case 1:{let t=new URL(i);return Number(t.searchParams.get("playback_shift"))}case 2:{let t=new URL(i);return Number(t.searchParams.get("offset_p")??0)}default:Ef(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as zA,Subject as vs,merge as xf}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new vs;this.transitionEnded$=new vs;this.transitionUpdated$=new vs;this.forceChanged$=new vs;this.stateChangeStarted$=xf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=xf(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,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:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||zA(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as KA}from"@vkontakte/videoplayer-shared";var Pf=i=>{switch(i){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return KA(i)}};import{assertNever as Dr,assertNonNullable as Jt,debounce as kf,ErrorCategory as Af,fromEvent as Xt,isNonNullable as wf,map as Rf,merge as $f,observableFrom as JA,Subject as XA,Subscription as su,timeout as ZA,getHighestQuality as ew}from"@vkontakte/videoplayer-shared";var tw=5,rw=5,iw=500,Lf=7e3,yi=class{constructor(e){this.subscription=new su;this.loadMediaTimeoutSubscription=new su;this.videoState=new L("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if(a?.to!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Dr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Dr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Dr(e)}break}default:Dr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Pf(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 su;this.subscription.add(e),this.subscription.add($f(this.videoState.stateChangeStarted$.pipe(Rf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Rf(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));let t=(a,s)=>this.subscription.add(a.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let a=new XA;e.add(a.pipe(kf(iw)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>tw)&&a.next(o),s=o})),e.add(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<rw&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Dr(n)}}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=$f(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,JA(["init"])).pipe(kf(0));t(r,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"),I(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?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),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&I(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let l=t[e];Jt(l);let c=ew(Object.keys(l));Jt(c);let d=l[c];Jt(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Jt(l),r=l.url,a="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];Jt(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Jt(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];Jt(l),r=se(l.url),a="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:Af.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Dr(e)}let n=new chrome.cast.media.MediaInfo(this.params.meta.videoId??r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return wf(o)&&(n.metadata.title=o),wf(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(ZA(Lf).subscribe(()=>s(`timeout(${Lf})`)))});(0,Mf.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Af.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Pu=$(Ke(),1);import{clearVideoElement as Df}from"@vkontakte/videoplayer-shared";import{clearVideoElement as aw}from"@vkontakte/videoplayer-shared";var Cf=i=>{try{i.pause(),i.playbackRate=0,aw(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as sw,Subscription as nw}from"@vkontakte/videoplayer-shared";var nu=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)}},ou=window.WeakMap?new WeakMap:new nu,uu=window.WeakMap?new WeakMap:new Map,ow=(i,e=20)=>{let t=0;return sw(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},pe=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Df(t):(t=document.createElement("video"),i.appendChild(t)),ou.set(t,r);let a=new nw;return a.add(ow(t,e)),uu.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},he=i=>{uu.get(i)?.unsubscribe(),uu.delete(i);let t=ou.get(i);ou.delete(i),t?Df(i):Cf(i)};var cu=$(ut(),1);import{assertNonNullable as Ti,isNonNullable as Xe,isNullable as fw,fromEvent as Or,merge as qf,observableFrom as Uf,filterChanged as Hf,map as Ii,Subject as jf,Subscription as bw,ValueSubject as gw,ErrorCategory as Sw}from"@vkontakte/videoplayer-shared";import{isNonNullable as lu,isNullable as hw,Subscription as mw}from"@vkontakte/videoplayer-shared";var ys=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=hw(a),l=new mw;return a&&l.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},s)),l},Je=(i,e,t)=>ys(e,()=>i.loop,r=>{lu(r)&&(i.loop=r)},{onError:t}),me=(i,e,t,r)=>ys(e,()=>({muted:i.muted,volume:i.volume}),a=>{lu(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),$e=(i,e,t,r)=>ys(e,()=>i.playbackRate,a=>{lu(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),xt=ys;var vw=i=>["__",i.language,i.label].join("|"),yw=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},du=class i{constructor(){this.available$=new jf;this.current$=new gw(void 0);this.error$=new jf;this.subscription=new bw;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:Sw.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(xt(t.internalTextTracks,()=>(0,cu.default)(Object,this.internalTracks),s=>{Xe(s)&&this.setInternal(s)},{equal:(s,n)=>Xe(s)&&Xe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ii(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(xt(t.externalTextTracks,()=>(0,cu.default)(Object,this.externalTracks),s=>{Xe(s)&&this.setExternal(s)},{equal:(s,n)=>Xe(s)&&Xe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ii(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(xt(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:a})),this.subscription.add(xt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ti(this.video);let{textTracks:e}=this.video;this.subscription.add(Or(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(qf(Or(e,"addtrack"),Or(e,"removetrack"),Uf(["init"])).pipe(Ii(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Hf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(qf(Or(e,"change"),Uf(["init"])).pipe(Ii(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ii(r=>r&&this.htmlTextTrackToITextTrack(r).id),Hf()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(Or(e,"addtrack").subscribe(r=>{r.track?.addEventListener("cuechange",t);let a=s=>{let n=s.target?.cues??null;n&&n.length&&(this.applyCueSettings(s.target?.cues??null),s.target?.removeEventListener("cuechange",a))};r.track?.addEventListener("cuechange",a)})),this.subscription.add(Or(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;Xe(t.align)&&(a.align=t.align),Xe(t.position)&&(a.position=t.position),Xe(t.size)&&(a.size=t.size),Xe(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){Ti(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:vw(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)??a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.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(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){Ti(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(fw(e)||!yw(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){Ti(this.video);let t=document.createElement("track");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){Ti(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.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)}},Le=du;var lt=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 Gf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},pu=i=>{let e=Gf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Qf=i=>{let e=Gf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Me,map as Pt,merge as Yf,filterChanged as Iw,isNonNullable as zf,Subject as Ew,filter as Kf,mapTo as Jf,combine as xw,once as Pw,ErrorCategory as kw,ValueSubject as Xf,clientChecker as Aw}from"@vkontakte/videoplayer-shared";var Tw=3,Wf=(i,e,t=Tw)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let u=s-1;u>=0;u--)i.end(u)+t>=r&&(r=i.start(u));for(let u=s+1;u<i.length;u++)i.start(u)-t<=a&&(a=i.end(u))}}return{from:r,to:a}};var fe=i=>{let e=E=>Me(i,E).pipe(Jf(void 0)),r=Yf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>Me(i,E))).pipe(Pt(E=>E.type==="ended"?i.readyState<2:i.readyState<3),Iw()),a=Yf(Me(i,"progress"),Me(i,"timeupdate")).pipe(Pt(()=>Wf(i.buffered,i.currentTime))),s=Aw.isSafari?xw({play:e("play").pipe(Pw()),playing:e("playing")}).pipe(Jf(void 0)):e("playing"),n=Me(i,"volumechange").pipe(Pt(()=>({muted:i.muted,volume:i.volume}))),o=Me(i,"ratechange").pipe(Pt(()=>i.playbackRate)),u=Me(i,"error").pipe(Kf(()=>!!(i.error||i.played.length)),Pt(()=>{let E=i.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:kw.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:i.error??void 0}})),l=Me(i,"timeupdate").pipe(Pt(()=>i.currentTime)),c=new Ew,d=.3,p;l.subscribe(E=>{i.loop&&zf(p)&&zf(E)&&p>=i.duration-d&&E<=d&&c.next(p),p=E});let h=e("pause").pipe(Kf(()=>!i.error&&p!==i.duration)),f=Me(i,"enterpictureinpicture"),b=Me(i,"leavepictureinpicture"),g=new Xf(Qf(i));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new Xf(pu(i));return Me(i,"fullscreenchange").pipe(Pt(()=>pu(i))).subscribe(S),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Me(i,"durationchange").pipe(Pt(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S}};import{VideoQuality as kt}from"@vkontakte/videoplayer-shared";var At=i=>{switch(i){case"mobile":return kt.Q_144P;case"lowest":return kt.Q_240P;case"low":return kt.Q_360P;case"sd":case"medium":return kt.Q_480P;case"hd":case"high":return kt.Q_720P;case"fullhd":case"full":return kt.Q_1080P;case"quadhd":case"quad":return kt.Q_1440P;case"ultrahd":case"ultra":return kt.Q_2160P}};var wt=$(Vr(),1),db=$(Ke(),1),Ts=$(It(),1);import{isNonNullable as X,isNullable as mu,now as pb,isHigher as fu,isHigherOrEqual as bu,isInvariantQuality as ub,isLower as lb,isLowerOrEqual as gu,videoSizeToQuality as Vw,assertNotEmptyArray as hb,assertNonNullable as Bw}from"@vkontakte/videoplayer-shared";var hu=!1,ct={},sb=i=>{hu=i},nb=()=>{ct={}},ob=i=>{i(ct)},Ei=(i,e)=>{hu&&(ct.meta=ct.meta??{},ct.meta[i]=e)},ue=class{constructor(e){this.name=e}next(e){if(!hu)return;ct.series=ct.series??{};let t=ct.series[this.name]??[];t.push([Date.now(),e]),ct.series[this.name]=t}};var _w=new ue("best_bitrate"),mb=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var Su=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),xi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},fb='Assertion "ABR Tracks is empty array" failed',Is=(i,e,t,r)=>{let a=[...e].sort(Su(1)),s=[...t].sort(Su(1)),n=s.filter(u=>X(u.bitrate)&&X(i.bitrate)?i.bitrate/u.bitrate>r:!0),o=(0,wt.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,wt.default)(s,-1);return o&&(0,db.default)(n,o)?o:n.length?(0,wt.default)(n,-1):(0,wt.default)(s,0)},cb=i=>"quality"in i,bb=(i,e,t,r)=>{let a=X(r?.last?.bitrate)&&X(t?.bitrate)&&r.last.bitrate<t.bitrate?i.trackCooldownIncreaseQuality:i.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&pb()-r.history[t.id]<=a&&(!r.last||t.id!==r.last.id);if(t?.id&&r&&!s&&r.recordSelection(t),s&&r?.last){let n=r.last;r?.recordSwitch(n);let o=cb(n)?"video":"audio",u=cb(n)?n.quality:n.bitrate;return e({message:`
|
|
7
8
|
[last ${o} selected] ${u}
|
|
8
|
-
`}),n}return
|
|
9
|
+
`}),n}return r?.recordSwitch(t),t},Nw=(i,e)=>Math.log(e)/Math.log(i),Rt=(i,{container:e,estimatedThroughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f})=>{hb(i,fb);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let v=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(v-1)+1;else{let T=r.pixelRatioLogBase,[q=0,ye=0,Oe=0]=r.pixelRatioLogCoefficients,P=Nw(T,q*v+ye)+Oe;Number.isFinite(P)&&(b*=P)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,S=r.considerPlaybackRate&&X(o)?o:1,k=i.filter(v=>!ub(v.quality)).sort((v,T)=>fu(v.quality,T.quality)?-1:1),E=(0,wt.default)(k,-1)?.quality,A=(0,wt.default)(k,0)?.quality,y=mu(a)||X(a.min)&&X(a.max)&&lb(a.max,a.min)||X(a.min)&&A&&fu(a.min,A)||X(a.max)&&E&&lb(a.max,E),R=S*mb(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),V={},_=k.filter(v=>{let T=!0;if(g)if(v.size)T=v.size.width<=g.width&&v.size.height<=g.height;else{let te=g&&Vw(g);T=te?gu(v.quality,te):!0}if(!T)return V[v.quality]="FitsContainer",!1;let q=h||t;if(!(X(q)&&isFinite(q)&&X(v.bitrate)?q-s>=v.bitrate*R:!0))return V[v.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&X(r.minBufferToSwitchUp)&&u&&!ub(u.quality)&&(n??0)<r.minBufferToSwitchUp&&fu(v.quality,u.quality))return V[v.quality]="Buffer",!1;if(!!d&&bu(v.quality,d))return V[v.quality]="DroppedFramesLimit",!1;if(!!p&&bu(v.quality,p))return V[v.quality]="StallsLimit",!1;let w=y||(mu(a.max)||gu(v.quality,a.max))&&(mu(a.min)||bu(v.quality,a.min)),K=X(c)&&!c?gu(v.quality,r.backgroundVideoQualityLimit):!0;return!w||!K?(V[v.quality]="FitsQualityLimits",!1):!0})[0];_&&_.bitrate&&_w.next(_.bitrate);let U=_??(0,wt.default)(k,-1)??i[0];return U.quality!==l?.last?.quality&&f({message:`
|
|
9
10
|
[VIDEO TRACKS ABR]
|
|
10
11
|
[available video tracks]
|
|
11
|
-
${
|
|
12
|
+
${i.map(v=>`{ id: ${v.id}, quality: ${v.quality}, bitrate: ${v.bitrate} }`).join(`
|
|
12
13
|
`)}
|
|
13
14
|
|
|
14
15
|
[tuning]
|
|
15
|
-
${
|
|
16
|
+
${(0,Ts.default)(Object,r??{}).map(([v,T])=>`${v}: ${T}`).join(`
|
|
16
17
|
`)}
|
|
17
18
|
|
|
18
19
|
[limit params]
|
|
@@ -24,7 +25,7 @@ var rS=Object.create;var Zu=Object.defineProperty;var aS=Object.getOwnPropertyDe
|
|
|
24
25
|
playbackRateFactor: ${S},
|
|
25
26
|
forwardBufferHealth: ${n},
|
|
26
27
|
bitrateFactor: ${R},
|
|
27
|
-
minBufferToSwitchUp: ${
|
|
28
|
+
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
28
29
|
droppedVideoMaxQualityLimit: ${d},
|
|
29
30
|
stallsVideoMaxQualityLimit: ${p},
|
|
30
31
|
limitsAreInvalid: ${y},
|
|
@@ -32,23 +33,23 @@ var rS=Object.create;var Zu=Object.defineProperty;var aS=Object.getOwnPropertyDe
|
|
|
32
33
|
minQualityLimit: ${a?.min},
|
|
33
34
|
|
|
34
35
|
[limited video tracks]
|
|
35
|
-
${
|
|
36
|
+
${(0,Ts.default)(Object,V).map(([v,T])=>`${v}: ${T}`).join(`
|
|
36
37
|
`)||"All tracks are available"}
|
|
37
38
|
|
|
38
|
-
[best video track] ${
|
|
39
|
-
[selected video track] ${
|
|
40
|
-
`}),
|
|
39
|
+
[best video track] ${_?.quality}
|
|
40
|
+
[selected video track] ${U?.quality}
|
|
41
|
+
`}),bb(r,f,U,l)},gb=(i,e,t,{estimatedThroughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{hb(t,fb);let c=a.considerPlaybackRate&&X(s)?s:1,d=[...t].sort(Su(-1)),p=i.bitrate;Bw(p);let h=c*mb(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),f,b=Is(i,e,t,a.minVideoAudioRatio),g=l||r;return X(g)&&isFinite(g)&&(f=d.find(S=>X(S.bitrate)&&X(b?.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),f||(f=b),f?.bitrate!==o?.last?.bitrate&&u({message:`
|
|
41
42
|
[AUDIO TRACKS ABR]
|
|
42
43
|
[available audio tracks]
|
|
43
44
|
${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
|
|
44
45
|
`)}
|
|
45
46
|
|
|
46
47
|
[tuning]
|
|
47
|
-
${
|
|
48
|
+
${(0,Ts.default)(Object,a??{}).map(([S,k])=>`${S}: ${k}`).join(`
|
|
48
49
|
`)}
|
|
49
50
|
|
|
50
51
|
[limit params]
|
|
51
|
-
estimatedThroughput: ${
|
|
52
|
+
estimatedThroughput: ${r},
|
|
52
53
|
stallsPredictedThroughput: ${l},
|
|
53
54
|
reserve: ${p},
|
|
54
55
|
playbackRate: ${s},
|
|
@@ -57,15 +58,15 @@ var rS=Object.create;var Zu=Object.defineProperty;var aS=Object.getOwnPropertyDe
|
|
|
57
58
|
bitrateFactor: ${h},
|
|
58
59
|
minBufferToSwitchUp: ${a.minBufferToSwitchUp},
|
|
59
60
|
|
|
60
|
-
[selected audio track] ${
|
|
61
|
-
`}),m&&If(a,u,m,o)};var K=r=>new URL(r).hostname;import{assertNever as Rf,assertNonNullable as $f,combine as $k,debounce as Lk,ErrorCategory as Lf,filter as Mf,filterChanged as Mk,isNonNullable as ru,map as ms,merge as Df,observableFrom as Dk,once as Ck,Subscription as Vk,ValueSubject as au,videoQualityToHeight as Bk,videoSizeToQuality as Ok}from"@vkontakte/videoplayer-shared";var xf=r=>{if(r instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(r.message))throw r;return!(r instanceof DOMException&&(r.code===20||r.name==="AbortError"))},me=async(r,e)=>{let t=r.muted;try{await r.play()}catch(i){if(!xf(i))return!1;if(e&&e(),t)return console.warn(i),!1;r.muted=!0;try{await r.play()}catch(a){return xf(a)&&(r.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as ds,isNullable as pk,assertNonNullable as gr}from"@vkontakte/videoplayer-shared";import{isNonNullable as Pf,assertNonNullable as cs,now as ck}from"@vkontakte/videoplayer-shared";function X(){return ck()}function Zo(r){return X()-r}function eu(r){let e=r.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=n=>i.test(n);return{resolve:(n,o,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function kf(r,e,t){let i=(...a)=>{t.apply(null,a),r.removeEventListener(e,i)};r.addEventListener(e,i)}function wi(r,e,t,i){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;cs(c);let E=Zo(c),F;if(E<b){F=b-E,setTimeout(g,F);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new a,R()},S=E=>(s=E,v),T=E=>(d=E,v),I=()=>(h="json",v),w=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},y=E=>(p=E,v),R=()=>{c=X(),n=new a,n.open("get",r);let E=0,F,Se=0,Ce=()=>(cs(c),Math.max(c,Math.max(F||0,Se||0)));if(s&&n.addEventListener("progress",k=>{let M=X();s.updateChunk&&k.loaded>E&&(s.updateChunk(Ce(),k.loaded-E),E=k.loaded,F=M)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;cs(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let M=n.response.byteLength-E;M&&s.updateChunk&&s.updateChunk(Ce(),M)}n.responseType==="json"&&!Object.values(n.response).length?w():(d&&d(),e(n.response))}else w()}),n.addEventListener("error",()=>{w()}),p){let k=()=>{cs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Se=X(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),v},v={withBitrateReporting:S,withParallel:y,withJSONResponse:I,withRetryCount:E=>(l=E,v),withRetryInterval:(E,F)=>(Pf(E)&&(b=E),Pf(F)&&(m=F),v),withTimeout:E=>(o=E,v),withFinally:T,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return v}var fr=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,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&i>0){let s=a*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(a)}/${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 br=class{constructor(e,t,i,a,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=a,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=X(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=X()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=wi(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=X()}_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=X();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(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=a,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=i,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as hk}from"@vkontakte/videoplayer-shared";var ps=1e4,tu=3;var mk=6e4,fk=10,bk=1,gk=500,Sr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=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.params=e,this.soundProhibitedEvent$=new hk,this.chunkRateEstimator=new fr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=eu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=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(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,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=eu(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}`),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,a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,i,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!i||i.bitrate>s.bitrate)&&(i=s));return a||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||ds(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{kf(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new br(tu,ps,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let w=s&&(!c||c===this.rep);return w||t("Not running!"),w},p=(w,y,R)=>{u&&u.abort(),u=wi(this.urlResolver.resolve(w,!1),y,R,()=>this._retryCallback()).withTimeout(ps).withBitrateReporting(this.bitrateSwitcher).withRetryCount(tu).withFinally(()=>{u=null}).send()},h=(w,y,R)=>{gr(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),y,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=w=>{let y=i.playbackRate;i.playbackRate!==w&&(t(`Playback rate switch: ${y}=>${w}`),i.playbackRate=w)},b=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let R=X()-1e4,V=0;for(let O=0;O<this.bufferStates.length;O++){let q=this.bufferStates[O];w=Math.min(w,q.buf),q.ts<R&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${w} drop=${V} jitter=${this.sourceJitter}`);let N=w-bk;this.sourceJitter>=0?N-=this.sourceJitter/2:this.sourceJitter-=1,N>3?m(1.15):N>1?m(1.1):N>.3?m(1.05):m(1)}},S=w=>{let y,R=()=>y&&y.start?y.start.length:0,V=k=>y.start[k]/1e3,N=k=>y.dur[k]/1e3,O=k=>y.fragIndex+k,q=(k,M)=>({chunkIdx:O(k),startTS:V(k),dur:N(k),discontinuity:M}),v=()=>{let k=0;if(y&&y.dur){let M=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,A=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Y=M;this.sourceJitter>1&&(Y+=this.sourceJitter-1);let Z=y.dur.length-1;for(;Z>=0&&(Y-=y.dur[Z],!(Y<=0));--Z);k=Math.min(Z,y.dur.length-1-A),k=Math.max(k,0)}return q(k,!0)},E=k=>{let M=R();if(!(M<=0)){if(ds(k)){for(let A=0;A<M;A++)if(V(A)>k)return q(A)}return v()}},F=k=>{let M=R(),A=k?k.chunkIdx+1:0,Y=A-y.fragIndex;if(!(M<=0)){if(!k||Y<0||Y-M>fk)return t(`Resync: offset=${Y} bChunks=${M} chunk=`+JSON.stringify(k)),v();if(!(Y>=M))return q(A-y.fragIndex,!1)}},Se=(k,M,A)=>{l&&l.abort(),l=wi(this.urlResolver.resolve(k,!0,this.lowLatency),M,A,()=>this._retryCallback()).withTimeout(ps).withRetryCount(tu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,M)=>{Se(w,A=>{if(!d())return;y=A;let Y=!!y.lowLatency;Y!==this.lowLatency&&b(Y);let Z=0;for(let dt=0;dt<y.dur.length;++dt)Z+=y.dur[dt];Z>0&&(gr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Z/y.dur.length)),a({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,k(E(M))},()=>this._handleNetworkError())},nextChunk:F}},T=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),gr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:w=>{let{videoElement:y,logger:R}=this.params,V=S(e.jidxUrl),N,O,q,v,E=0,F,Se,Ce,k=()=>{F&&(clearTimeout(F),F=void 0);let C=Math.max(gk,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ee=E+C,Q=X(),oe=Math.min(1e4,ee-Q);E=Q;let ve=()=>{l||d()&&V.seek(()=>{d()&&(E=X(),M(),k())})};oe>0?F=window.setTimeout(()=>{this.paused?k():ve()},oe):ve()},M=()=>{let C;for(;C=V.nextChunk(v);)v=C,ei(C);let ee=V.nextChunk(q);if(ee){if(q&&ee.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?k():(T(),this._initPlayerWith(e));return}dt(ee)}else k()},A=(C,ee)=>{if(!d()||!this.sourceBuffer)return;let Q,oe,ve,et=Ge=>{window.setTimeout(()=>{d()&&A(C,ee)},Ge)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),et(100);else{let Ge=X(),tt=y.currentTime;!this.paused&&y.buffered.length>1&&Se===tt&&Ge-Ce>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),Se!==tt&&(Se=tt,Ce=Ge);let Qe=this._getBufferSizeSec();if(Qe>30)R(`Buffered ${Qe} seconds; delaying appendBuffer`),et(2e3);else try{this.sourceBuffer.appendBuffer(C),this.videoPlayStarted?(this.bufferStates.push({ts:Ge,buf:Qe}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ee&&ee()}catch(ti){if(ti.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),ve=this.sourceBuffer.buffered.length,ve!==0&&(Q=this.sourceBuffer.buffered.start(0),oe=tt,oe-Q>4&&this.sourceBuffer.remove(Q,oe-3)),et(1e3);else throw ti}}},Y=()=>{O&&N&&(R([`Appending chunk, sz=${O.byteLength}:`,JSON.stringify(q)]),A(O,function(){O=null,M()}))},Z=C=>e.fragUrlTemplate.replace("%%id%%",C.chunkIdx),dt=C=>{d()&&h(Z(C),(ee,Q)=>{if(d()){if(Q/=1e3,O=ee,q=C,n=C.startTS,Q){let oe=Math.min(10,C.dur/Q);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*oe:oe}Y()}},()=>this._handleNetworkError())},ei=C=>{d()&&(gr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Z(C),!1)))},Lt=C=>{d()&&(e.cachedHeader=C,A(C,()=>{N=!0,Y()}))};s=!0,V.seek(C=>{if(d()){if(E=X(),!C){k();return}v=C,!pk(w)||C.startTS>w?dt(C):(q=C,M())}},w),e.cachedHeader?Lt(e.cachedHeader):p(e.headerUrl,Lt,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),ds(a)&&(a+=.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,gr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ds(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=X();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Zo(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=X();d<o&&(n=p),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=wi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ps).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;me(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},mk))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Sk,filter as wf,fromEvent as vk,interval as yk,isHigher as Tk,isInvariantQuality as Ik,isLower as Ek,merge as xk,Subject as Af,Subscription as Pk}from"@vkontakte/videoplayer-shared";var iu=class{constructor(){this.onDroopedVideoFramesLimit$=new Af;this.subscription=new Pk;this.playing=!1;this.tracks=[];this.forceChecker$=new Af;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&&!Ik(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(i-a)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Tk(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(vk(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=yk(this.droppedFramesChecker.checkTime).pipe(wf(()=>this.playing),wf(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(Sk(this.droppedFramesChecker.checkTime)),i=xk(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=Object.entries(this.limitCounts).filter(([,i])=>i>=this.droppedFramesChecker.countLimit).sort(([i],[a])=>Ek(i,a)?-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}},hs=iu;import{map as kk,Observable as wk}from"@vkontakte/videoplayer-shared";import{fromEvent as Ak}from"@vkontakte/videoplayer-shared";var vr=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var Rk=(r,e)=>new wk(t=>{if(!window.IntersectionObserver)return;let i={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||vr()))},{...i,...e});a.observe(r);let s=Ak(document,"visibilitychange").pipe(kk(n=>!document.hidden||vr())).subscribe(n=>t.next(n));return()=>{a.unobserve(r),s.unsubscribe}}),De=Rk;var _k=["paused","playing","ready"],Nk=["paused","playing","ready"],yr=class{constructor(e){this.subscription=new Vk;this.videoState=new $("stopped");this.representations$=new au([]);this.textTracksManager=new Le;this.droppedFramesManager=new hs;this.maxSeekBackTime$=new au(1/0);this.zeroTime$=new au(void 0);this.liveOffset=new ot;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:Lf.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,i=[];for(let a of t){let s=a.name??a.index.toString(10),n=vt(a.name)??Ok(a.video),o=a.bitrate/1e3,u={...a.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};i.push({track:l,representation:a})}this.representations$.next(i),this.params.output.availableVideoTracks$.next(i.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,i=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),ru(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(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Nk.includes(e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&_k.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(te(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(te(this.params.source.url,u))}return;default:return Rf(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Lf.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Df(this.videoState.stateChangeStarted$.pipe(ms(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ms(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ce(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(K(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=he(this.video);this.subscription.add(this.representations$.pipe(ms(a=>a.map(({track:s})=>s)),Mf(a=>!!a.length),Ck()).subscribe(a=>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:a}))),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(Mk(),ms(a=>-a/1e3)).subscribe(this.params.output.duration$)).add($k({zeroTime:this.zeroTime$.pipe(Mf(ru)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Ke(this.video,this.params.desiredState.isLooped,t)).add(pe(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add($e(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(De(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&Bk(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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 Rf(a.to)}},t)).add(Df(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Dk(["init"])).pipe(Lk(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),de(this.video)}createLiveDashPlayer(){let e=new Sr({videoElement:this.video,videoState:this.videoState,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(),a=!i&&ru(t)?t:Tt(e.map(({track:l})=>l),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},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=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(i),n||u||s!==o){let l=e.find(({track:c})=>c.id===s)?.representation;$f(l,"Representations missing"),this.dash.startPlay(l,i)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:i})=>i.id===e.id)?.representation;$f(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(),a=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(te(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Cf=yr;var Je=(r,e)=>{let t=0;for(let i=0;i<r.length;i++){let a=r.start(i)*1e3,s=r.end(i)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as yA,assertNonNullable as TA,debounce as IA,ErrorCategory as Bu,filter as rg,filterChanged as aa,fromEvent as EA,isNonNullable as ag,map as Ou,merge as Ds,observableFrom as xA,observeElementSize as PA,once as sg,Subscription as kA,ValueSubject as wA}from"@vkontakte/videoplayer-shared";var fs=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 a=0,s=i.length;a<s;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let a=0,s=i.length;a<s;a++){let n=i[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},Ai=class extends fs{constructor(){super(),this.listeners||fs.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)}},Tr=class{constructor(){Object.defineProperty(this,"signal",{value:new Ai,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document>"u")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch{i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Tr.prototype[Symbol.toStringTag]="AbortController",Ai.prototype[Symbol.toStringTag]="AbortSignal");function bs(r){return r.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof r.Request=="function"&&!r.Request.prototype.hasOwnProperty("signal")||!r.AbortController}function su(r){typeof r=="function"&&(r={fetch:r});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=r;if(!bs({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Ir=bs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Vf=Ir?su({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ue=Ir?Vf.fetch:window.fetch,V0=Ir?Vf.Request:window.Request,ie=Ir?Tr:window.AbortController,B0=Ir?Ai:window.AbortSignal;var vs=Oe(ki(),1);var lt=()=>window.ManagedMediaSource||window.MediaSource,gs=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Bf=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),Of=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Is,clientChecker as ys}from"@vkontakte/videoplayer-shared";var Ts=document.createElement("video"),Uk='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Hk='video/mp4; codecs="hev1.1.6.L93.B0"',_f='video/webm; codecs="vp09.00.10.08"',Nf='video/webm; codecs="av01.0.00M.08"',jk='audio/mp4; codecs="mp4a.40.2"',Gk='audio/webm; codecs="opus"',Er={mms:gs(),mse:Bf(),hls:!!(Ts.canPlayType?.("application/x-mpegurl")||Ts.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},fe={mp4:!!Ts.canPlayType?.("video/mp4"),webm:!!Ts.canPlayType?.("video/webm"),cmaf:!0},be={h264:!!lt()?.isTypeSupported?.(Uk),h265:!!lt()?.isTypeSupported?.(Hk),vp9:!!lt()?.isTypeSupported?.(_f),av1:!!lt()?.isTypeSupported?.(Nf),aac:!!lt()?.isTypeSupported?.(jk),opus:!!lt()?.isTypeSupported?.(Gk)},Ri=(be.h264||be.h265)&&be.aac,Ht,Qk=async()=>{if(!window.navigator.mediaCapabilities)return;let r={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:Nf}}),window.navigator.mediaCapabilities.decodingInfo({...r,video:{...r.video,contentType:_f}})]);Ht={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Qk()}catch(r){console.error(r)}var $i=Er.hls&&fe.mp4,Ff=()=>Object.keys(be).filter(r=>be[r]),qf=(r,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let a=Er.mse&&(!i||!!window.MediaStreamTrack)||Er.mms&&t;return r.filter(s=>{switch(s){case"DASH_SEP":return a&&fe.mp4&&Ri;case"DASH_WEBM":return a&&fe.webm&&be.vp9&&be.opus;case"DASH_WEBM_AV1":return a&&fe.webm&&be.av1&&be.opus;case"DASH_STREAMS":return a&&(fe.mp4&&Ri||fe.webm&&(be.vp9||be.av1)&&(be.opus||be.aac));case"DASH_LIVE":return a&&fe.mp4&&Ri;case"DASH_LIVE_CMAF":return a&&fe.mp4&&Ri&&fe.cmaf;case"DASH_ONDEMAND":return a&&fe.mp4&&Ri;case"HLS":case"HLS_ONDEMAND":return $i||e&&a&&fe.mp4&&Ri;case"HLS_LIVE":case"HLS_LIVE_CMAF":return $i;case"MPEG":return fe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Er.webrtc&&Er.ws&&be.h264&&(fe.mp4||fe.webm);default:return Is(s)}})},Ss=r=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(r){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Ht?Ht[t].smooth?[t,e]:Ht[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Ht?Ht[t].powerEfficient?[t,e]:Ht[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Is(r)}return[e,t]},Uf=({webmCodec:r,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...Ss(r),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(ys.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...Ss(r),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ss(r),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ss(r),...a,"HLS","HLS_ONDEMAND"];default:Is(e)}return $i?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Hf=({androidPreferredFormat:r,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...a],n=[...a,...i],o,u=ys.isMac&&ys.isSafari;if(ys.isAndroid)switch(r){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Is(r)}else $i&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},nu=r=>r?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],jf=r=>{if(r.size===0)return;if(r.size===1){let t=r.values().next();return(0,vs.default)(t.value.split("."),0)}for(let t of r){let i=(0,vs.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=r.values().next();return(0,vs.default)(e.value.split("."),0)};import{ErrorCategory as xr}from"@vkontakte/videoplayer-shared";var Gf=r=>{if(!r)return{id:"EmptyResponse",category:xr.PARSER,message:"Empty response"};if(r.length<=2&&r.match(/^\d+$/))return{id:`UVError#${r}`,category:xr.NETWORK,message:`UV Error ${r}`};let e=r.trimStart().substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:xr.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(r,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:xr.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:xr.PARSER,message:"Response is valid XML, but parser failed"}};var It=(r,e,t=0)=>{for(let i=0;i<r.length;i++)if(r.start(i)*1e3-t<=e&&r.end(i)*1e3+t>e)return!0;return!1};import{abortable as Lu,assertNonNullable as Kt,clientChecker as sA,combine as As,ErrorCategory as kt,filter as Mu,filterChanged as Wb,flattenObject as ia,fromEvent as Xt,getTraceSubscriptionMethod as nA,interval as Du,isNonNullable as Yb,map as Cu,merge as Jt,now as oA,Subject as zb,Subscription as Kb,tap as uA,throttle as lA,ValueSubject as W}from"@vkontakte/videoplayer-shared";var Di=Oe(ki(),1);var Wk=(r,e={})=>{let i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{r({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Yk=r=>window.clearTimeout(r),Qf=r=>typeof r=="function"&&r?.toString().endsWith("{ [native code] }"),Wf=!Qf(window.requestIdleCallback)||!Qf(window.cancelIdleCallback),ou=Wf?Wk:window.requestIdleCallback,K0=Wf?Yk:window.cancelIdleCallback;var Nb=Oe(ns(),1);import{assertNever as zk,ErrorCategory as Yf,clientChecker as uu,Subject as zf}from"@vkontakte/videoplayer-shared";var Kk=18,Kf=!1;try{Kf=uu.isSafari&&!!uu.macVersion&&uu.macVersion<=Kk}catch(r){console.error(r)}var lu=class{constructor(e){this.bufferFull$=new zf;this.error$=new zf;this.queue=[];this.currentTask=null;this.destroyed=!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:Yf.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 a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let i;Kf&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);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)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(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Yf.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:zk(t)}}},Xf=lu;var cu=r=>{let e=0;for(let t=0;t<r.length;t++)e+=r.end(t)-r.start(t);return e*1e3};import{abortable as Wt,assertNonNullable as J,ErrorCategory as xt,fromEvent as ku,getExponentialDelay as wu,isNonNullable as Yr,isNullable as xe,now as Es,once as zw,Subject as Kw,Subscription as Xw,ValueSubject as zr}from"@vkontakte/videoplayer-shared";var _=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 Li=class extends _{};var Pr=class extends _{};var kr=class extends _{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let a=this.readString(4);this.compatibleBrands.push(a),i-=4}}};var wr=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var H=class extends _{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var Ar=class extends H{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var Rr=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $r=class extends _{constructor(e,t){super(e,t),this.data=this.content}};var jt=class extends H{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let i=0;i<this.referenceCount;i++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Lr=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Mr=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Dr=class extends H{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Cr=class extends H{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Vr=class extends H{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Br=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Or=class extends H{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 _r=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Nr=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Fr=class extends H{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var qr=class extends _{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ur=class extends H{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 Hr=class extends H{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 jr=class extends H{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 a=0;a<this.sampleCount;a++)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 Jk={ftyp:kr,moov:wr,mvhd:Ar,moof:Rr,mdat:$r,sidx:jt,trak:Lr,mdia:Br,mfhd:Fr,tkhd:Or,traf:qr,tfhd:Ur,tfdt:Hr,trun:jr,minf:_r,sv3d:Mr,st3d:Dr,prhd:Cr,proj:Nr,equi:Vr,uuid:Pr,unknown:Li},Et=class r{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i));if(!n.size)break;t.push(n),i+=n.size}catch{break}return t}createBox(e,t){let i=Jk[e];return i?new i(t,new r):new Li(t,new r)}};var Gt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var ew=new TextDecoder("ascii"),tw=r=>ew.decode(new DataView(r.buffer,r.byteOffset+4,4))==="ftyp",iw=r=>{let e=new jt(r,new Et),t=e.earliestPresentationTime/e.timescale*1e3,i=r.byteOffset+r.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},rw=(r,e)=>{let i=new Et().parse(r),a=new Gt(i),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(r.buffer,l,d)},aw=r=>{let t=new Et().parse(r);return new Gt(t).find("sidx")?.timescale},sw=(r,e)=>{let i=new Et().parse(r),s=new Gt(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},nw=r=>{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 Et().parse(r),a=new Gt(i);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Jf={validateData:tw,parseInit:nw,getIndexRange:()=>{},parseSegments:iw,parseFeedableSegmentChunk:rw,getChunkEndTime:sw,getTimescaleFromIndex:aw};import{assertNonNullable as pu,isNonNullable as ib,isNullable as uw}from"@vkontakte/videoplayer-shared";import{assertNever as ow}from"@vkontakte/videoplayer-shared";var Zf={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"}},eb=r=>{let e=r.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=Gr(r,t),a=i in Zf,s=a?Zf[i].type:"binary",n=r.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(r.buffer,r.byteOffset+t+1,o-1),l=n&255>>o,c=Gr(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>r.byteLength?h=new DataView(r.buffer,r.byteOffset+p):h=new DataView(r.buffer,r.byteOffset+p,d),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Gr=(r,e=r.byteLength)=>{switch(e){case 1:return r.getUint8(0);case 2:return r.getUint16(0);case 3:return r.getUint8(0)*2**16+r.getUint16(1);case 4:return r.getUint32(0);case 5:return r.getUint8(0)*2**32+r.getUint32(1);case 6:return r.getUint16(0)*2**32+r.getUint32(2);case 7:{let t=r.getUint8(0)*281474976710656+r.getUint16(1)*4294967296+r.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},He=(r,e)=>{switch(e){case"int":return r.getInt8(0);case"uint":return Gr(r);case"float":return r.byteLength===4?r.getFloat32(0):r.getFloat64(0);case"string":return new TextDecoder("ascii").decode(r);case"utf8":return new TextDecoder("utf-8").decode(r);case"date":return new Date(Date.UTC(2001,0)+r.getInt8(0)).getTime();case"master":return r;case"binary":return r;default:ow(e)}},Qt=(r,e)=>{let t=0;for(;t<r.byteLength;){let i=new DataView(r.buffer,r.byteOffset+t),a=eb(i);if(!e(a))return;a.type==="master"&&Qt(a.value,e),t=a.value.byteOffset-r.byteOffset+a.valueSize}},tb=r=>{if(r.getUint32(0)!==440786851)return!1;let e,t,i,a=eb(r);return Qt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=He(o,n):s===17026?t=He(o,n):s===17029&&(i=He(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var rb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],lw=[231,22612,22743,167,171,163,160,175],cw=r=>{let e,t,i,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Qt(r,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=He(m,h);l=Gr(g)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?i=He(m,h):p===17545?a=He(m,h):p===21420&&l===475249515?u=He(m,h):p===374648427?Qt(m,({tag:g,type:S,value:T})=>g===30321?(c=He(T,S)===1,!1):!0):s&&n&&rb.includes(p)&&(o=!0),!o}),pu(e,"Failed to parse webm Segment start"),pu(t,"Failed to parse webm Segment end"),pu(a,"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(a/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},dw=r=>{if(uw(r.cuesSeekPosition))return;let e=r.segmentStart+r.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},pw=(r,e)=>{let t=!1,i=!1,a=o=>ib(o.time)&&ib(o.position),s=[],n;return Qt(r,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=He(l,u));break;case 183:break;case 241:n&&(n.position=He(l,u));break;default:t&&rb.includes(o)&&(i=!0)}return!(t&&i)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},hw=r=>{let e=0,t=!1;try{Qt(r,i=>i.tag===524531317?i.tagSize<=r.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):lw.includes(i.tag)?(e+i.tagSize<=r.byteLength&&(e+=i.tagSize,t||=[163,160,175].includes(i.tag)),!0):!1)}catch{}return e>0&&e<=r.byteLength&&t?new DataView(r.buffer,r.byteOffset,e):null},ab={validateData:tb,parseInit:cw,getIndexRange:dw,parseSegments:pw,parseFeedableSegmentChunk:hw};var Qr=r=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(r);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return ab;case"mp4":return Jf}}throw new ReferenceError(`Unsupported mime type ${r}`)},sb=r=>"getChunkEndTime"in r;var vu=Oe(wb(),1),Db=Oe(ki(),1);var Su=r=>{let e=r.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=i;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=i[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return["6E","7A","F4"].includes(o)}}return!1};import{isNonNullable as $b,isNullable as Lb}from"@vkontakte/videoplayer-shared";var Ab=r=>{if(r.includes("/")){let e=r.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(r)};var Rb=r=>{try{let e=Ww(),t=r.match(e),{groups:i}=t??{};if(i){let a={};if(i.extensions){let o=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{a[u[0]]=u.slice(2)})}let s=i.variants?.split(/-/).filter(o=>o!==""),n={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:a,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function Ww(){let r="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
62
|
-
(?<language>${`(?:[a-z]{2,3}(?:-${
|
|
61
|
+
[selected audio track] ${f?.id}
|
|
62
|
+
`}),f&&bb(a,u,f,o)};var Z=i=>new URL(i).hostname;import{assertNever as Ab,assertNonNullable as wb,combine as nR,debounce as oR,ErrorCategory as Rb,filter as $b,filterChanged as uR,isNonNullable as Eu,map as As,merge as Lb,observableFrom as lR,once as cR,Subscription as dR,ValueSubject as xu,videoQualityToHeight as pR,videoSizeToQuality as hR}from"@vkontakte/videoplayer-shared";var vb=$(Ke(),1),Sb=i=>{if(i instanceof DOMException&&(0,vb.default)(["Failed to load because no supported source was found.","The element has no supported sources."],i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},be=async(i,e)=>{let t=i.muted;try{await i.play()}catch(r){if(!Sb(r))return!1;if(e&&e(),t)return console.warn(r),!1;i.muted=!0;try{await i.play()}catch(a){return Sb(a)&&(i.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as xs,isNullable as Uw,assertNonNullable as Ai}from"@vkontakte/videoplayer-shared";var Tb=$(ut(),1);import{isNonNullable as yb,assertNonNullable as Es,now as Fw}from"@vkontakte/videoplayer-shared";function ee(){return Fw()}function vu(i){return ee()-i}function yu(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Ib(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Br(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Es(c);let T=vu(c),q;if(T<b){q=b-T,setTimeout(g,q);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,R()},S=T=>(s=T,v),k=T=>(d=T,v),E=()=>(h="json",v),A=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},y=T=>(p=T,v),R=()=>{c=ee(),n=new a,n.open("get",i);let T=0,q,ye=0,Oe=()=>(Es(c),Math.max(c,Math.max(q||0,ye||0)));if(s&&n.addEventListener("progress",P=>{let C=ee();s.updateChunk&&P.loaded>T&&(s.updateChunk(Oe(),P.loaded-T),T=P.loaded,q=C)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>A())),n.addEventListener("load",()=>{if(u)return;Es(n);let P=n.status;if(P>=200&&P<300){if(n.response.byteLength&&s){let C=n.response.byteLength-T;C&&s.updateChunk&&s.updateChunk(Oe(),C)}n.responseType==="json"&&!(0,Tb.default)(Object,n.response).length?A():(d&&d(),e(n.response))}else A()}),n.addEventListener("error",()=>{A()}),p){let P=()=>{Es(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ye=ee(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=h,n.send(),v},v={withBitrateReporting:S,withParallel:y,withJSONResponse:E,withRetryCount:T=>(l=T,v),withRetryInterval:(T,q)=>(yb(T)&&(b=T),yb(q)&&(f=q),v),withTimeout:T=>(o=T,v),withFinally:k,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return v}var Pi=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,r){return{start:e,end:t,bytes:r}}_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 r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&r>0){let s=a*8/(r/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(a)}/${Math.round(r)} 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,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Eb=$(ut(),1);var ki=class{constructor(e,t,r,a,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=r,this.MAX_PARALLEL_REQUESTS=a,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 r=ee(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ee()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Br(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ee()}_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=ee();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Eb.default)(Object,this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,a){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=a,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}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=a,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as Hw}from"@vkontakte/videoplayer-shared";var Ps=1e4,Tu=3;var jw=6e4,Gw=10,Qw=1,Ww=500,wi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=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.params=e,this.soundProhibitedEvent$=new Hw,this.chunkRateEstimator=new Pi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=yu(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,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=yu(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,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-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}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.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,r=t.buffered.length,a;r!==0&&(a=t.buffered.start(r-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){let{videoElement:t}=this.params,r,a,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!a||s.bitrate>a.bitrate)&&(a=s):(!r||r.bitrate>s.bitrate)&&(r=s));return a||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||xs(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:a,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Ib(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ki(Tu,Ps,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let A=s&&(!c||c===this.rep);return A||t("Not running!"),A},p=(A,y,R)=>{u&&u.abort(),u=Br(this.urlResolver.resolve(A,!1),y,R,()=>this._retryCallback()).withTimeout(Ps).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Tu).withFinally(()=>{u=null}).send()},h=(A,y,R)=>{Ai(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(A,!1),y,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=A=>{let y=r.playbackRate;r.playbackRate!==A&&(t(`Playback rate switch: ${y}=>${A}`),r.playbackRate=A)},b=A=>{this.lowLatency=A,t(`lowLatency changed to ${A}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let A=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=ee()-1e4,V=0;for(let _=0;_<this.bufferStates.length;_++){let U=this.bufferStates[_];A=Math.min(A,U.buf),U.ts<R&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${A} drop=${V} jitter=${this.sourceJitter}`);let F=A-Qw;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?f(1.15):F>1?f(1.1):F>.3?f(1.05):f(1)}},S=A=>{let y,R=()=>y&&y.start?y.start.length:0,V=P=>y.start[P]/1e3,F=P=>y.dur[P]/1e3,_=P=>y.fragIndex+P,U=(P,C)=>({chunkIdx:_(P),startTS:V(P),dur:F(P),discontinuity:C}),v=()=>{let P=0;if(y&&y.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,w=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,K=C;this.sourceJitter>1&&(K+=this.sourceJitter-1);let te=y.dur.length-1;for(;te>=0&&(K-=y.dur[te],!(K<=0));--te);P=Math.min(te,y.dur.length-1-w),P=Math.max(P,0)}return U(P,!0)},T=P=>{let C=R();if(!(C<=0)){if(xs(P)){for(let w=0;w<C;w++)if(V(w)>P)return U(w)}return v()}},q=P=>{let C=R(),w=P?P.chunkIdx+1:0,K=w-y.fragIndex;if(!(C<=0)){if(!P||K<0||K-C>Gw)return t(`Resync: offset=${K} bChunks=${C} chunk=`+JSON.stringify(P)),v();if(!(K>=C))return U(w-y.fragIndex,!1)}},ye=(P,C,w)=>{l&&l.abort(),l=Br(this.urlResolver.resolve(P,!0,this.lowLatency),C,w,()=>this._retryCallback()).withTimeout(Ps).withRetryCount(Tu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,C)=>{ye(A,w=>{if(!d())return;y=w;let K=!!y.lowLatency;K!==this.lowLatency&&b(K);let te=0;for(let bt=0;bt<y.dur.length;++bt)te+=y.dur[bt];te>0&&(Ai(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/y.dur.length)),a({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,P(T(C))},()=>this._handleNetworkError())},nextChunk:q}},k=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ai(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:A=>{let{videoElement:y,logger:R}=this.params,V=S(e.jidxUrl),F,_,U,v,T=0,q,ye,Oe,P=()=>{q&&(clearTimeout(q),q=void 0);let O=Math.max(Ww,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),re=T+O,Y=ee(),ce=Math.min(1e4,re-Y);T=Y;let Te=()=>{l||d()&&V.seek(()=>{d()&&(T=ee(),C(),P())})};ce>0?q=window.setTimeout(()=>{this.paused?P():Te()},ce):Te()},C=()=>{let O;for(;O=V.nextChunk(v);)v=O,lr(O);let re=V.nextChunk(U);if(re){if(U&&re.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?P():(k(),this._initPlayerWith(e));return}bt(re)}else P()},w=(O,re)=>{if(!d()||!this.sourceBuffer)return;let Y,ce,Te,rt=je=>{window.setTimeout(()=>{d()&&w(O,re)},je)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),rt(100);else{let je=ee(),it=y.currentTime;!this.paused&&y.buffered.length>1&&ye===it&&je-Oe>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),ye!==it&&(ye=it,Oe=je);let Ge=this._getBufferSizeSec();if(Ge>30)R(`Buffered ${Ge} seconds; delaying appendBuffer`),rt(2e3);else try{this.sourceBuffer.appendBuffer(O),this.videoPlayStarted?(this.bufferStates.push({ts:je,buf:Ge}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),re&&re()}catch(cr){if(cr.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Te=this.sourceBuffer.buffered.length,Te!==0&&(Y=this.sourceBuffer.buffered.start(0),ce=it,ce-Y>4&&this.sourceBuffer.remove(Y,ce-3)),rt(1e3);else throw cr}}},K=()=>{_&&F&&(R([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(U)]),w(_,function(){_=null,C()}))},te=O=>e.fragUrlTemplate.replace("%%id%%",O.chunkIdx),bt=O=>{d()&&h(te(O),(re,Y)=>{if(d()){if(Y/=1e3,_=re,U=O,n=O.startTS,Y){let ce=Math.min(10,O.dur/Y);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ce:ce}K()}},()=>this._handleNetworkError())},lr=O=>{d()&&(Ai(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(O),!1)))},_t=O=>{d()&&(e.cachedHeader=O,w(O,()=>{F=!0,K()}))};s=!0,V.seek(O=>{if(d()){if(T=ee(),!O){P();return}v=O,!Uw(A)||O.startTS>A?bt(O):(U=O,C())}},A),e.cachedHeader?_t(e.cachedHeader):p(e.headerUrl,_t,()=>this._handleNetworkError())},stop:k,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),xs(a)&&(a+=.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,Ai(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return xs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ee();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&vu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ee();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Br(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ps).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;be(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:a}=this.params,s=n=>{let o=[];return n?.length?(n.forEach((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({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))},jw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var kb=$(It(),1);import{debounce as Yw,filter as xb,fromEvent as zw,interval as Kw,isHigher as Jw,isInvariantQuality as Xw,isLower as Zw,merge as eR,Subject as Pb,Subscription as tR}from"@vkontakte/videoplayer-shared";var Iu=class{constructor(){this.onDroopedVideoFramesLimit$=new Pb;this.subscription=new tR;this.playing=!1;this.tracks=[];this.forceChecker$=new Pb;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&&!Xw(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,a=t-this.prevDroppedVideoFrames,s=1-(r-a)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&Jw(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(zw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Kw(this.droppedFramesChecker.checkTime).pipe(xb(()=>this.playing),xb(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(Yw(this.droppedFramesChecker.checkTime)),r=eR(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),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,kb.default)(Object,this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>Zw(r,a)?-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}},ks=Iu;import{map as rR,Observable as iR}from"@vkontakte/videoplayer-shared";import{fromEvent as aR}from"@vkontakte/videoplayer-shared";var Ri=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var sR=(i,e)=>new iR(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ri()))},{...r,...e});a.observe(i);let s=aR(document,"visibilitychange").pipe(rR(n=>!document.hidden||Ri())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Ce=sR;var mR=["paused","playing","ready"],fR=["paused","playing","ready"],$i=class{constructor(e){this.subscription=new dR;this.videoState=new L("stopped");this.representations$=new xu([]);this.textTracksManager=new Le;this.droppedFramesManager=new ks;this.maxSeekBackTime$=new xu(1/0);this.zeroTime$=new xu(void 0);this.liveOffset=new lt;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:Rb.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let t=e.manifest,r=[];for(let a of t){let s=a.name??a.index.toString(10),n=At(a.name)??hR(a.video),o=a.bitrate/1e3,u={...a.video};if(!n)continue;let l={id:s,quality:n,bitrate:o,size:u};r.push({track:l,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map(({track:a})=>a)),this.videoState.getTransition()?.to==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let t=e.quality,r=this.representations$.getValue().find(({representation:a})=>a===t)?.track;this.params.output.hostname$.next(new URL(t.headerUrl,this.params.source.url).hostname),Eu(r)&&this.params.output.currentVideoTrack$.next(r);break}case"bandwidth":{let{size:t,duration:r}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,r);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(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Pu.default)(fR,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,Pu.default)(mR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(se(this.params.source.url,u))}return;default:return Ab(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Rb.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Lb(this.videoState.stateChangeStarted$.pipe(As(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(As(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=pe(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(Z(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 r=fe(this.video);this.subscription.add(this.representations$.pipe(As(a=>a.map(({track:s})=>s)),$b(a=>!!a.length),cR()).subscribe(a=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:a}))),this.subscription.add(r.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(uR(),As(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(nR({zeroTime:this.zeroTime$.pipe($b(Eu)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Je(this.video,this.params.desiredState.isLooped,t)).add(me(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add($e(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ce(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&pR(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{switch(a.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 Ab(a.to)}},t)).add(Lb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,lR(["init"])).pipe(oR(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 wi({videoElement:this.video,videoState:this.videoState,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(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Eu(t)?t:Rt(e.map(({track:l})=>l),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},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=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(r),n||u||s!==o){let l=e.find(({track:c})=>c.id===s)?.representation;wb(l,"Representations missing"),this.dash.startPlay(l,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;wb(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(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(se(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Mb=$i;var ov=$(Ke(),1),pl=$(It(),1);var Ze=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as KL,assertNonNullable as JL,debounce as XL,ErrorCategory as cl,filter as av,filterChanged as ga,fromEvent as ZL,isNonNullable as sv,map as dl,merge as zs,observableFrom as eM,observeElementSize as tM,once as nv,Subscription as rM,ValueSubject as iM}from"@vkontakte/videoplayer-shared";var ws=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let a=0,s=r.length;a<s;a++)if(r[a].callback===t){r.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let a=0,s=r.length;a<s;a++){let n=r[a];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},_r=class extends ws{constructor(){super(),this.listeners||ws.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)}},Li=class{constructor(){Object.defineProperty(this,"signal",{value:new _r,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Li.prototype[Symbol.toStringTag]="AbortController",_r.prototype[Symbol.toStringTag]="AbortSignal");function Rs(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function ku(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Rs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Mi=Rs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Cb=Mi?ku({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,dt=Mi?Cb.fetch:window.fetch,T_=Mi?Cb.Request:window.Request,ke=Mi?Li:window.AbortController,I_=Mi?_r:window.AbortSignal;var ul=$(wu(),1);var Ru=$(ut(),1),Ms=$(Vr(),1);var pt=()=>window.ManagedMediaSource||window.MediaSource,$s=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),Zb=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),eg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Os,clientChecker as Cs}from"@vkontakte/videoplayer-shared";var Ds=document.createElement("video"),FR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',qR='video/mp4; codecs="hev1.1.6.L93.B0"',tg='video/webm; codecs="vp09.00.10.08"',rg='video/webm; codecs="av01.0.00M.08"',UR='audio/mp4; codecs="mp4a.40.2"',HR='audio/webm; codecs="opus"',Ci={mms:$s(),mse:Zb(),hls:!!(Ds.canPlayType?.("application/x-mpegurl")||Ds.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ge={mp4:!!Ds.canPlayType?.("video/mp4"),webm:!!Ds.canPlayType?.("video/webm"),cmaf:!0},Se={h264:!!pt()?.isTypeSupported?.(FR),h265:!!pt()?.isTypeSupported?.(qR),vp9:!!pt()?.isTypeSupported?.(tg),av1:!!pt()?.isTypeSupported?.(rg),aac:!!pt()?.isTypeSupported?.(UR),opus:!!pt()?.isTypeSupported?.(HR)},Nr=(Se.h264||Se.h265)&&Se.aac,Zt,jR=async()=>{if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:rg}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:tg}})]);Zt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{jR()}catch(i){console.error(i)}var Fr=Ci.hls&&ge.mp4,ig=()=>Object.keys(Se).filter(i=>Se[i]),ag=(i,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let a=Ci.mse&&(!r||!!window.MediaStreamTrack)||Ci.mms&&t;return i.filter(s=>{switch(s){case"DASH_SEP":return a&&ge.mp4&&Nr;case"DASH_WEBM":return a&&ge.webm&&Se.vp9&&Se.opus;case"DASH_WEBM_AV1":return a&&ge.webm&&Se.av1&&Se.opus;case"DASH_STREAMS":return a&&(ge.mp4&&Nr||ge.webm&&(Se.vp9||Se.av1)&&(Se.opus||Se.aac));case"DASH_LIVE":return a&&ge.mp4&&Nr;case"DASH_LIVE_CMAF":return a&&ge.mp4&&Nr&&ge.cmaf;case"DASH_ONDEMAND":return a&&ge.mp4&&Nr;case"HLS":case"HLS_ONDEMAND":return Fr||e&&a&&ge.mp4&&Nr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Fr;case"MPEG":return ge.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Ci.webrtc&&Ci.ws&&Se.h264&&(ge.mp4||ge.webm);default:return Os(s)}})},Ls=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Zt?Zt[t].smooth?[t,e]:Zt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Zt?Zt[t].powerEfficient?[t,e]:Zt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Os(i)}return[e,t]},sg=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Ls(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Cs.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...a,"MPEG",...Ls(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ls(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ls(i),...a,"HLS","HLS_ONDEMAND"];default:Os(e)}return Fr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},ng=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],a=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...a],n=[...a,...r],o,u=Cs.isMac&&Cs.isSafari;if(Cs.isAndroid)switch(i){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:Os(i)}else Fr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},$u=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],og=i=>{if(i.size===0)return;if(i.size===1){let t=(0,Ru.default)(i).next();return(0,Ms.default)(t.value.split("."),0)}for(let t of i){let r=(0,Ms.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=(0,Ru.default)(i).next();return(0,Ms.default)(e.value.split("."),0)};var wg=$(Ag(),1);import{ErrorCategory as Oi}from"@vkontakte/videoplayer-shared";var Rg=i=>{if(!i)return{id:"EmptyResponse",category:Oi.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:Oi.NETWORK,message:`UV Error ${i}`};let e=(0,wg.default)(i).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Oi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(i,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Oi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Oi.PARSER,message:"Response is valid XML, but parser failed"}};var $t=(i,e,t=0)=>{for(let r=0;r<i.length;r++)if(i.start(r)*1e3-t<=e&&i.end(r)*1e3+t>e)return!0;return!1};import{abortable as sl,assertNonNullable as sr,clientChecker as OL,combine as ha,ErrorCategory as Dt,filter as js,filterChanged as nl,flattenObject as ma,fromEvent as nr,getTraceSubscriptionMethod as VL,interval as ol,isNonNullable as zS,map as fa,merge as or,now as BL,Subject as KS,Subscription as JS,tap as _L,throttle as NL,ValueSubject as W}from"@vkontakte/videoplayer-shared";var _s=$(Ke(),1),jr=$(Vr(),1),Ns=$(wu(),1),et=$(ut(),1);var o$=(i,e={})=>{let r=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},u$=i=>window.clearTimeout(i),$g=i=>typeof i=="function"&&i?.toString().endsWith("{ [native code] }"),Lg=!$g(window.requestIdleCallback)||!$g(window.cancelIdleCallback),Ou=Lg?o$:window.requestIdleCallback,Vi=Lg?u$:window.cancelIdleCallback;var FS=$(It(),1);var qS=$(gs(),1);import{assertNever as l$,ErrorCategory as Mg,clientChecker as Vu,Subject as Cg}from"@vkontakte/videoplayer-shared";var c$=18,Dg=!1;try{Dg=Vu.isSafari&&!!Vu.macVersion&&Vu.macVersion<=c$}catch(i){console.error(i)}var Bu=class{constructor(e){this.bufferFull$=new Cg;this.error$=new Cg;this.queue=[];this.currentTask=null;this.destroyed=!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:Mg.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(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})}async remove(e,t,r){return r&&r.aborted?!1:new Promise(a=>{let s={operation:"remove",from:e,to:t,signal:r,callback:a};this.queue.unshift(s),this.pull()})}async abort(e){return new Promise(t=>{let r;Dg&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);r&&(this.queue=[r]),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)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(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Mg.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),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:l$(t)}}},Og=Bu;var _u=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};import{abortable as rr,assertNonNullable as le,ErrorCategory as Mt,fromEvent as el,getExponentialDelay as tl,isNonNullable as Vs,isNullable as De,now as Bs,once as PL,Subject as kL,Subscription as AL,ValueSubject as Hr}from"@vkontakte/videoplayer-shared";var N=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 qr=class extends N{};var Bi=class extends N{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let a=this.content.byteOffset,s=a+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(a,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var _i=class extends N{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var Ni=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var j=class extends N{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Fi=class extends j{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var qi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends N{constructor(e,t){super(e,t),this.data=this.content}};var er=class extends j{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Hi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends j{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Qi=class extends j{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Wi=class extends j{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Yi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends j{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Ki=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ji=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xi=class extends j{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends j{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ta=class extends j{constructor(t,r){super(t,r);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 ra=class extends j{constructor(t,r){super(t,r);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 a=0;a<this.sampleCount;a++)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 p$={ftyp:_i,moov:Ni,mvhd:Fi,moof:qi,mdat:Ui,sidx:er,trak:Hi,mdia:Yi,mfhd:Xi,tkhd:zi,traf:Zi,tfhd:ea,tfdt:ta,trun:ra,minf:Ki,sv3d:ji,st3d:Gi,prhd:Qi,proj:Ji,equi:Wi,uuid:Bi,unknown:qr},ht=class i{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch{break}return t}createBox(e,t){let r=p$[e];return r?new r(t,new i):new qr(t,new i)}};var Lt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var m$=new TextDecoder("ascii"),f$=i=>m$.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",b$=i=>{let e=new er(i,new ht),t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},g$=(i,e)=>{let r=new ht().parse(i),a=new Lt(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,d)},S$=i=>{let t=new ht().parse(i),r=new Lt(t),a={},s=r.findAll("uuid");return s.length?s[s.length-1]:a},v$=i=>{let t=new ht().parse(i);return new Lt(t).find("sidx")?.timescale},y$=(i,e)=>{let r=new ht().parse(i),s=new Lt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},T$=i=>{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}}},r=new ht().parse(i),a=new Lt(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Vg={validateData:f$,parseInit:T$,getIndexRange:()=>{},parseSegments:b$,parseFeedableSegmentChunk:g$,getChunkEndTime:y$,getServerLatencyTimestamps:S$,getTimescaleFromIndex:v$};var aa=$(Ke(),1);import{assertNonNullable as Fu,isNonNullable as Fg,isNullable as E$}from"@vkontakte/videoplayer-shared";import{assertNever as I$}from"@vkontakte/videoplayer-shared";var Bg={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"}},_g=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=ia(i,t),a=r in Bg,s=a?Bg[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,c=ia(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ia=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ue=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return ia(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:I$(e)}},tr=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=_g(r);if(!e(a))return;a.type==="master"&&tr(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Ng=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=_g(i);return tr(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Ue(o,n):s===17026?t=Ue(o,n):s===17029&&(r=Ue(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var qg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],x$=[231,22612,22743,167,171,163,160,175],P$=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return tr(i,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ue(f,h);l=ia(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ue(f,h):p===17545?a=Ue(f,h):p===21420&&l===475249515?u=Ue(f,h):p===374648427?tr(f,({tag:g,type:S,value:k})=>g===30321?(c=Ue(k,S)===1,!1):!0):s&&n&&(0,aa.default)(qg,p)&&(o=!0),!o}),Fu(e,"Failed to parse webm Segment start"),Fu(t,"Failed to parse webm Segment end"),Fu(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},k$=i=>{if(E$(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},A$=(i,e)=>{let t=!1,r=!1,a=o=>Fg(o.time)&&Fg(o.position),s=[],n;return tr(i,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ue(l,u));break;case 183:break;case 241:n&&(n.position=Ue(l,u));break;default:t&&(0,aa.default)(qg,o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},w$=i=>{let e=0,t=!1;try{tr(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,aa.default)(x$,r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=(0,aa.default)([163,160,175],r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Ug={validateData:Ng,parseInit:P$,getIndexRange:k$,parseSegments:A$,parseFeedableSegmentChunk:w$};var sa=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Ug;case"mp4":return Vg}}throw new ReferenceError(`Unsupported mime type ${i}`)};var Wu=$(uS(),1),LS=$(It(),1),MS=$(xS(),1),CS=$(ut(),1),DS=$(Vr(),1);var PS=$(Ke(),1),Qu=i=>{let e=i.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[a,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[a,s,n]=r;return!!(a&&parseInt(a,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let a=r[0];if(!a||a.length!==6)return!1;let[s,n]=a.toUpperCase(),o=s+n;return(0,PS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as wS,isNullable as RS}from"@vkontakte/videoplayer-shared";var kS=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var AS=i=>{try{let e=EL(),t=i.match(e),{groups:r}=t??{};if(r){let a={};if(r.extensions){let o=r.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(o||[]).forEach(u=>{a[u[0]]=u.slice(2)})}let s=r.variants?.split(/-/).filter(o=>o!==""),n={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.script,extensions:a,variants:s};return Object.keys(n).forEach(o=>{let u=n[o];(typeof u>"u"||u==="")&&delete n[o]}),n}return null}catch{return null}};function EL(){let i="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
63
|
+
(?<language>${`(?:[a-z]{2,3}(?:-${i})?|[a-z]{4}|[a-z]{5,8})`})
|
|
63
64
|
(-(?<script>[a-z]{4}))?
|
|
64
65
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
65
66
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
66
67
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
67
68
|
(?:-(?<privateuse>(?:${e})))?
|
|
68
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Mb=r=>{if(!r.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(r),a=i?.[1]==="-"?-1:1,s={days:e(i?.[5],a),hours:e(i?.[6],a),minutes:e(i?.[7],a),seconds:e(i?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ct=(r,e)=>{let t=r;t=(0,vu.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(i)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,vu.default)(t,n,(o,u)=>Lb(s)?o:Lb(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Cb=(r,e)=>{let i=new DOMParser().parseFromString(r,"application/xml"),a={video:[],audio:[],text:[]},s=i.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(y=>y.textContent?.trim()??""),u=(0,Db.default)(o,0)??"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),p=d?new Date(d).getTime():void 0,h,m=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),S=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)h=Mb(m);else if(b){let y=Mb(b);$b(y)&&(h=y)}else S&&(h=parseInt(S,10));let T=0,I=s.getAttribute("profiles")?.split(",")??[];for(let y of l){let R=y.getAttribute("id")??"id"+(T++).toString(10),V=y.getAttribute("mimeType")??"",N=y.getAttribute("codecs")??"",O=y.getAttribute("contentType")??V?.split("/")[0],q=y.getAttribute("profiles")?.split(",")??[],v=Rb(y.getAttribute("lang")??"")??{},E=y.querySelector("Label")?.textContent?.trim()??void 0,F=y.querySelectorAll("Representation"),Se=y.querySelector("SegmentTemplate"),Ce=y.querySelector("Role")?.getAttribute("value")??void 0,k=O,M={id:R,language:v.language,isDefault:Ce==="main",label:E,codecs:N,hdr:k==="video"&&Su(N),mime:V,representations:[]};for(let A of F){let Y=A.getAttribute("lang")??void 0,Z=A.getAttribute("label")??void 0,dt=A.querySelector("BaseURL")?.textContent?.trim()??"",ei=new URL(dt||u,e).toString(),Lt=A.getAttribute("mimeType")??V,C=A.getAttribute("codecs")??N??"",ee;if(O==="text"){let Q=A.getAttribute("id")||"",oe=v.privateuse?.includes("x-auto")||Q.includes("_auto"),ve=A.querySelector("SegmentTemplate");if(ve){let et={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},Ge=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,tt=parseInt(ve.getAttribute("startNumber")??"",10)??1,Qe=parseInt(ve.getAttribute("timescale")??"",10),ti=ve.querySelectorAll("SegmentTimeline S")??[],ii=ve.getAttribute("media");if(!ii)continue;let ga=[],Sa=0,va="",ri=0,Oi=tt,re=0;for(let Ve of ti){let Mt=parseInt(Ve.getAttribute("d")??"",10),ke=parseInt(Ve.getAttribute("r")??"",10)||0,pt=parseInt(Ve.getAttribute("t")??"",10);re=Number.isFinite(pt)?pt:re;let Dt=Mt/Qe*1e3,ai=re/Qe*1e3;for(let We=0;We<ke+1;We++){let ht=ct(ii,{...et,segmentNumber:Oi.toString(10),segmentTime:(re+We*Mt).toString(10)}),si=(ai??0)+We*Dt,Ni=si+Dt;Oi++,ga.push({time:{from:si,to:Ni},url:ht})}re+=(ke+1)*Mt,Sa+=(ke+1)*Dt}ri=re/Qe*1e3,va=ct(ii,{...et,segmentNumber:Oi.toString(10),segmentTime:re.toString(10)});let _i={time:{from:ri,to:1/0},url:va},it={type:"template",baseUrl:ei,segmentTemplateUrl:ii,initUrl:"",totalSegmentsDurationMs:Sa,segments:ga,nextSegmentBeyondManifest:_i,timescale:Qe};ee={id:Q,kind:"text",segmentReference:it,profiles:[],duration:h,bitrate:Ge,mime:"",codecs:"",width:0,height:0,isAuto:oe}}else ee={id:Q,isAuto:oe,kind:"text",url:ei}}else{let Q=A.getAttribute("contentType")??Lt?.split("/")[0]??O,oe=y.getAttribute("profiles")?.split(",")??[],ve=parseInt(A.getAttribute("width")??"",10),et=parseInt(A.getAttribute("height")??"",10),Ge=parseInt(A.getAttribute("bandwidth")??"",10)/1e3,tt=A.getAttribute("frameRate")??"",Qe=A.getAttribute("quality")??void 0,ti=tt?Ab(tt):void 0,ii=A.getAttribute("id")??"id"+(T++).toString(10),ga=Q==="video"?`${et}p`:Q==="audio"?`${Ge}Kbps`:C,Sa=`${ii}@${ga}`,va=[...I,...q,...oe],ri,Oi=A.querySelector("SegmentBase"),re=A.querySelector("SegmentTemplate")??Se;if(Oi){let it=A.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ve,Mt]=it.split("-").map(ht=>parseInt(ht,10)),ke={from:Ve,to:Mt},pt=A.querySelector("SegmentBase")?.getAttribute("indexRange"),[Dt,ai]=pt?pt.split("-").map(ht=>parseInt(ht,10)):[],We=pt?{from:Dt,to:ai}:void 0;ri={type:"byteRange",url:ei,initRange:ke,indexRange:We}}else if(re){let it={representationId:A.getAttribute("id")??void 0,bandwidth:A.getAttribute("bandwidth")??void 0},Ve=parseInt(re.getAttribute("timescale")??"",10),Mt=re.getAttribute("initialization")??"",ke=re.getAttribute("media"),pt=parseInt(re.getAttribute("startNumber")??"",10)??1,Dt=ct(Mt,it);if(!ke)throw new ReferenceError("No media attribute in SegmentTemplate");let ai=re.querySelectorAll("SegmentTimeline S")??[],We=[],ht=0,si="",Ni=0;if(ai.length){let ya=pt,Be=0;for(let ni of ai){let Ye=parseInt(ni.getAttribute("d")??"",10),Ct=parseInt(ni.getAttribute("r")??"",10)||0,Ta=parseInt(ni.getAttribute("t")??"",10);Be=Number.isFinite(Ta)?Ta:Be;let Ys=Ye/Ve*1e3,eS=Be/Ve*1e3;for(let Ia=0;Ia<Ct+1;Ia++){let tS=ct(ke,{...it,segmentNumber:ya.toString(10),segmentTime:(Be+Ia*Ye).toString(10)}),Ju=(eS??0)+Ia*Ys,iS=Ju+Ys;ya++,We.push({time:{from:Ju,to:iS},url:tS})}Be+=(Ct+1)*Ye,ht+=(Ct+1)*Ys}Ni=Be/Ve*1e3,si=ct(ke,{...it,segmentNumber:ya.toString(10),segmentTime:Be.toString(10)})}else if($b(h)){let Be=parseInt(re.getAttribute("duration")??"",10)/Ve*1e3,ni=Math.ceil(h/Be),Ye=0;for(let Ct=1;Ct<ni;Ct++){let Ta=ct(ke,{...it,segmentNumber:Ct.toString(10),segmentTime:Ye.toString(10)});We.push({time:{from:Ye,to:Ye+Be},url:Ta}),Ye+=Be}Ni=Ye,si=ct(ke,{...it,segmentNumber:ni.toString(10),segmentTime:Ye.toString(10)})}let Zg={time:{from:Ni,to:1/0},url:si};ri={type:"template",baseUrl:ei,segmentTemplateUrl:ke,initUrl:Dt,totalSegmentsDurationMs:ht,segments:We,nextSegmentBeyondManifest:Zg,timescale:Ve}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Q||!Lt)continue;let _i={video:"video",audio:"audio",text:"text"}[Q];if(!_i)continue;k||=_i,ee={id:Sa,kind:_i,segmentReference:ri,profiles:va,duration:h,bitrate:Ge,mime:Lt,codecs:C,width:ve,height:et,fps:ti,quality:Qe}}M.language||=Y,M.label||=Z,M.mime||=Lt,M.codecs||=C,M.hdr||=k==="video"&&Su(C),M.representations.push(ee)}k&&a[k].push(M)}return{dynamic:c,liveAvailabilityStartTime:p,duration:h,streams:a,baseUrls:o}};var Iu=Oe(ki(),1);import{videoSizeToQuality as Yw}from"@vkontakte/videoplayer-shared";var Vb=({id:r,width:e,height:t,bitrate:i,fps:a,quality:s})=>{let n=(s?vt(s):void 0)??Yw({width:e,height:t});return n&&{id:r,quality:n,bitrate:i,size:{width:e,height:t},fps:a}},Bb=({id:r,bitrate:e})=>({id:r,bitrate:e}),Ob=({language:r,label:e},{id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),_b=({language:r,label:e,id:t,url:i,isAuto:a})=>({id:t,url:i,isAuto:a,type:"internal",language:r,label:e}),Eu=({id:r,language:e,label:t,codecs:i,isDefault:a})=>({id:r,language:e,label:t,codec:(0,Iu.default)(i.split("."),0),isDefault:a}),xu=({id:r,language:e,label:t,hdr:i,codecs:a})=>({id:r,language:e,hdr:i,label:t,codec:(0,Iu.default)(a.split("."),0)}),Pu=r=>"url"in r,Ee=r=>r.type==="template",Wr=r=>r instanceof DOMException&&(r.name==="AbortError"||r.code===20);var Kr=class{constructor(e,t,i,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentSegmentLength$=new zr(0);this.onLastSegment$=new zr(!1);this.fullyBuffered$=new zr(!1);this.playingRepresentation$=new zr(void 0);this.playingRepresentationInit$=new zr(void 0);this.error$=new Kw;this.gaps=[];this.subscription=new Xw;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ie;this.switchAbortController=new ie;this.destroyAbortController=new ie;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=Wt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);J(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.resetAccumulateBufferAfterStall(),this.startAccumulateBuffer(),this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Xf(this.sourceBuffer),this.subscription.add(ku(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:xt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:xt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(ku(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:xt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,cu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Je(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),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),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);J(i,"No init buffer for starting representation"),J(a,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=Wt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);J(i,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(xe(s)||xe(a)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),J(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(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();Yr(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=Wt(this.destroyAbortController.signal,async function*(e){let t=e?.flatMap(u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!Ee(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let i=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(i);J(a);let s=this.segments.get(i);J(s,"No segments for starting representation");let n=this.initData.get(i);if(J(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,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}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ie,Wt(this.switchAbortController.signal,async function*(i,a=!1){this.switchingToRepresentationId=i;let s=this.representations.get(i);J(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(xe(o)||xe(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),J(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();Yr(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ie,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(xe(e)||xe(this.downloadingRepresentationId)||xe(this.playingRepresentationId)||xe(this.sourceBuffer)||Yr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(J(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let a=i.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Je(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&cu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=Je(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))l="high";else{let c=(0,Di.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&Je(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Di.default)(i,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,a=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+a}),i=s.time.to;Yr(t.duration)&&t.duration-i>0&&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,a=[],s=0,n=t.length-1;do a.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()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=e?.streams[this.kind].flatMap(a=>a.representations).find(a=>a.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=e?.streams[this.kind].flatMap(i=>i.representations)??[];for(let i of t){if(!i||!Ee(i.segmentReference))return;let a=i.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),s=this.segments.get(i.id)??[],n=(0,Di.default)(s,-1)?.time.to??0,o=a?.findIndex(u=>Math.floor(n)>=Math.floor(u.time.from)&&Math.floor(n)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(i.segmentReference);this.segments.set(i.id,u)}else{let u=a.slice(o+1);this.segments.set(i.id,[...s,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;J(e);let t=this.segments.get(e);if(t?.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}startAccumulateBuffer(){this.bufferAccumulation.enabled=!0}resetAccumulateBufferAfterStall(){J(this.playingRepresentationId);let e=this.representations.get(this.playingRepresentationId)?.duration;J(e);let{shortVideoDuration:t,shortVideoBufferStallSize:i,longVideoBufferStallSize:a}=this.tuning.dash.accumulationBufferStallSize;this.bufferAccumulation={enabled:!1,targetBufferSizeMs:e<=t?i:a,accumulatedBufferSizeMs:0,accumulated:[]}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let i=t.segmentReference;if(!Ee(i))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*i.timescale/1e3).toString(10),u=ct(i.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}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&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();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(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let a=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let b=p<=i&&h>=i,g=p>i||b||m===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&p<=i+S||h<=i+S;return(d==="none"||d==="partially_ejected"&&g&&T&&this.sourceBuffer&&!(It(this.sourceBuffer.buffered,p)&&It(this.sourceBuffer.buffered,h)))&&g&&T});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){Ee(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 a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Wt(o,async function*(){let c=wu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Es(),!c)return;let d=new DataView(c);if(!isFinite(a.segment.time.to)){let p=t.segmentReference.timescale,h=Qr(t.mime);a.segment.time.to=h.getChunkEndTime(d,p)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Wr(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())Ee(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Wt(n,async function*(){let u=wu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),ku(window,"online").pipe(zw()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=Es(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Wr(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ee(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,a={from:(0,Di.default)(e,0).byte.from,to:(0,Di.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Es(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:xt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ee(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 a=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Es();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:xt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Qr(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let c=l.byte.from-i,d=l.byte.to-i,p=d-c+1,h=c<a,m=d<=a;if(!h)continue;let b=Qr(o.mime),g=this.tuning.dash.enableSubSegmentBufferFeeding&&(sb(b)||this.bufferAccumulation.targetBufferSizeMs===0);if(l.status==="downloading"&&m){l.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+c,p),T=this.getCurrentPosition();Yr(T)&&(this.bufferAccumulation.accumulatedBufferSizeMs=l.time.to-T,this.bufferAccumulation.accumulated.push({dataView:S,segmentProgress:u}),this.activeSegments.delete(u));let I=async({dataView:w,segmentProgress:y})=>{await this.sourceBufferTaskQueue.append(w,s)&&!s.aborted?this.onSegmentFullyAppended(y,t):n()};this.bufferAccumulation.enabled&&this.bufferAccumulation.accumulatedBufferSizeMs>this.bufferAccumulation.targetBufferSizeMs?(this.bufferAccumulation.accumulated.forEach(I),this.resetAccumulateBufferAfterStall()):(!this.bufferAccumulation.enabled||!this.bufferAccumulation.targetBufferSizeMs||xe(T))&&(I({dataView:S,segmentProgress:u}),this.resetAccumulateBufferAfterStall())}else if(g&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-c),u.loadedBytes>u.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),T=u.loadedBytes===p?S:b.parseFeedableSegmentChunk(S);T?.byteLength&&(l.status="partially_fed",u.feedingBytes+=T.byteLength,await this.sourceBufferTaskQueue.append(T,s)&&!s.aborted?(u.fedBytes+=T.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){this.tuning.useSafariEndlessRequestBugfix&&(J(this.sourceBuffer),It(this.sourceBuffer.buffered,e.segment.time.from,100)&&It(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:xt.VIDEO_PIPELINE,message:"Safari 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",Pu(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let a of this.segments.get(i.id)??[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");J(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment]),this.tuning.useNewPruneBufferStrategy&&this.pruneBuffer(this.getCurrentPosition(),1/0,!1)}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[a,s]of this.initData.entries()){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=ou(()=>(0,Nb.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Wt(this.destroyAbortController.signal,async function*(){let o=wu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Qr(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ee(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:xt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of this.segments.values())for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||xe(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=Pu(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)["none","partially_ejected"].includes(h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(a.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||xe(e)?0:Je(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let a={representation:e,from:i.time.from,to:i.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){a=void 0;break}o>i.time.from&&o<i.time.to&&(a.from=o),n<i.time.to&&n>i.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){J(this.sourceBuffer);for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=ou(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:xt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(xe(this.sourceBuffer)||xe(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let a=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:s})}let t=100;for(let i of this.segments.values())for(let a of i){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Xr=r=>{let e=new URL(r);return e.searchParams.set("quic","1"),e.toString()};var Fb=r=>{let e=r.get("X-Delivery-Type"),t=r.get("X-Reused"),i=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:i,reused:a}};import{abortable as Jr,assertNever as Ub,fromEvent as Hb,merge as Jw,now as Zr,Subscription as Zw,ValueSubject as Au,flattenObject as Ci}from"@vkontakte/videoplayer-shared";var qb=r=>{let e=new URL(r);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var xs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Au(void 0);this.lastConnectionReused$=new Au(void 0);this.lastRequestFirstBytes$=new Au(void 0);this.abortAllController=new ie;this.subscription=new Zw;this.fetchManifest=Jr(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Xr(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=qb(i));let a=yield Ue(i,{signal:this.abortAllController.signal}).catch(ea);return a?(t.log("success",Ci({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Ci({url:i,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=Jr(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{c.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let v=new URL(l,location.href);v.searchParams.append("bytes",`${i.from}-${i.to}`),l=v.toString();break}default:Ub(t)}this.requestQuic&&(l=Xr(l));let p=this.abortAllController.signal,h;if(n){let v=new ie;if(h=Jw(Hb(this.abortAllController.signal,"abort"),Hb(n,"abort")).subscribe(()=>{try{v.abort()}catch(E){ea(E)}}),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(E){ea(E)}p=v.signal}let m=Zr();d.log("startRequest",Ci({url:l,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:m}));let b=yield Ue(l,{priority:s,headers:c,signal:p}).catch(ea),g=Zr();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-m),!b.ok||!b.body){h?.unsubscribe();let v=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:v}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let v=Zr(),E={requestStartedAt:m,requestEndedAt:v,duration:v-m};return d.log("endRequest",Ci(E)),d.end(),b.arrayBuffer()}let[S,T]=b.body.tee(),I=S.getReader();o&&this.throughputEstimator?.trackStream(T,u);let w=0,y=new Uint8Array(0),R=!1,V=v=>{h?.unsubscribe(),R=!0,ea(v)},N=Jr(p,async function*({done:v,value:E}){if(w===0&&this.lastRequestFirstBytes$.next(Zr()-m),p.aborted){h?.unsubscribe();return}if(!v&&E){let F=new Uint8Array(y.length+E.length);F.set(y),F.set(E,y.length),y=F,w+=E.byteLength,a?.(new DataView(y.buffer),w),yield I?.read().then(N,V)}}.bind(this));yield I?.read().then(N,V),h?.unsubscribe();let O=Zr(),q={failed:R,requestStartedAt:m,requestEndedAt:O,duration:O-m};return R?(d.error("endRequest",Ci(q)),d.end(),null):(d.log("endRequest",Ci(q)),d.end(),y.buffer)}.bind(this));this.fetchByteRangeRepresentation=Jr(this.abortAllController.signal,async function*(e,t,i){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=e.indexRange??t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,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;b=new DataView(S)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=Jr(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(i,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Fb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,i)??null;case"template":return await this.fetchTemplateRepresentation(e,i)??null;default:Ub(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ea=r=>{if(!Wr(r))throw r};var Yt=(r,e,t)=>t*e+(1-t)*r,Ru=(r,e)=>r.reduce((t,i)=>t+i,0)/e,jb=(r,e,t,i)=>{let a=0,s=t,n=Ru(r,e),o=e<i?e:i;for(let u=0;u<o;u++)r[s]>n?a++:a--,s=(r.length+s-1)%r.length;return Math.abs(a)===o};import{isNullable as eA,ValueSubject as Gb}from"@vkontakte/videoplayer-shared";var Pt=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 Gb(e.initial),this.debounced$=new Gb(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new se(`raw_${t}`),this.smoothedSeries$=new se(`smoothed_${t}`),this.reportedSeries$=new se(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;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)&&(eA(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 Ps=class extends Pt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Yt(this.slow,e,this.params.emaAlphaSlow),this.fast=Yt(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var ks=class extends Pt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ru(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Yt(this.emaSmoothed,e,this.params.emaAlpha);let i=jb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var ws=class extends Pt{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?Yt(this.smoothed,t,this.params.emaAlpha):t}};var zt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Ps({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ks({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ws({initial:e,label:"liveEdgeDelay",...t})}};var $u=(r,e)=>{r&&r.playbackRate!==e&&(r.playbackRate=e)};import{isNullable as tA,ValueSubject as iA}from"@vkontakte/videoplayer-shared";var ta=class r{constructor(e,t){this.currentRepresentation$=new iA(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(!tA(e))for(let t of this.representations)for(let i of t){let a=i.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...i,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let i=r.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=>r.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ee(t.segmentReference))}};var cA=["timeupdate","progress","play","seeked","stalled","waiting"],dA=["timeupdate","progress","loadeddata","playing","seeked"];var Rs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Kb;this.representationSubscription=new Kb;this.state$=new $("none");this.currentVideoRepresentation$=new W(void 0);this.currentVideoRepresentationInit$=new W(void 0);this.currentAudioRepresentation$=new W(void 0);this.currentVideoSegmentLength$=new W(0);this.currentAudioSegmentLength$=new W(0);this.error$=new zb;this.lastConnectionType$=new W(void 0);this.lastConnectionReused$=new W(void 0);this.lastRequestFirstBytes$=new W(void 0);this.currentLiveTextRepresentation$=new W(null);this.isLive$=new W(!1);this.liveDuration$=new W(0);this.liveAvailabilityStartTime$=new W(void 0);this.bufferLength$=new W(0);this.liveLoadBufferLength$=new W(0);this.livePositionFromPlayer$=new W(0);this.isLowLatency$=new W(!1);this.isActiveLowLatency$=new W(!1);this.currentStallDuration$=new W(0);this.videoLastDataObtainedTimestamp$=new W(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new zb;this.gapWatchdogActive=!1;this.destroyController=new ie;this.initManifest=Lu(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=te(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:kt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Lu(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:kt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Cb(e??"",this.manifestUrlString)}catch(n){let o=Gf(e)??{id:"ManifestParsing",category:kt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let i=(n,o,u)=>!!(this.element?.canPlayType?.(o)&<()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:p})=>i(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=jf(l);if(c&&(a[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=a.video.some(m=>m.hdr),h=a.video.some(m=>!m.hdr);sA.isHDR&&d&&p?a.video=a.video.filter(m=>m.hdr):h&&(a.video=a.video.filter(m=>!m.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",ia(s)),s}.bind(this));this.initRepresentations=Lu(this.destroyController.signal,async function*(e,t,i){this.tracer.log("initRepresentationsStart",ia({initialVideo:e,initialAudio:t,sourceHls:i})),Kt(this.manifest),Kt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(Xt(p,"error").pipe(Mu(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:kt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Of():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&gs())if(i){let p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Kr("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Yb(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Kr("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ta.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ta(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Du(1e3).subscribe(p=>{if(this.element?.paused){let h=No(this.manifestUrlString,2);this.manifestUrlString=te(this.manifestUrlString,h+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Jt(...dA.map(p=>Xt(this.element,p))).pipe(Cu(p=>this.element?Je(this.element.buffered,this.element.currentTime*1e3):0),Wb(),uA(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Jt(Xt(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Wb()).subscribe(h=>$u(this.element,1))),this.representationSubscription.add(As({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Mu(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(As({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:h,isActiveLowLatency:m})=>{if(!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-b,I=1;Math.abs(T)>g&&(I=1+Math.sign(T)*S),$u(this.element,I)})),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(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(As({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(lA(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(Kt(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=No(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,T=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,w=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,y=isFinite(h)?h:m,R=this.isActiveLowLatency$.getValue(),V=S<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(R&&V);let N="none";if(R?N="active_low_latency":this.isLowLatency$.getValue()&&V?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(O=>O.proceedLowLatencyLive()),N="active_low_latency"):g!==0&&y<T?N="live_forward_buffering":y<T+w&&(N="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),N==="live_forward_buffering"||N==="live_with_target_offset"){let O=p-(T+I),q=this.normolizeLiveOffset(Math.trunc(g+O/b)),v=Math.abs(q-g),E;!h||v<=this.tuning.dashCmafLive.offsetCalculationError?E=g:q>0&&v>this.tuning.dashCmafLive.offsetCalculationError?E=q:E=0,this.manifestUrlString=te(this.manifestUrlString,E,2)}N!=="none"&&N!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=Jt(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Cu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Jt(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Cu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(Jt(this.forceEnded$,As({allBuffersFull:l,someBufferEnded:c}).pipe(Mu(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:kt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(Jt(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>this.source?.addEventListener("sourceopen",p)));let d=[this.manifest.duration??0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{let h=[];return p.duration&&h.push(p.duration),Ee(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&Yb(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)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=Du(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:kt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new xs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveEstimatedDelay=zt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.initTracerSubscription()}async seekLive(e){Kt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=te(this.manifestUrlString,t,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(){Kt(this.element),this.state$.setState("running"),this.subscription.add(Jt(...cA.map(e=>Xt(this.element,e)),Xt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:kt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Xt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Xt(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&It(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let i={timeInWaiting:t},a=oA(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),i.position=p}this.tracer.log("stallIntervalCallback",ia(i))};this.videoBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.startAccumulateBuffer(),this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=Du(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:kt.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,i=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,i)}seek(e,t){Kt(this.element),Kt(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),It(this.element.buffered,i)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.startAccumulateBuffer(),this.videoBufferManager.maintain(i),this.audioBufferManager?.startAccumulateBuffer(),this.audioBufferManager?.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",ia({requestedPosition:e,forcePrecise:t,position:i}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.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=nA(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}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={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let i=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=i&&o.to+s>i&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ia(t)))}}};var $s=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ls=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 a=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:a,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 a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>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 Xb=`attribute vec2 a_vertex;
|
|
69
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var $S=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},mt=(i,e)=>{let t=i;t=(0,Wu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,LS.default)(Object,r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,Wu.default)(t,n,(o,u)=>RS(s)?o:RS(u)?s:(0,MS.default)(s,parseInt(u,10),"0"))}return t},OS=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from((0,CS.default)(s.querySelectorAll("MPD > BaseURL"))).map(y=>y.textContent?.trim()??""),u=(0,DS.default)(o,0)??"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),p=d?new Date(d).getTime():void 0,h,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),S=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)h=$S(f);else if(b){let y=$S(b);wS(y)&&(h=y)}else S&&(h=parseInt(S,10));let k=0,E=s.getAttribute("profiles")?.split(",")??[];for(let y of l){let R=y.getAttribute("id")??"id"+(k++).toString(10),V=y.getAttribute("mimeType")??"",F=y.getAttribute("codecs")??"",_=y.getAttribute("contentType")??V?.split("/")[0],U=y.getAttribute("profiles")?.split(",")??[],v=AS(y.getAttribute("lang")??"")??{},T=y.querySelector("Label")?.textContent?.trim()??void 0,q=y.querySelectorAll("Representation"),ye=y.querySelector("SegmentTemplate"),Oe=y.querySelector("Role")?.getAttribute("value")??void 0,P=_,C={id:R,language:v.language,isDefault:Oe==="main",label:T,codecs:F,hdr:P==="video"&&Qu(F),mime:V,representations:[]};for(let w of q){let K=w.getAttribute("lang")??void 0,te=w.getAttribute("label")??void 0,bt=w.querySelector("BaseURL")?.textContent?.trim()??"",lr=new URL(bt||u,e).toString(),_t=w.getAttribute("mimeType")??V,O=w.getAttribute("codecs")??F??"",re;if(_==="text"){let Y=w.getAttribute("id")||"",ce=v.privateuse?.includes("x-auto")||Y.includes("_auto"),Te=w.querySelector("SegmentTemplate");if(Te){let rt={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},je=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,it=parseInt(Te.getAttribute("startNumber")??"",10)??1,Ge=parseInt(Te.getAttribute("timescale")??"",10),cr=Te.querySelectorAll("SegmentTimeline S")??[],dr=Te.getAttribute("media");if(!dr)continue;let La=[],Ma=0,Ca="",pr=0,Yr=it,oe=0;for(let Ve of cr){let Nt=parseInt(Ve.getAttribute("d")??"",10),Re=parseInt(Ve.getAttribute("r")??"",10)||0,gt=parseInt(Ve.getAttribute("t")??"",10);oe=Number.isFinite(gt)?gt:oe;let Ft=Nt/Ge*1e3,hr=oe/Ge*1e3;for(let Qe=0;Qe<Re+1;Qe++){let St=mt(dr,{...rt,segmentNumber:Yr.toString(10),segmentTime:(oe+Qe*Nt).toString(10)}),mr=(hr??0)+Qe*Ft,Kr=mr+Ft;Yr++,La.push({time:{from:mr,to:Kr},url:St})}oe+=(Re+1)*Nt,Ma+=(Re+1)*Ft}pr=oe/Ge*1e3,Ca=mt(dr,{...rt,segmentNumber:Yr.toString(10),segmentTime:oe.toString(10)});let zr={time:{from:pr,to:1/0},url:Ca},at={type:"template",baseUrl:lr,segmentTemplateUrl:dr,initUrl:"",totalSegmentsDurationMs:Ma,segments:La,nextSegmentBeyondManifest:zr,timescale:Ge};re={id:Y,kind:"text",segmentReference:at,profiles:[],duration:h,bitrate:je,mime:"",codecs:"",width:0,height:0,isAuto:ce}}else re={id:Y,isAuto:ce,kind:"text",url:lr}}else{let Y=w.getAttribute("contentType")??_t?.split("/")[0]??_,ce=y.getAttribute("profiles")?.split(",")??[],Te=parseInt(w.getAttribute("width")??"",10),rt=parseInt(w.getAttribute("height")??"",10),je=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,it=w.getAttribute("frameRate")??"",Ge=w.getAttribute("quality")??void 0,cr=it?kS(it):void 0,dr=w.getAttribute("id")??"id"+(k++).toString(10),La=Y==="video"?`${rt}p`:Y==="audio"?`${je}Kbps`:O,Ma=`${dr}@${La}`,Ca=[...E,...U,...ce],pr,Yr=w.querySelector("SegmentBase"),oe=w.querySelector("SegmentTemplate")??ye;if(Yr){let at=w.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ve,Nt]=at.split("-").map(St=>parseInt(St,10)),Re={from:Ve,to:Nt},gt=w.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ft,hr]=gt?gt.split("-").map(St=>parseInt(St,10)):[],Qe=gt?{from:Ft,to:hr}:void 0;pr={type:"byteRange",url:lr,initRange:Re,indexRange:Qe}}else if(oe){let at={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},Ve=parseInt(oe.getAttribute("timescale")??"",10),Nt=oe.getAttribute("initialization")??"",Re=oe.getAttribute("media"),gt=parseInt(oe.getAttribute("startNumber")??"",10)??1,Ft=mt(Nt,at);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let hr=oe.querySelectorAll("SegmentTimeline S")??[],Qe=[],St=0,mr="",Kr=0;if(hr.length){let Da=gt,Be=0;for(let fr of hr){let We=parseInt(fr.getAttribute("d")??"",10),qt=parseInt(fr.getAttribute("r")??"",10)||0,Oa=parseInt(fr.getAttribute("t")??"",10);Be=Number.isFinite(Oa)?Oa:Be;let cn=We/Ve*1e3,sy=Be/Ve*1e3;for(let Va=0;Va<qt+1;Va++){let ny=mt(Re,{...at,segmentNumber:Da.toString(10),segmentTime:(Be+Va*We).toString(10)}),wl=(sy??0)+Va*cn,oy=wl+cn;Da++,Qe.push({time:{from:wl,to:oy},url:ny})}Be+=(qt+1)*We,St+=(qt+1)*cn}Kr=Be/Ve*1e3,mr=mt(Re,{...at,segmentNumber:Da.toString(10),segmentTime:Be.toString(10)})}else if(wS(h)){let Be=parseInt(oe.getAttribute("duration")??"",10)/Ve*1e3,fr=Math.ceil(h/Be),We=0;for(let qt=1;qt<fr;qt++){let Oa=mt(Re,{...at,segmentNumber:qt.toString(10),segmentTime:We.toString(10)});Qe.push({time:{from:We,to:We+Be},url:Oa}),We+=Be}Kr=We,mr=mt(Re,{...at,segmentNumber:fr.toString(10),segmentTime:We.toString(10)})}let ay={time:{from:Kr,to:1/0},url:mr};pr={type:"template",baseUrl:lr,segmentTemplateUrl:Re,initUrl:Ft,totalSegmentsDurationMs:St,segments:Qe,nextSegmentBeyondManifest:ay,timescale:Ve}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Y||!_t)continue;let zr={video:"video",audio:"audio",text:"text"}[Y];if(!zr)continue;P||=zr,re={id:Ma,kind:zr,segmentReference:pr,profiles:Ca,duration:h,bitrate:je,mime:_t,codecs:O,width:Te,height:rt,fps:cr,quality:Ge}}C.language||=K,C.label||=te,C.mime||=_t,C.codecs||=O,C.hdr||=P==="video"&&Qu(O),C.representations.push(re)}P&&a[P].push(C)}return{dynamic:c,liveAvailabilityStartTime:p,duration:h,streams:a,baseUrls:o}};var Ku=$(Vr(),1);import{videoSizeToQuality as xL}from"@vkontakte/videoplayer-shared";var VS=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s,streamId:n})=>{let o=(s?At(s):void 0)??xL({width:e,height:t});return o&&{id:i,quality:o,bitrate:r,size:{width:e,height:t},fps:a,streamId:n}},BS=({id:i,bitrate:e})=>({id:i,bitrate:e}),_S=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),NS=({language:i,label:e,id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Ju=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Ku.default)(r.split("."),0),isDefault:a}),Xu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Ku.default)(a.split("."),0)}),Zu=i=>"url"in i,Ae=i=>i.type==="template",na=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var oa=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new Hr(0);this.currentSegmentLength$=new Hr(0);this.onLastSegment$=new Hr(!1);this.fullyBuffered$=new Hr(!1);this.playingRepresentation$=new Hr(void 0);this.playingRepresentationInit$=new Hr(void 0);this.error$=new kL;this.gaps=[];this.subscription=new AL;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ke;this.switchAbortController=new ke;this.destroyAbortController=new ke;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=rr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);le(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Og(this.sourceBuffer),this.subscription.add(el(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(el(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,_u(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ze(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);le(r,"No init buffer for starting representation"),le(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=rr(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);le(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(De(s)||De(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),le(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(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();Vs(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=rr(this.destroyAbortController.signal,async function*(e){let t=(0,Ns.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!Ae(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);le(a);let s=this.segments.get(r);le(s,"No segments for starting representation");let n=this.initData.get(r);if(le(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,this.baseUrls=l?.baseUrls??[],this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ke,rr(this.switchAbortController.signal,async function*(r,a=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);le(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(De(o)||De(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),le(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();Vs(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ke,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(De(e)||De(this.downloadingRepresentationId)||De(this.playingRepresentationId)||De(this.sourceBuffer)||Vs(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(le(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Ze(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&_u(this.sourceBuffer.buffered)>=this.bufferLimit){let l=Ze(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if((0,_s.default)(o,a))l="high";else{let c=(0,jr.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&Ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,jr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;Vs(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=(0,Ns.default)(e?.streams[this.kind],a=>a.representations).find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r?.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){let t=(0,Ns.default)(e?.streams[this.kind],r=>r.representations)??[];for(let r of t){if(!r||!Ae(r.segmentReference))return;let a=r.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,jr.default)(s,-1)?.time.to??0,o=a?.findIndex(u=>Math.floor(n)>=Math.floor(u.time.from)&&Math.floor(n)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,u)}else{let u=a.slice(o+1);this.segments.set(r.id,[...s,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;le(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){for(let t of(0,et.default)(this.representations)){let r=t.segmentReference;if(!Ae(r))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.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),u=mt(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.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&&Vi&&Vi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Vi&&Vi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();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,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),k=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&k&&this.sourceBuffer&&!($t(this.sourceBuffer.buffered,p)&&$t(this.sourceBuffer.buffered,h)))&&g&&k});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){Ae(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await rr(o,async function*(){let c=tl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Bs(),!c)return;let d=new DataView(c),p=sa(t.mime);if(!isFinite(a.segment.time.to)){let b=t.segmentReference.timescale;a.segment.time.to=p.getChunkEndTime(d,b)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),na(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(0,et.default)(this.representations))Ae(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await rr(n,async function*(){let u=tl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),el(window,"online").pipe(PL()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=Bs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),na(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ae(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,jr.default)(e,0).byte.from,to:(0,jr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Bs(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ae(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Bs();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Mt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,_s.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=sa(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<a,f=d<=a;if(!h)continue;let b=sa(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),S=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):n())}}}onSegmentFullyAppended(e,t){this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(le(this.sourceBuffer),$t(this.sourceBuffer.buffered,e.segment.time.from,100)&&$t(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Mt.VIDEO_PIPELINE,message:"Safari 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",Zu(e.segment)&&(e.segment.size=e.fedBytes);for(let r of(0,et.default)(this.representations))if(r.id!==t)for(let a of this.segments.get(r.id)??[])a.status==="fed"&&Math.round(a.time.from)===Math.round(e.segment.time.from)&&Math.round(a.time.to)===Math.round(e.segment.time.to)&&(a.status="none");le(this.sourceBuffer),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(0,et.default)(this.activeSegments))if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[a,s]of(0,FS.default)(this.initData)){let n=s instanceof Promise;t||=n,s===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=Ou(()=>(0,qS.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",r=!1){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?rr(this.destroyAbortController.signal,async function*(){let o=tl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,sa(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ae(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Mt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async dropBuffer(){for(let e of(0,et.default)(this.segments))for(let t of e)t.status="none";await this.pruneBuffer(0,1/0,!0)}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||De(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=Zu(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of(0,et.default)(this.segments))for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of(0,et.default)(this.segments))for(let h of p)(0,_s.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(a.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of(0,et.default)(this.segments))for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||De(e)?0:Ze(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){le(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Ou(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(De(this.sourceBuffer)||De(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=100;for(let r of(0,et.default)(this.segments))for(let a of r){let{status:s}=a;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(a.time.from),o=Math.ceil(a.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var ua=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var US=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as la,assertNever as jS,fromEvent as GS,merge as wL,now as ca,Subscription as RL,ValueSubject as rl,flattenObject as Gr}from"@vkontakte/videoplayer-shared";var HS=i=>{let e=new URL(i);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Fs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new rl(void 0);this.lastConnectionReused$=new rl(void 0);this.lastRequestFirstBytes$=new rl(void 0);this.abortAllController=new ke;this.subscription=new RL;this.fetchManifest=la(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ua(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=HS(r));let a=yield dt(r,{signal:this.abortAllController.signal}).catch(da);return a?(t.log("success",Gr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Gr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=la(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let v=new URL(l,location.href);v.searchParams.append("bytes",`${r.from}-${r.to}`),l=v.toString();break}default:jS(t)}this.requestQuic&&(l=ua(l));let p=this.abortAllController.signal,h;if(n){let v=new ke;if(h=wL(GS(this.abortAllController.signal,"abort"),GS(n,"abort")).subscribe(()=>{try{v.abort()}catch(T){da(T)}}),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(T){da(T)}p=v.signal}let f=ca();d.log("startRequest",Gr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield dt(l,{priority:s,headers:c,signal:p}).catch(da),g=ca();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){h?.unsubscribe();let v=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:v}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let v=ca(),T={requestStartedAt:f,requestEndedAt:v,duration:v-f};return d.log("endRequest",Gr(T)),d.end(),b.arrayBuffer()}let[S,k]=b.body.tee(),E=S.getReader();o&&this.throughputEstimator?.trackStream(k,u);let A=0,y=new Uint8Array(0),R=!1,V=v=>{h?.unsubscribe(),R=!0,da(v)},F=la(p,async function*({done:v,value:T}){if(A===0&&this.lastRequestFirstBytes$.next(ca()-f),p.aborted){h?.unsubscribe();return}if(!v&&T){let q=new Uint8Array(y.length+T.length);q.set(y),q.set(T,y.length),y=q,A+=T.byteLength,a?.(new DataView(y.buffer),A),yield E?.read().then(F,V)}}.bind(this));yield E?.read().then(F,V),h?.unsubscribe();let _=ca(),U={failed:R,requestStartedAt:f,requestEndedAt:_,duration:_-f};return R?(d.error("endRequest",Gr(U)),d.end(),null):(d.log("endRequest",Gr(U)),d.end(),y.buffer)}.bind(this));this.fetchByteRangeRepresentation=la(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=la(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=US(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){let{type:a}=e;switch(a){case"byteRange":return await this.fetchByteRangeRepresentation(e,t,r)??null;case"template":return await this.fetchTemplateRepresentation(e,r)??null;default:jS(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},da=i=>{if(!na(i))throw i};var ir=(i,e,t)=>t*e+(1-t)*i,il=(i,e)=>i.reduce((t,r)=>t+r,0)/e,QS=(i,e,t,r)=>{let a=0,s=t,n=il(i,e),o=e<r?e:r;for(let u=0;u<o;u++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as $L,ValueSubject as WS}from"@vkontakte/videoplayer-shared";var Ct=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 WS(e.initial),this.debounced$=new WS(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ue(`raw_${t}`),this.smoothedSeries$=new ue(`smoothed_${t}`),this.reportedSeries$=new ue(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;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)&&($L(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 qs=class extends Ct{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ir(this.slow,e,this.params.emaAlphaSlow),this.fast=ir(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Us=class extends Ct{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=il(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ir(this.emaSmoothed,e,this.params.emaAlpha);let r=QS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Hs=class extends Ct{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?ir(this.smoothed,t,this.params.emaAlpha):t}};var ar=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new qs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Us({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Hs({initial:e,label:"liveEdgeDelay",...t})}};var al=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};import{isNullable as LL,ValueSubject as ML}from"@vkontakte/videoplayer-shared";var pa=class i{constructor(e,t){this.currentRepresentation$=new ML(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(!LL(e))for(let t of this.representations)for(let r of t){let a=r.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let r=i.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>i.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ae(t.segmentReference))}};var FL=["timeupdate","progress","play","seeked","stalled","waiting"],qL=["timeupdate","progress","loadeddata","playing","seeked"];var Gs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new JS;this.representationSubscription=new JS;this.state$=new L("none");this.currentVideoRepresentation$=new W(void 0);this.currentVideoRepresentationInit$=new W(void 0);this.currentAudioRepresentation$=new W(void 0);this.currentVideoSegmentLength$=new W(0);this.currentAudioSegmentLength$=new W(0);this.error$=new KS;this.lastConnectionType$=new W(void 0);this.lastConnectionReused$=new W(void 0);this.lastRequestFirstBytes$=new W(void 0);this.currentLiveTextRepresentation$=new W(null);this.isLive$=new W(!1);this.liveDuration$=new W(0);this.liveAvailabilityStartTime$=new W(void 0);this.bufferLength$=new W(0);this.liveLatency$=new W(void 0);this.liveLoadBufferLength$=new W(0);this.livePositionFromPlayer$=new W(0);this.isLowLatency$=new W(!1);this.isActiveLowLatency$=new W(!1);this.currentStallDuration$=new W(0);this.videoLastDataObtainedTimestamp$=new W(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new KS;this.gapWatchdogActive=!1;this.destroyController=new ke;this.initManifest=sl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Dt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=sl(this.destroyController.signal,async function*(){this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Dt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=OS(e??"",this.manifestUrlString)}catch(n){let o=Rg(e)??{id:"ManifestParsing",category:Dt.PARSER,message:"Failed to parse MPD manifest",thrown:n};this.error$.next(o)}if(!t)return null;let r=(n,o,u)=>!!(this.element?.canPlayType?.(o)&&pt()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:p})=>r(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=og(l);if(c&&(a[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=a.video.some(f=>f.hdr),h=a.video.some(f=>!f.hdr);OL.isHDR&&d&&p?a.video=a.video.filter(f=>f.hdr):h&&(a.video=a.video.filter(f=>!f.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",ma(s)),s}.bind(this));this.initRepresentations=sl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",ma({initialVideo:e,initialAudio:t,sourceHls:r})),sr(this.manifest),sr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(nr(p,"error").pipe(js(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Dt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?eg():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&$s())if(r){let p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new oa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],zS(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new oa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}pa.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new pa(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(ol(1e3).subscribe(p=>{if(this.element?.paused){let h=Ss(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,h+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(or(...qL.map(p=>nr(this.element,p))).pipe(fa(p=>this.element?Ze(this.element.buffered,this.element.currentTime*1e3):0),nl(),_L(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(or(nr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(nl()).subscribe(h=>al(this.element,1))),this.representationSubscription.add(ha({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(js(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(ha({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(js(({isLive:h})=>h),fa(h=>({...h})),nl((h,f)=>f.bufferLength<h.bufferLength),fa(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=Ss(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ha({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,k=h-b,E=1;Math.abs(k)>g&&(E=1+Math.sign(k)*S),al(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(S=>S.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(ha({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(NL(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(sr(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=Ss(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,y=isFinite(h)?h:f,R=this.isActiveLowLatency$.getValue(),V=S<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(R&&V);let F="none";if(R?F="active_low_latency":this.isLowLatency$.getValue()&&V?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),F="active_low_latency"):g!==0&&y<k?F="live_forward_buffering":y<k+A&&(F="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),F==="live_forward_buffering"||F==="live_with_target_offset"){let _=p-(k+E),U=this.normolizeLiveOffset(Math.trunc(g+_/b)),v=Math.abs(U-g),T;!h||v<=this.tuning.dashCmafLive.offsetCalculationError?T=g:U>0&&v>this.tuning.dashCmafLive.offsetCalculationError?T=U:T=0,this.manifestUrlString=se(this.manifestUrlString,T,2)}F!=="none"&&F!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=or(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(fa(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=or(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(fa(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(or(this.forceEnded$,ha({allBuffersFull:l,someBufferEnded:c}).pipe(js(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:Dt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(or(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>this.source?.addEventListener("sourceopen",p)));let d=[this.manifest.duration??0,...(0,ul.default)((0,ul.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let h=[];return p.duration&&h.push(p.duration),Ae(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&zS(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)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=ol(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Dt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Fs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=ar.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){sr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=se(this.manifestUrlString,t,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(){sr(this.element),this.state$.setState("running"),this.subscription.add(or(...FL.map(e=>nr(this.element,e)),nr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Dt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(nr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(nr(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&$t(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let r={timeInWaiting:t},a=BL(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%5e3===0)this.seekLive(this.liveLastSeekOffset),r.liveLastSeekOffset=this.liveLastSeekOffset;else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",ma(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=ol(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Dt.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,r)}seek(e,t){sr(this.element),sr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),$t(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",ma({requestedPosition:e,forcePrecise:t,position:r}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.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=VL(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}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={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ma(t)))}}};var Qs=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ws=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,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let a=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:a,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e??this.rotationSpeed.x,this.rotationSpeed.y=t??this.rotationSpeed.y,this.rotationSpeed.z=r??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,r){this.setRotationSpeed(e,t,r),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,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var XS=`attribute vec2 a_vertex;
|
|
69
70
|
attribute vec2 a_texel;
|
|
70
71
|
|
|
71
72
|
varying vec2 v_texel;
|
|
@@ -76,7 +77,7 @@ void main(void) {
|
|
|
76
77
|
// save texel vector to pass to fragment shader
|
|
77
78
|
v_texel = a_texel;
|
|
78
79
|
}
|
|
79
|
-
`;var
|
|
80
|
+
`;var ZS=`#ifdef GL_ES
|
|
80
81
|
precision highp float;
|
|
81
82
|
precision highp int;
|
|
82
83
|
#else
|
|
@@ -119,6 +120,5 @@ void main(void) {
|
|
|
119
120
|
// sample using new coordinates
|
|
120
121
|
gl_FragColor = texture2D(u_texture, tc);
|
|
121
122
|
}
|
|
122
|
-
`;var Ms=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 a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new $s(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ls(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"),a=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(a,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(Xb,this.gl.VERTEX_SHADER),i=this.createShader(Jb,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,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/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,a=this.camera.fov.y/180/2,s=e-i,n=t-a,o=e+i,u=t-a,l=e+i,c=t+a,d=e-i,p=t+a;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as mA,now as Zb,Subscription as fA,filter as bA,combine as eg,ValueSubject as tg,isNonNullable as gA}from"@vkontakte/videoplayer-shared";var Vu=class{constructor(){this.isSeeked$=new tg(!1);this.isBuffering$=new tg(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new fA}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(eg({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(bA(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(eg({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:i})=>{if(mA(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:a,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=Zb(),p=n&&this.currentStallsCount>=n,h=a&&!i&&d-this.lastUniqueVideoTrackSelectedTimestamp>=a+u&&t>=a,m=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(p||h||m)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,gA(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Zb(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},ig=Vu;var Zt=class{constructor(e){this.subscription=new kA;this.videoState=new $("stopped");this.elementSize$=new wA(void 0);this.textTracksManager=new Le;this.droppedFramesManager=new hs;this.stallsManager=new ig;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new mr;this.audioTrackSwitchHistory=new mr;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&i?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),x(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"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):i?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return yA(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ms(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.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ce(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(K(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 Rs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=he(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Bu.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(rg(c=>!!c.length),sg()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Ou(c=>c.to.state!=="none"),aa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(aa()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:i.isBuffering$}),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.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(rg(ag),sg()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Ou(c=>c.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Ke(this.video,t.isLooped,a)),this.subscription.add(pe(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add($e(this.video,t.playbackRate,i.playbackRateState$,a)),s(PA(this.video),this.elementSize$),s(De(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(TA(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of d.audio){h.push(Eu(m));let b=[];for(let g of m.representations){let S=Bb(g);b.push(S),this.audioTracksMap.set(S,{stream:m,representation:g})}this.audioStreamsMap.set(m,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(xu(h));let m=[];for(let b of h.representations){let g=Vb(b);g&&(m.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,m)}if(this.params.output.availableVideoStreams$.next(p),this.textTracksManager)for(let h of d.text)for(let m of h.representations){let b=Ob(h,m);this.textTracksMap.set(b,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let o=c=>e.error$.next({id:"RepresentationSwitch",category:Bu.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Ds(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,EA(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,b=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===h.id);ag(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,m?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),m){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,S).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(aa()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(xu(h))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(aa()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Eu(h))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager?.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(Ou(({to:c})=>c==="ready"),aa());this.subscription.add(Ds(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Ds(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Ds(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xA(["init"])).pipe(IA(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:R})=>R===a),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:R})=>R===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Je(this.video.buffered,this.video.currentTime*1e3),p=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:R})=>R===m?.id)??this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!i){let R=ls(n,c,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,R?.bitrate??-1/0)}if(o){let R=ls(o,c,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,R?.bitrate??-1/0)}}let S=Tt(c,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,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}),T=i?S??n:n??S,I=b&&Ef(T,c,this.audioStreamsMap.get(b)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),w=this.videoTracksMap.get(T)?.representation,y=I&&this.audioTracksMap.get(I)?.representation;if(w&&y)return[w,y];if(w&&!y&&this.audioTracksMap.size===0)return[w,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bu.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),this.textTracksManager?.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),de(this.video),this.tracer.end()}};var sa=class extends Zt{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as ng,interval as AA,map as og}from"@vkontakte/videoplayer-shared";var na=class extends Zt{constructor(e){super(e),this.liveOffset=new ot,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:i,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(t.timeUpdate$,e.liveBufferTime$),a(this.player.liveDuration$,e.duration$),this.subscription.add(i.isLowLatency.stateChangeEnded$.pipe(og(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(ng({interval:AA(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(s-1);n<=0&&e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(ng({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(og(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=_b(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t==="paused"&&i==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var lg=Oe(ns(),1);import{assertNever as oa,assertNonNullable as ug,debounce as RA,ErrorCategory as Cs,filter as $A,isNonNullable as LA,isNullable as MA,map as Vs,merge as DA,Observable as CA,observableFrom as VA,Subscription as BA,videoSizeToQuality as OA}from"@vkontakte/videoplayer-shared";var je={};var Vi=(r,e)=>new CA(t=>{let i=(a,s)=>t.next(s);return r.on(e,i),()=>r.off(e,i)}),ua=class{constructor(e){this.subscription=new BA;this.videoState=new $("initializing");this.textTracksManager=new Le;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(i?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:oa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:oa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:oa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:oa(e)}break;default:oa(t)}};this.video=ce(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),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(K(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),de(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Cs.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,lg.default)(import("hls.js").then(a=>{e||(je.Hls=a.default,je.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){ug(je.Hls,"hls.js not loaded"),this.hls=new je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){ug(je.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Cs.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=he(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Ke(this.video,e.isLooped,i)),this.subscription.add(pe(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add($e(this.video,e.playbackRate,a.playbackRateState$,i)),s(De(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Vs(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Vi(this.hls,je.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Cs.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(Vi(this.hls,je.Events.MANIFEST_PARSED).pipe(Vs(({levels:l})=>l.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=vt(d.attrs.QUALITY??"")??OA({width:h,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(Vi(this.hls,je.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Vi(this.hls,je.Events.LEVEL_LOADING).pipe(Vs(({url:l})=>K(l))),t.hostname$),s(Vi(this.hls,je.Events.FRAG_CHANGED),l=>{let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(bt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>Array.from(this.trackLevels.values()).find(({level:c})=>c===l)?.track,o=Vi(this.hls,je.Events.LEVEL_SWITCHED).pipe(Vs(({level:l})=>n(this.hls.levels[l])));o.pipe($A(LA)).subscribe(t.currentVideoTrack$,i),this.subscription.add(bt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(MA(l))return;let c=this.trackLevels.get(l.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=DA(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,VA(["init"])).pipe(RA(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cs.DOM,thrown:t}))||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){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.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0)}};var cg="X-Playback-Duration",_u=async r=>{let e=await Ue(r),t=await e.text(),i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return i?parseInt(i,10):e.headers.has(cg)?parseInt(e.headers.get(cg),10):void 0};import{assertNever as zA,combine as KA,debounce as XA,ErrorCategory as _s,filter as JA,filterChanged as ZA,isNonNullable as hg,isNullable as Ns,map as mg,merge as eR,observableFrom as tR,Subscription as iR,ValueSubject as qu,VideoQuality as rR}from"@vkontakte/videoplayer-shared";var Fu=Oe(Zn(),1);import{videoSizeToQuality as _A,getExponentialDelay as NA}from"@vkontakte/videoplayer-shared";var FA=r=>{let e=null;if(r.QUALITY&&(e=vt(r.QUALITY)),!e&&r.RESOLUTION){let[t,i]=r.RESOLUTION.split("x").map(a=>parseInt(a,10));e=_A({width:t,height:i})}return e??null},qA=(r,e)=>{let t=r.split(`
|
|
123
|
-
`),i=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,Fu.default)(o[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=FA(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,m;if(l.RESOLUTION){let[g,S]=l.RESOLUTION.split("x").map(T=>parseInt(T,10));g&&S&&(m={width:g,height:S})}let b=new URL(t[++s],e).toString();d&&i.push({id:c,quality:d,url:b,bandwidth:p,size:m,fps:h})}if(u){let l=(0,Fu.default)(u[1].split(",").map(h=>{let m=h.indexOf("=");return[h.substring(0,m),h.substring(m+1)]}).map(([h,m])=>[h,m.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,p=l.NAME;c&&d&&a.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:a}},UA=r=>new Promise(e=>{setTimeout(()=>{e()},r)}),Nu=0,dg=async(r,e=r,t,i)=>{let s=await(await Ue(r,i)).text();Nu+=1;try{let{qualityManifests:n,textTracks:o}=qA(s,e);return{qualityManifests:n,textTracks:o}}catch{if(Nu<=t.manifestRetryMaxCount)return await UA(NA(Nu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),dg(r,e,t)}return{qualityManifests:[],textTracks:[]}},Bs=dg;import{isNonNullable as HA,Subscription as jA,throttle as GA,ValueSubject as pg,Logger as QA,Subject as WA,ErrorCategory as YA}from"@vkontakte/videoplayer-shared";var Os=class{constructor(e,t,i,a){this.subscription=new jA;this.abortControllers={destroy:new ie,nextManifest:null};this.numberFormat=new Intl.NumberFormat("ru-RU",{maximumFractionDigits:2,minimumFractionDigits:2,useGrouping:!0});this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new pg(null);this.getCurrentTime$=new pg(null);this.error$=new WA;this.logger=new QA,this.log=this.logger.createComponentLog("LiveTextManager"),this.params={fetchManifestData:i,sourceUrl:a},this.subscription.add(e.pipe(GA(1e3)).subscribe(s=>{this.processLiveTime(s)})).add(this.logger.log$.subscribe(s=>{console.debug(`%c${s.component}`,"background:#258b6d;",s.message)})),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 a=new URL(i.url,t).toString();this.log({message:"[parseTextTracks]"}),this.log({message:a});let n=await(await Ue(a,{signal:this.abortControllers.destroy.signal})).text();this.log({message:n});let o=this.parsePlaylist(n,a);return this.log({message:JSON.stringify(o,void 0,2)}),{textTrack:i,playlist:o}}}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},a=e.split(`
|
|
124
|
-
`),s=0;for(let n=0;n<a.length;++n){let o=a[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=a[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),p=new Date(i.programDateTime).valueOf();i.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(HA(e)&&this.currentTextTrackData){this.log({message:`[processLiveTime] ${e.toFixed(2)}, ${new Date(e).toISOString()}`});let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:a}=t[t.length-1].time;if(e<i){this.log({message:`[processLiveTime] out of bounds (before) ! ${i-e}`});return}if(e>a){this.log({message:`[processLiveTime] out of bounds (after) !' ${e-a}`});return}let s=a-e;this.log({message:`Current segments time left: ${this.numberFormat.format(s)} ms`}),s<4e3&&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 ie;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:YA.WTF,thrown:t,message:e})}};var la=class{constructor(e){this.subscription=new iR;this.videoState=new $("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new qu([]);this.liveOffset=new ot;this.manifestStartTime$=new qu(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(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()):a?.to==="playing"&&x(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 a?.to==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return zA(t)}};this.params=e,this.video=ce(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:rR.INVARIANT,url:this.params.source.url};let t=(i,a)=>Bs(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},a);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Os(this.params.output.liveTime$,this.video,t,this.params.source.url):this.textTracksManager=new Le,t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:a})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:_s.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:_s.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(K(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new qu(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:_s.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=he(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(pe(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,i)),s(De(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(a.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(ZA(),mg(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&hg(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(K(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(KA({startTime:this.manifestStartTime$.pipe(JA(hg)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(mg(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=eR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,tR(["init"])).pipe(XA(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),de(this.video)}prepare(){let e=this.selectManifest();if(Ns(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??i??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=te(a.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),_u(n).then(o=>{if(!Ns(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(Ns(u)||!isFinite(u))&&Ue(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,n).toString();_u(d).then(p=>{Ns(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:_s.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=te(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as aR,debounce as sR,ErrorCategory as Uu,fromEvent as Hu,isNonNullable as nR,isNullable as oR,map as fg,merge as bg,observableFrom as gg,Subscription as uR,ValueSubject as lR,VideoQuality as cR,clientChecker as dR}from"@vkontakte/videoplayer-shared";var ca=class{constructor(e){this.subscription=new uR;this.videoState=new $("stopped");this.textTracksManager=new Le;this.manifests$=new lR([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?x(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),x(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()):a?.to==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return aR(t)}};this.params=e,this.video=ce(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:cR.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(K(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Bs(te(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Uu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=i?"master":s;return i&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Uu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=he(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(fg(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,i)),this.subscription.add(pe(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&nR(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(K(m.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(fg(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!dR.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(bg(Hu(o,"addtrack"),Hu(o,"removetrack"),Hu(o,"change"),gg(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=bg(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,gg(["init"])).pipe(sR(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),de(this.video)}prepare(){let e=this.selectManifest();if(oR(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??i??{};for(let[o,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Uu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as pR,assertNonNullable as Sg,debounce as hR,ErrorCategory as vg,isHigher as mR,isHigherOrEqual as fR,isInvariantQuality as yg,isLowerOrEqual as bR,isNonNullable as gR,merge as SR,observableFrom as vR,Subscription as yR,map as TR}from"@vkontakte/videoplayer-shared";var da=class{constructor(e){this.subscription=new yR;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Le;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"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(i?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return pR(e)}};this.params=e,this.video=ce(e.container,e.tuning),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:vg.WTF,message:"MpegProvider internal logic error",thrown:o})},a=he(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(TR(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ke(this.video,t.isLooped,i)),this.subscription.add(pe(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,i)),s(De(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&gR(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=SR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,vR(["init"])).pipe(hR(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),de(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Sg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Sg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Xr(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(K(t))}playIfAllowed(){me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vg.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,i=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=Object.values(this.trackUrls).find(o=>!yg(o.track.quality)&&bR(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&fR(n.quality,a.quality)&&(t=a),!t){let o=Object.values(this.trackUrls).filter(l=>!yg(l.track.quality)&&mR(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(i=t.quality)}else if(!e){let a=Object.values(this.trackUrls).map(s=>s.track);t=Tt(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};import{assertNever as Ig,debounce as PR,merge as Eg,observableFrom as kR,Subscription as wR,map as xg,ValueSubject as AR,ErrorCategory as Gu,VideoQuality as RR}from"@vkontakte/videoplayer-shared";import{ErrorCategory as IR}from"@vkontakte/videoplayer-shared";var Tg=["stun:videostun.mycdn.me:80"],ER=1e3,xR=3,ju=()=>null,Fs=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=ju;this.externalStopCallback=ju;this.externalErrorCallback=ju;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:Tg}]};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:IR.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),ER)}normalizeOptions(e={}){let t={stunServerList:Tg,maxRetryNumber:xR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var pa=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new AR(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"),x(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"),x(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"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):i?.to==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Ig(e)}};this.subscription=new wR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ce(e.container,e.tuning),this.liveStreamClient=new Fs(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),de(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Gu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Eg(this.videoState.stateChangeStarted$.pipe(xg(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(xg(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=he(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(De(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},i)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(pe(this.video,t.volume,a.volumeState$,i)).add(a.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 Ig(n.to)}},i)).add(Eg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,kR(["init"])).pipe(PR(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(K(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:RR.INVARIANT}),this.video.srcObject=e,x(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:Gu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Gu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ha=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as ma,assertNonNullable as wt,ErrorCategory as qs,filter as $g,isNonNullable as Lg,isNullable as OR,map as _R,merge as NR,once as FR,Subject as ge,Subscription as Mg,ValueSubject as L,flattenObject as Dg}from"@vkontakte/videoplayer-shared";import{Observable as $R,map as Pg,Subscription as LR,Subject as MR}from"@vkontakte/videoplayer-shared";var kg=r=>new $R(e=>{let t=new LR,i=r.desiredPlaybackState$.stateChangeStarted$.pipe(Pg(({from:l,to:c})=>`${l}-${c}`)),a=r.desiredPlaybackState$.stateChangeEnded$,s=r.providerChanged$.pipe(Pg(({type:l})=>l!==void 0)),n=new MR,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),r.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),r.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as DR,Subscription as CR,combine as VR,filter as Ag,once as Rg}from"@vkontakte/videoplayer-shared";function wg(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as BR}from"@vkontakte/videoplayer-shared";var Bi=class r{constructor(e,t,i,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=a;this.destroyController=new ie;this.subscriptions=new CR;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Ag(s=>!!s.type),Rg()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){BR.isSafari&&e!=="MPEG"||this.subscriptions.add(VR({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Ag(({playbackState:t,video:i,volume:{muted:a,volume:s}})=>t==="playing"&&!!i&&!a&&!!s),Rg()).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=wg();this.audioContext=i;let a=i.createGain();if(this.gainNode=a,a.gain.value=t,a.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(a),!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:r.errorId,category:DR.VIDEO_PIPELINE,message:e?.message??`${r.errorId} exception`,thrown:e})}};var qR={chunkDuration:5e3,maxParallelRequests:5},fa=class{constructor(e){this.current$=new L({type:void 0});this.providerError$=new ge;this.noAvailableProvidersError$=new ge;this.volumeMultiplierError$=new ge;this.providerOutput={position$:new L(0),duration$:new L(1/0),volume$:new L({muted:!1,volume:1}),availableVideoStreams$:new L([]),currentVideoStream$:new L(void 0),availableVideoTracks$:new L([]),currentVideoTrack$:new L(void 0),availableAudioStreams$:new L([]),currentAudioStream$:new L(void 0),availableAudioTracks$:new L([]),currentVideoSegmentLength$:new L(0),currentAudioSegmentLength$:new L(0),isAudioAvailable$:new L(!0),autoVideoTrackLimitingAvailable$:new L(!1),autoVideoTrackLimits$:new L(void 0),currentBuffer$:new L(void 0),isBuffering$:new L(!0),error$:new ge,warning$:new ge,willSeekEvent$:new ge,soundProhibitedEvent$:new ge,seekedEvent$:new ge,loopedEvent$:new ge,endedEvent$:new ge,firstBytesEvent$:new ge,loadedMetadataEvent$:new ge,firstFrameEvent$:new ge,canplay$:new ge,isLive$:new L(void 0),isLowLatency$:new L(!1),canChangePlaybackSpeed$:new L(!0),liveTime$:new L(void 0),liveBufferTime$:new L(void 0),availableTextTracks$:new L([]),currentTextTrack$:new L(void 0),hostname$:new L(void 0),httpConnectionType$:new L(void 0),httpConnectionReused$:new L(void 0),inPiP$:new L(!1),inFullscreen$:new L(!1),element$:new L(void 0),elementVisible$:new L(!0),availableSources$:new L(void 0),is3DVideo$:new L(!1),playbackState$:new L(""),getCurrentTime$:new L(null)};this.subscription=new Mg;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=qf([...Hf(this.params.tuning),...Uf(this.params.tuning)],this.params.tuning).filter(l=>Lg(e.sources[l])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning,s=[];i?s=[i]:a.length?s=[...t.filter(l=>!a.includes(l)),...t.filter(l=>a.includes(l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Dg(s)),this.screenFormatsIterator=new ha(s);let n=[...nu(!0),...nu(!1)];this.chromecastFormatsIterator=new ha(n.filter(l=>Lg(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Bi.isSupported()&&(this.volumeMultiplierManager=new Bi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(OR(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:qs.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();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 ma(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:a}=this.params,s=this.providerOutput,n={container:i,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return wt(o),new sa({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return wt(o),new na({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return wt(o),$i||!this.params.tuning.useHlsJs?new ca({...n,source:o}):new ua({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return wt(o),new la({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return wt(o),new da({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return wt(o),new Cf({...n,source:o,config:{...qR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return wt(o),new pa({container:i,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return ma(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return wt(o),new cr({connection:o,meta:s,container:i,source:t,format:e,desiredState:a,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 ma(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return ma(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 ma(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=a=>{let s=new URL(a);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,Cg.default)(Object.entries(e).map(([a,s])=>[a,i(s)]))}initProviderErrorHandling(){let e=new Mg,t=!1,i=0;return e.add(NR(this.providerOutput.error$.pipe($g(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),kg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(_R(a=>({id:`ProviderHangup:${a}`,category:qs.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe($g(({to:s})=>s==="playing"),FR()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===qs.NETWORK,u=a.category===qs.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",Dg(n))})),e}};import{fromEvent as Us,once as UR,combine as HR,Subscription as Vg,ValueSubject as Qu,map as jR,filter as GR,isNonNullable as Hs,now as Pe,safeStorage as Wu}from"@vkontakte/videoplayer-shared";var QR=5e3,Bg="one_video_throughput",Og="one_video_rtt",ba=window.navigator.connection,_g=()=>{let r=ba?.downlink;if(Hs(r)&&r!==10)return r*1e3},Ng=()=>{let r=ba?.rtt;if(Hs(r)&&r!==3e3)return r},Fg=(r,e,t)=>{let i=t*8,a=i/r;return i/(a+e)},Yu=class r{constructor(e){this.subscription=new Vg;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=r.load(Bg)||(e.useBrowserEstimation?_g():void 0)||QR,i=r.load(Og)??(e.useBrowserEstimation?Ng():void 0)??0;if(this.throughput$=new Qu(t),this.rtt$=new Qu(i),this.rttAdjustedThroughput$=new Qu(Fg(t,i,e.rttPenaltyRequestSize)),this.throughput=zt.getSmoothedValue(t,-1,e),this.rtt=zt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let a=()=>{let n=_g();n&&this.throughput.next(n);let o=Ng();Hs(o)&&this.rtt.next(o)};ba&&"onchange"in ba&&this.subscription.add(Us(ba,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Wu.set(Bg,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Wu.set(Og,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(HR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(jR(({throughput:a,rtt:s})=>Fg(a,s,e.rttPenaltyRequestSize)),GR(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=Pe(),a=new Vg;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(Us(e,"progress").pipe(UR()).subscribe(s=>{t=s.loaded,i=Pe()}));break;case 1:case 0:a.add(Us(e,"loadstart").subscribe(()=>{t=0,i=Pe()}));break}a.add(Us(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Pe(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let a=0,s=Pe(),n=0,o=Pe(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,Pe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Pe();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let m=o-s;m&&this.addRawSpeed(n,m,1,t),n=d.byteLength,s=Pe()}else n+=d.byteLength;o=Pe()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Pe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Pe()-o,this.concurrentDownloads.size),n=0,o=Pe());await i?.read().then(l,u)}};this.concurrentDownloads.add(e),i?.read().then(l,u)}addRawSpeed(e,t,i=1,a=!1){if(r.sanityCheck(e,t,a)){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 a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){let t=Wu.get(e);if(Hs(t))return parseInt(t,10)??void 0}},qg=Yu;import{fillWithDefault as WR,VideoQuality as Ug}from"@vkontakte/videoplayer-shared";var Hg={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:{bitrateFactorAtEmptyBuffer:1.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:1.2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Ug.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ug.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,accumulationBufferStallSize:{shortVideoDuration:2*6e4,shortVideoBufferStallSize:0,longVideoBufferStallSize:0},qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,delayEstimator:{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:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1},jg=r=>({...WR(r,Hg),configName:[...r.configName??[],...Hg.configName]});import{assertNonNullable as js,combine as At,ErrorCategory as Gs,filter as ne,filterChanged as B,fromEvent as Ku,isNonNullable as e$,isNullable as t$,Logger as i$,map as D,mapTo as Yg,merge as Rt,now as Qs,once as Ze,Subject as U,Subscription as zg,tap as Kg,ValueSubject as P,isHigher as r$,isInvariantQuality as Xg,flattenObject as $t,throttle as Xu,getTraceSubscriptionMethod as Jg,Tracer as a$}from"@vkontakte/videoplayer-shared";import{merge as YR,map as zR,filter as Gg,isNonNullable as KR}from"@vkontakte/videoplayer-shared";var zu=({seekState:r,position$:e})=>YR(r.stateChangeEnded$.pipe(zR(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Gg(KR)),e.pipe(Gg(()=>r.getState().state==="none")));import{assertNonNullable as XR}from"@vkontakte/videoplayer-shared";var Qg=r=>{let e=typeof r.container=="string"?document.getElementById(r.container):r.container;return XR(e,`Wrong container or containerId {${r.container}}`),e};import{filter as JR,once as ZR}from"@vkontakte/videoplayer-shared";var Wg=(r,e,t,i)=>{r!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(JR(a=>a.length>0),ZR()).subscribe(a=>{a.find(i)&&e.startTransitionTo(r)}):(r===void 0||t?.getValue().find(i))&&e.startTransitionTo(r)};var Ws=class{constructor(e={configName:[]},t=a$.createRootTracer(!1)){this.subscription=new zg;this.logger=new i$;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new $("stopped"),seekState:new $({state:"none"}),volume:new $({volume:1,muted:!1}),videoTrack:new $(void 0),videoStream:new $(void 0),audioStream:new $(void 0),autoVideoTrackSwitching:new $(!0),autoVideoTrackLimits:new $({}),isLooped:new $(!1),isLowLatency:new $(!1),playbackRate:new $(1),externalTextTracks:new $([]),internalTextTracks:new $([]),currentTextTrack:new $(void 0),textTrackCuesSettings:new $({}),cameraOrientation:new $({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new U,ready$:new U,started$:new U,playing$:new U,paused$:new U,stopped$:new U,willStart$:new U,willResume$:new U,willPause$:new U,willStop$:new U,willDestruct$:new U,watchCoverageRecord$:new U,watchCoverageLive$:new U,managedError$:new U,fatalError$:new U,ended$:new U,looped$:new U,seeked$:new U,willSeek$:new U,autoplaySoundProhibited$:new U,firstBytes$:new U,loadedMetadata$:new U,firstFrame$:new U,canplay$:new U,log$:new U};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:mf,getCurrentTime$:new P(null)};if(this.initLogs(),this.tuning=jg(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Pa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new qg(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,a,s)=>{let n=Reflect.get(i,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return["number","string","boolean"].includes(b)?m:m===null?null:`<${b}>`})),c=`Player.${String(a)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Gs.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...i}=e;return this.tracer.log("initVideo",$t(i)),this.domContainer=Qg(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new fa({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}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!vr()?(this.tracer.log("request play from hidden tab"),Ku(document,"visibilitychange").pipe(Ze()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=i&&!a&&(s=i-.1),this.tracer.log("seekTime",{duration:i,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){js(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return 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(ne(i=>i.length>0),Ze()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",$t(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){js(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",$t(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Wg(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return 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.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let a=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(t$(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return e$(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:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Rt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ne(({from:e})=>e==="stopped"),Ze()).subscribe(()=>{this.initedAt=Qs(),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"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",$t(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Gs.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(Ze()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",$t(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(D(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(n=>n.destination),B()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(D(n=>n.map(({quality:o})=>o).sort((o,u)=>Xg(o)?1:Xg(u)?-1:r$(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(B()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(B((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(B((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(B()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(B()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(B()).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(D(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.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(At({hasLiveOffsetByPaused:Rt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(n=>n.to),B(),D(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(At({atLiveEdge:At({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:zu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),B(),Kg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(At({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),B(),Kg(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(n=>n.muted),B()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(n=>n.volume),B()).subscribe(this.info.volume$)).add(zu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Rt(e.providerOutput.endedEvent$.pipe(Yg(!0)),e.providerOutput.seekedEvent$.pipe(Yg(!1))).pipe(B()).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.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(D(n=>({id:n?`No${n}`:"NoProviders",category:Gs.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(Ze(),D(n=>n??Qs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(Ze(),D(()=>Qs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ze(),D(()=>Qs()-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 P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new P(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ne(({to:n})=>n==="playing"),Ze()).subscribe(()=>i.next(!1)));let a=0,s=Rt(e.providerOutput.isBuffering$,t,i).pipe(D(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),B());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(Rt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Rt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(D(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new zg;this.subscription.add(t),this.subscription.add(e.current$.pipe(B((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ne(i=>i.length>0),Ze()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let i=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=Tt(e,{container:this.domContainer.getBoundingClientRect(),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(Rt(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(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;js(this.providerContainer),js(e),hf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>pf(t)),this.providerContainer.current$.subscribe(({type:t})=>hr("provider",t)),e.duration$.subscribe(t=>hr("duration",t)),e.availableVideoTracks$.pipe(ne(t=>!!t.length),Ze()).subscribe(t=>hr("tracks",t)),this.events.fatalError$.subscribe(new se("fatalError")),this.events.managedError$.subscribe(new se("managedError")),e.position$.subscribe(new se("position")),e.currentVideoTrack$.pipe(D(t=>t?.quality)).subscribe(new se("quality")),this.info.currentBuffer$.subscribe(new se("buffer")),e.isBuffering$.subscribe(new se("isBuffering"))].forEach(t=>this.subscription.add(t)),hr("codecs",Ff())}initTracerSubscription(){let e=Jg(this.tracer.log.bind(this.tracer)),t=Jg(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(B()).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(At({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ne(({currentQuality:i,videoBitrate:a})=>!!i&&!!a),B((i,a)=>i.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ne(i=>i>0),B()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ne(i=>i>0),B()).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(At({currentBuffer:this.info.currentBuffer$.pipe(ne(i=>i.end>0),B((i,a)=>i.end===a.end&&i.start===a.start)),position:this.info.position$.pipe(B())}).pipe(Xu(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(B()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(B()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(B()).subscribe(e("canChangePlaybackSpeed"))).add(At({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ne(({liveTime:i,liveBufferTime:a})=>!!i&&!!a),Xu(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(B(),ne(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(B(),ne(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(B()).subscribe(e("muted"))).add(this.info.volume$.pipe(B()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(B(),ne(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(At({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ne(({throughputEstimation:i,rtt:a})=>!!i&&!!a),Xu(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(B(),ne(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(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Gs.DOM,message:String(a)})})};this.subscription.add(Rt(Ku(document,"visibilitychange"),Ku(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",$t({quality:t,availableTracks:$t(e),track:$t(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}};import{Subscription as MG,Observable as DG,Subject as CG,ValueSubject as VG,VideoQuality as BG}from"@vkontakte/videoplayer-shared";var OG=`@vkontakte/videoplayer-core@${el}`;export{Ea as ChromecastState,zs as HttpConnectionType,DG as Observable,ue as PlaybackState,Ws as Player,OG as SDK_VERSION,CG as Subject,MG as Subscription,Ks as Surface,el as VERSION,VG as ValueSubject,mt as VideoFormat,BG as VideoQuality};
|
|
123
|
+
`;var Ys=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Qs(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ws(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"),r=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),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(r,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(a,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(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(XS,this.gl.VERTEX_SHADER),r=this.createShader(ZS,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),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,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),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,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,u=t-a,l=e+r,c=t+a,d=e-r,p=t+a;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as jL,now as ev,Subscription as GL,filter as QL,combine as tv,ValueSubject as rv,isNonNullable as WL}from"@vkontakte/videoplayer-shared";var ll=class{constructor(){this.isSeeked$=new rv(!1);this.isBuffering$=new rv(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new GL}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(tv({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(QL(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(tv({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(jL(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:a,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=ev(),p=n&&this.currentStallsCount>=n,h=a&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=a+u&&t>=a,f=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(p||h||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,WL(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=ev(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},iv=ll;var ur=class{constructor(e){this.subscription=new rM;this.videoState=new L("stopped");this.elementSize$=new iM(void 0);this.textTracksManager=new Le;this.droppedFramesManager=new ks;this.stallsManager=new iv;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new xi;this.audioTrackSwitchHistory=new xi;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),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"),I(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"),I(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&I(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return KL(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new Ys(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.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=pe(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(Z(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 Gs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=fe(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:cl.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(av(c=>!!c.length),nv()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(dl(c=>c.to.state!=="none"),ga());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(ga()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),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.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(av(sv),nv()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(dl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Je(this.video,t.isLooped,a)),this.subscription.add(me(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add($e(this.video,t.playbackRate,r.playbackRateState$,a)),s(tM(this.video),this.elementSize$),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(JL(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(Ju(f));let b=[];for(let g of f.representations){let S=BS(g);b.push(S),this.audioTracksMap.set(S,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Xu(h));let f=[];for(let b of h.representations){let g=VS({...b,streamId:h.id});g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}if(this.params.output.availableVideoStreams$.next(p),this.textTracksManager)for(let h of d.text)for(let f of h.representations){let b=_S(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let o=c=>e.error$.next({id:"RepresentationSwitch",category:cl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(zs(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,ZL(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,ov.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=[...this.videoTracksMap.keys()].find(S=>this.videoTracksMap.get(S)?.representation.id===h.id);sv(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),f){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,S).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSize$.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ga()).subscribe(c=>{let d=[...(0,pl.default)(this.videoTracksMap)].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Xu(h))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ga()).subscribe(c=>{let d=[...(0,pl.default)(this.audioTracksMap)].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Ju(h))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager?.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(dl(({to:c})=>c==="ready"),ga());this.subscription.add(zs(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(zs(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=zs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,eM(["init"])).pipe(XL(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:R})=>R===a),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:R})=>R===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Ze(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:R})=>R===f?.id)??this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let R=Is(n,c,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,R?.bitrate??-1/0)}if(o){let R=Is(o,c,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,R?.bitrate??-1/0)}}let S=Rt(c,{container:this.elementSize$.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,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}),k=r?S??n:n??S,E=b&&gb(k,c,this.audioStreamsMap.get(b)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(k)?.representation,y=E&&this.audioTracksMap.get(E)?.representation;if(A&&y)return[A,y];if(A&&!y&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cl.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.destroy3DScene(),this.textTracksManager?.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),he(this.video),this.tracer.end()}};var Sa=class extends ur{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as uv,interval as aM,map as lv}from"@vkontakte/videoplayer-shared";var va=class extends ur{constructor(e){super(e),this.liveOffset=new lt,this.textTracksManager=null}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:a}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),a(t.timeUpdate$,e.liveBufferTime$),a(this.player.liveDuration$,e.duration$),a(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(lv(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(uv({interval:aM(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{if(this.videoState.getState()==="playing"){let n=e.position$.getValue()+(s-1);n<=0&&e.position$.next(n),this.liveOffset?.resetTo(-n*1e3)}})).add(uv({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(lv(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=NS(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{this.params.output.position$.next(e/1e3),this.liveOffset?.resetTo(n,a)})}};var dv=$(gs(),1),pv=$(ut(),1);import{assertNever as ya,assertNonNullable as cv,debounce as sM,ErrorCategory as Ks,filter as nM,isNonNullable as oM,isNullable as uM,map as Js,merge as lM,Observable as cM,observableFrom as dM,Subscription as pM,videoSizeToQuality as hM}from"@vkontakte/videoplayer-shared";var He={};var Qr=(i,e)=>new cM(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ta=class{constructor(e){this.subscription=new pM;this.videoState=new L("initializing");this.textTracksManager=new Le;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(e!=="initializing")switch(r?.to!=="paused"&&a.state==="requested"&&this.seek(a.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ya(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ya(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ya(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ya(e)}break;default:ya(t)}};this.video=pe(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),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(Z(this.params.source.url)),this.loadHlsJs()}destroy(){this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),this.hls?.detachMedia(),this.hls?.destroy(),this.params.output.element$.next(void 0),he(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ks.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,dv.default)(import("hls.js").then(a=>{e||(He.Hls=a.default,He.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){cv(He.Hls,"hls.js not loaded"),this.hls=new He.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){cv(He.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Ks.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=fe(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Je(this.video,e.isLooped,r)),this.subscription.add(me(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add($e(this.video,e.playbackRate,a.playbackRateState$,r)),s(Ce(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Js(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Qr(this.hls,He.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Ks.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Qr(this.hls,He.Events.MANIFEST_PARSED).pipe(Js(({levels:l})=>l.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=At(d.attrs.QUALITY??"")??hM({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(Qr(this.hls,He.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Qr(this.hls,He.Events.LEVEL_LOADING).pipe(Js(({url:l})=>Z(l))),t.hostname$),s(Qr(this.hls,He.Events.FRAG_CHANGED),l=>{let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(xt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>Array.from((0,pv.default)(this.trackLevels)).find(({level:c})=>c===l)?.track,o=Qr(this.hls,He.Events.LEVEL_SWITCHED).pipe(Js(({level:l})=>n(this.hls.levels[l])));o.pipe(nM(oM)).subscribe(t.currentVideoTrack$,r),this.subscription.add(xt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(uM(l))return;let c=this.trackLevels.get(l.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=lM(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dM(["init"])).pipe(sM(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ks.DOM,thrown:t}))||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){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.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0)}};var hv="X-Playback-Duration",hl=async i=>{let e=await dt(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(hv)?parseInt(e.headers.get(hv),10):void 0};import{assertNever as vM,combine as yM,debounce as TM,ErrorCategory as Zs,filter as IM,filterChanged as EM,isNonNullable as fv,isNullable as en,map as bv,merge as xM,observableFrom as PM,Subscription as kM,ValueSubject as bl,VideoQuality as AM}from"@vkontakte/videoplayer-shared";var fl=$(vo(),1);import{videoSizeToQuality as mM,getExponentialDelay as fM}from"@vkontakte/videoplayer-shared";var bM=i=>{let e=null;if(i.QUALITY&&(e=At(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=mM({width:t,height:r})}return e??null},gM=(i,e)=>{let t=i.split(`
|
|
124
|
+
`),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,fl.default)(Object,o[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=bM(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,S]=l.RESOLUTION.split("x").map(k=>parseInt(k,10));g&&S&&(f={width:g,height:S})}let b=new URL(t[++s],e).toString();d&&r.push({id:c,quality:d,url:b,bandwidth:p,size:f,fps:h})}if(u){let l=(0,fl.default)(Object,u[1].split(",").map(h=>h.split("=")).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,p=l.NAME;c&&d&&a.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},SM=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),ml=0,mv=async(i,e=i,t)=>{let a=await(await dt(i)).text();ml+=1;try{let{qualityManifests:s,textTracks:n}=gM(a,e);return{qualityManifests:s,textTracks:n}}catch{if(ml<=t.manifestRetryMaxCount)return await SM(fM(ml-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),mv(i,e,t)}return{qualityManifests:[],textTracks:[]}},Xs=mv;var Ia=class{constructor(e){this.subscription=new kM;this.videoState=new L("stopped");this.textTracksManager=new Le;this.manifests$=new bl([]);this.liveOffset=new lt;this.manifestStartTime$=new bl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="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"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="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 a?.to==="paused"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return vM(t)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:AM.INVARIANT,url:this.params.source.url},Xs(se(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})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Zs.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Zs.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),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(Z(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new bl(e.source.maxSeekBackTime??1/0),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Zs.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=fe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(me(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ce(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(EM(),bv(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&fv(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(yM({startTime:this.manifestStartTime$.pipe(IM(fv)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(bv(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=xM(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,PM(["init"])).pipe(TM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){let e=this.selectManifest();if(en(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??r??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=se(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),hl(n).then(o=>{if(!en(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(en(u)||!isFinite(u))try{dt(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,n).toString();hl(d).then(p=>{en(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Zs.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as wM,debounce as RM,ErrorCategory as gl,fromEvent as Sl,isNonNullable as $M,isNullable as LM,map as gv,merge as Sv,observableFrom as vv,Subscription as MM,ValueSubject as CM,VideoQuality as DM,clientChecker as OM}from"@vkontakte/videoplayer-shared";var Ea=class{constructor(e){this.subscription=new MM;this.videoState=new L("stopped");this.textTracksManager=new Le;this.manifests$=new CM([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="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"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return wM(t)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:DM.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(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Xs(se(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:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:gl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:gl.WTF,message:"HlsProvider internal logic error",thrown:o})},a=fe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(gv(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(me(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&$M(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Z(f.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(gv(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!OM.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Sv(Sl(o,"addtrack"),Sl(o,"removetrack"),Sl(o,"change"),vv(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Sv(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,vv(["init"])).pipe(RM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),he(this.video)}prepare(){let e=this.selectManifest();if(LM(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:s,min:n}=t?.to??r??{};for(let[o,u]of[[s,"mq"],[n,"lq"]]){let l=String(parseFloat(o||""));u&&o&&a.searchParams.set(u,l)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Ev=$(It(),1),xa=$(ut(),1);import{assertNever as VM,assertNonNullable as yv,debounce as BM,ErrorCategory as Tv,isHigher as _M,isHigherOrEqual as NM,isInvariantQuality as Iv,isLowerOrEqual as FM,isNonNullable as qM,merge as UM,observableFrom as HM,Subscription as jM,map as GM}from"@vkontakte/videoplayer-shared";var Pa=class{constructor(e){this.subscription=new jM;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Le;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=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"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?I(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),I(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()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return VM(e)}};this.params=e,this.video=pe(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Ev.default)(Object,this.params.source).reverse().forEach(([t,r],a)=>{let s=a.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,xa.default)(Object,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,r=o=>{e.error$.next({id:"MpegProvider",category:Tv.WTF,message:"MpegProvider internal logic error",thrown:o})},a=fe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.loadedMetadata$,e.loadedMetadataEvent$),s(a.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(GM(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(me(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ce(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&qM(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=UM(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,HM(["init"])).pipe(BM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}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;yv(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];yv(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ua(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Z(t))}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Tv.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=(0,xa.default)(Object,this.trackUrls).find(o=>!Iv(o.track.quality)&&FM(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&NM(n.quality,a.quality)&&(t=a),!t){let o=(0,xa.default)(Object,this.trackUrls).filter(l=>!Iv(l.track.quality)&&_M(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(r=t.quality)}else if(!e){let a=(0,xa.default)(Object,this.trackUrls).map(s=>s.track);t=Rt(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as Pv,debounce as zM,merge as kv,observableFrom as KM,Subscription as JM,map as Av,ValueSubject as XM,ErrorCategory as yl,VideoQuality as ZM}from"@vkontakte/videoplayer-shared";import{ErrorCategory as QM}from"@vkontakte/videoplayer-shared";var xv=["stun:videostun.mycdn.me:80"],WM=1e3,YM=3,vl=()=>null,tn=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=vl;this.externalStopCallback=vl;this.externalErrorCallback=vl;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.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:xv}]};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:QM.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),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))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),WM)}normalizeOptions(e={}){let t={stunServerList:xv,maxRetryNumber:YM,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var ka=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new XM(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=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"),I(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"),I(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()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Pv(e)}};this.subscription=new JM,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=pe(e.container,e.tuning),this.liveStreamClient=new tn(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,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:yl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};kv(this.videoState.stateChangeStarted$.pipe(Av(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Av(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=fe(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Ce(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(me(this.video,t.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(e.volume$,r)).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 Pv(n.to)}},r)).add(kv(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,KM(["init"])).pipe(zM(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}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(Z(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:ZM.INVARIANT}),this.video.srcObject=e,I(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:yl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){be(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:yl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Aa=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as wa,assertNonNullable as Ot,ErrorCategory as rn,filter as Cv,isNonNullable as Dv,isNullable as oC,map as uC,merge as lC,once as cC,Subject as ve,Subscription as Ov,ValueSubject as M,flattenObject as Vv}from"@vkontakte/videoplayer-shared";import{Observable as eC,map as wv,Subscription as tC,Subject as rC}from"@vkontakte/videoplayer-shared";var Rv=i=>new eC(e=>{let t=new tC,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(wv(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(wv(({type:l})=>l!==void 0)),n=new rC,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as iC,Subscription as aC,combine as sC,filter as Lv,once as Mv}from"@vkontakte/videoplayer-shared";function $v(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as nC}from"@vkontakte/videoplayer-shared";var Wr=class i{constructor(e,t,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.destroyController=new ke;this.subscriptions=new aC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Lv(s=>!!s.type),Mv()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){nC.isSafari&&e!=="MPEG"||this.subscriptions.add(sC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Lv(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),Mv()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}async initAudioContextOnce(e){let{volumeMultiplier:t}=this,r=$v();this.audioContext=r;let a=r.createGain();if(this.gainNode=a,a.gain.value=t,a.connect(r.destination),r.state==="suspended"&&(await r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(a),!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:i.errorId,category:iC.VIDEO_PIPELINE,message:e?.message??`${i.errorId} exception`,thrown:e})}};var dC={chunkDuration:5e3,maxParallelRequests:5},Ra=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new ve;this.noAvailableProvidersError$=new ve;this.volumeMultiplierError$=new ve;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),availableVideoStreams$:new M([]),currentVideoStream$:new M(void 0),availableVideoTracks$:new M([]),currentVideoTrack$:new M(void 0),availableAudioStreams$:new M([]),currentAudioStream$:new M(void 0),availableAudioTracks$:new M([]),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new ve,warning$:new ve,willSeekEvent$:new ve,soundProhibitedEvent$:new ve,seekedEvent$:new ve,loopedEvent$:new ve,endedEvent$:new ve,firstBytesEvent$:new ve,loadedMetadataEvent$:new ve,firstFrameEvent$:new ve,canplay$:new ve,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),liveLatency$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new Ov;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=ag([...ng(this.params.tuning),...sg(this.params.tuning)],this.params.tuning).filter(l=>Dv(e.sources[l])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(l=>!(0,Tl.default)(a,l)),...t.filter(l=>(0,Tl.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Vv(s)),this.screenFormatsIterator=new Aa(s);let n=[...$u(!0),...$u(!1)];this.chromecastFormatsIterator=new Aa(n.filter(l=>Dv(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Wr.isSupported()&&(this.volumeMultiplierManager=new Wr(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),this.volumeMultiplierManager?.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(oC(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:rn.WTF,message:"Failed to create provider",thrown:a})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),a=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:a?r.position:t,forcePrecise:a?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();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 wa(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:a}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Ot(o),new Sa({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ot(o),new va({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ot(o),Fr||!this.params.tuning.useHlsJs?new Ea({...n,source:o}):new Ta({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Ia({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Pa({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ot(o),new Mb({...n,source:o,config:{...dC,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ot(o),new ka({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return wa(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ot(o),new yi({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,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 wa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return wa(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 wa(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=a=>{let s=new URL(a);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:r(e.url)}}return(0,_v.default)(Object,(0,Bv.default)(Object,e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Ov,t=!1,r=0;return e.add(lC(this.providerOutput.error$.pipe(Cv(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),Rv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(uC(a=>({id:`ProviderHangup:${a}`,category:rn.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(Cv(({to:s})=>s==="playing"),cC()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination,n={error:a,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=a.category===rn.NETWORK,u=a.category===rn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",Vv(n))})),e}};import{fromEvent as an,once as pC,combine as hC,Subscription as Nv,ValueSubject as Il,map as mC,filter as fC,isNonNullable as sn,now as we,safeStorage as El}from"@vkontakte/videoplayer-shared";var bC=5e3,Fv="one_video_throughput",qv="one_video_rtt",$a=window.navigator.connection,Uv=()=>{let i=$a?.downlink;if(sn(i)&&i!==10)return i*1e3},Hv=()=>{let i=$a?.rtt;if(sn(i)&&i!==3e3)return i},jv=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},xl=class i{constructor(e){this.subscription=new Nv;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(Fv)||(e.useBrowserEstimation?Uv():void 0)||bC,r=i.load(qv)??(e.useBrowserEstimation?Hv():void 0)??0;if(this.throughput$=new Il(t),this.rtt$=new Il(r),this.rttAdjustedThroughput$=new Il(jv(t,r,e.rttPenaltyRequestSize)),this.throughput=ar.getSmoothedValue(t,-1,e),this.rtt=ar.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=Uv();n&&this.throughput.next(n);let o=Hv();sn(o)&&this.rtt.next(o)};$a&&"onchange"in $a&&this.subscription.add(an($a,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{El.set(Fv,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{El.set(qv,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(hC({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(mC(({throughput:a,rtt:s})=>jv(a,s,e.rttPenaltyRequestSize)),fC(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=we(),a=new Nv;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(an(e,"progress").pipe(pC()).subscribe(s=>{t=s.loaded,r=we()}));break;case 1:case 0:a.add(an(e,"loadstart").subscribe(()=>{t=0,r=we()}));break}a.add(an(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=we(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=we(),n=0,o=we(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,we()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=we();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=we()}else n+=d.byteLength;o=we()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&we()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,we()-o,this.concurrentDownloads.size),n=0,o=we());await r?.read().then(l,u)}};this.concurrentDownloads.add(e),r?.read().then(l,u)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=El.get(e);if(sn(t))return parseInt(t,10)??void 0}},Gv=xl;import{fillWithDefault as gC,VideoQuality as Qv}from"@vkontakte/videoplayer-shared";var Wv={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:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Qv.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Qv.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!0,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!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,useOldMSEDetection:!1},Yv=i=>({...gC(i,Wv),configName:[...i.configName??[],...Wv.configName]});import{assertNonNullable as nn,combine as ft,ErrorCategory as on,filter as ne,filterChanged as B,fromEvent as kl,isNonNullable as xC,isNullable as PC,Logger as kC,map as D,mapTo as Xv,merge as Vt,now as un,once as tt,Subject as H,Subscription as Zv,tap as ey,ValueSubject as x,isHigher as AC,isInvariantQuality as ty,flattenObject as Bt,throttle as Al,getTraceSubscriptionMethod as ry,Tracer as wC}from"@vkontakte/videoplayer-shared";import{merge as SC,map as vC,filter as zv,isNonNullable as yC}from"@vkontakte/videoplayer-shared";var Pl=({seekState:i,position$:e})=>SC(i.stateChangeEnded$.pipe(vC(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),zv(yC)),e.pipe(zv(()=>i.getState().state==="none")));import{assertNonNullable as TC}from"@vkontakte/videoplayer-shared";var Kv=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return TC(e,`Wrong container or containerId {${i.container}}`),e};import{filter as IC,once as EC}from"@vkontakte/videoplayer-shared";var Jv=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(IC(a=>a.length>0),EC()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var ln=class{constructor(e={configName:[]},t=wC.createRootTracer(!1)){this.subscription=new Zv;this.logger=new kC;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new x(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),isLowLatency:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new x("stopped"),position$:new x(0),duration$:new x(1/0),muted$:new x(!1),volume$:new x(1),availableVideoStreams$:new x([]),currentVideoStream$:new x(void 0),availableQualities$:new x([]),availableQualitiesFps$:new x({}),currentQuality$:new x(void 0),isAutoQualityEnabled$:new x(!0),autoQualityLimitingAvailable$:new x(!1),autoQualityLimits$:new x({}),availableAudioStreams$:new x([]),currentAudioStream$:new x(void 0),availableAudioTracks$:new x([]),isAudioAvailable$:new x(!0),currentPlaybackRate$:new x(1),currentBuffer$:new x({start:0,end:0}),isBuffering$:new x(!0),isStalled$:new x(!1),isEnded$:new x(!1),isLooped$:new x(!1),isLive$:new x(void 0),canChangePlaybackSpeed$:new x(void 0),atLiveEdge$:new x(void 0),atLiveDurationEdge$:new x(void 0),liveTime$:new x(void 0),liveBufferTime$:new x(void 0),liveLatency$:new x(void 0),currentFormat$:new x(void 0),availableTextTracks$:new x([]),currentTextTrack$:new x(void 0),throughputEstimation$:new x(void 0),rttEstimation$:new x(void 0),videoBitrate$:new x(void 0),hostname$:new x(void 0),httpConnectionType$:new x(void 0),httpConnectionReused$:new x(void 0),surface$:new x("none"),chromecastState$:new x("NOT_AVAILABLE"),chromecastDeviceName$:new x(void 0),intrinsicVideoSize$:new x(void 0),availableSources$:new x(void 0),is3DVideo$:new x(!1),currentVideoSegmentLength$:new x(0),currentAudioSegmentLength$:new x(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,autoplaySoundProhibited$:new H,firstBytes$:new H,loadedMetadata$:new H,firstFrame$:new H,canplay$:new H,log$:new H};this.experimental={element$:new x(void 0),tuningConfigName$:new x([]),enableDebugTelemetry$:new x(!1),dumpTelemetry:ob};if(this.initLogs(),this.tuning=Yv(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ha({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Gv(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,a,s)=>{let n=Reflect.get(r,a,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,iy.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(a)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:on.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Bt(r)),this.domContainer=Kv(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Ra({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}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),this.providerContainer?.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ri()?(this.tracer.log("request play from hidden tab"),kl(document,"visibilitychange").pipe(tt()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=r&&!a&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){nn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return 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(ne(r=>r.length>0),tt()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Bt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){nn(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Bt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return Jv(e,this.desiredState.currentTextTrack,this.providerContainer?.providerOutput.availableTextTracks$,t=>t.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",{...e}),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let a=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+s.x,y:a.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(PC(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return xC(r)?r/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((r,{width:a})=>r||a||0,0),height:e.reduce((r,{height:a})=>r||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Vt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ne(({from:e})=>e==="stopped"),tt()).subscribe(()=>{this.initedAt=un(),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"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",Bt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:on.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(tt()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Bt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(D(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(n=>n.destination),B()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(ft({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(ne(({currentVideoStream:n})=>!!n),D(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?.id===u.streamId).map(({quality:u})=>u).sort((u,l)=>ty(u)?1:ty(l)?-1:AC(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(B()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(B((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(B((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(B()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(B()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(B()).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(D(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.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(ft({hasLiveOffsetByPaused:Vt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(n=>n.to),B(),D(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(ft({atLiveEdge:ft({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Pl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),B(),ey(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(ft({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),B(),ey(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(n=>n.muted),B()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(n=>n.volume),B()).subscribe(this.info.volume$)).add(Pl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Vt(e.providerOutput.endedEvent$.pipe(Xv(!0)),e.providerOutput.seekedEvent$.pipe(Xv(!1))).pipe(B()).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.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(D(n=>({id:n?`No${n}`:"NoProviders",category:on.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.firstBytesEvent$.pipe(tt(),D(n=>n??un()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(tt(),D(()=>un()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(tt(),D(()=>un()-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 x(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new x(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ne(({to:n})=>n==="playing"),tt()).subscribe(()=>r.next(!1)));let a=0,s=Vt(e.providerOutput.isBuffering$,t,r).pipe(D(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),B());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(Vt(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.videoWidth,height:n?.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n?.size?.width,height:n?.size?.height},{width:o?.videoWidth,height:o?.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(Vt(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(D(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Zv;this.subscription.add(t),this.subscription.add(e.current$.pipe(B((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ne(r=>r.length>0),tt()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let r=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=Rt(e,{container:this.domContainer.getBoundingClientRect(),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(Vt(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(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;nn(this.providerContainer),nn(e),nb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>sb(t)),this.providerContainer.current$.subscribe(({type:t})=>Ei("provider",t)),e.duration$.subscribe(t=>Ei("duration",t)),e.availableVideoTracks$.pipe(ne(t=>!!t.length),tt()).subscribe(t=>Ei("tracks",t)),this.events.fatalError$.subscribe(new ue("fatalError")),this.events.managedError$.subscribe(new ue("managedError")),e.position$.subscribe(new ue("position")),e.currentVideoTrack$.pipe(D(t=>t?.quality)).subscribe(new ue("quality")),this.info.currentBuffer$.subscribe(new ue("buffer")),e.isBuffering$.subscribe(new ue("isBuffering"))].forEach(t=>this.subscription.add(t)),Ei("codecs",ig())}initTracerSubscription(){let e=ry(this.tracer.log.bind(this.tracer)),t=ry(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(B()).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(ft({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ne(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),B((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ne(r=>r>0),B()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ne(r=>r>0),B()).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(ft({currentBuffer:this.info.currentBuffer$.pipe(ne(r=>r.end>0),B((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe(B())}).pipe(Al(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(B()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(B()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(B()).subscribe(e("canChangePlaybackSpeed"))).add(ft({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ne(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),Al(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(B(),ne(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(B(),ne(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(B()).subscribe(e("muted"))).add(this.info.volume$.pipe(B()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(B(),ne(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(ft({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ne(({throughputEstimation:r,rtt:a})=>!!r&&!!a),Al(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(B(),ne(r=>r===!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},r=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:on.DOM,message:String(a)})})};this.subscription.add(Vt(kl(document,"visibilitychange"),kl(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",Bt({quality:t,availableTracks:Bt(e),track:Bt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as _Y,Observable as NY,Subject as FY,ValueSubject as qY,VideoQuality as UY}from"@vkontakte/videoplayer-shared";var HY=`@vkontakte/videoplayer-core@${$l}`;export{Ba as ChromecastState,dn as HttpConnectionType,NY as Observable,de as PlaybackState,ln as Player,HY as SDK_VERSION,FY as Subject,_Y as Subscription,pn as Surface,$l as VERSION,qY as ValueSubject,vt as VideoFormat,UY as VideoQuality};
|