@vkontakte/videoplayer-core 2.0.124-dev.594551f7.0 → 2.0.124-dev.6f019bb5.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 +12 -12
- package/es2015.esm.js +12 -12
- package/es2018.cjs.js +13 -13
- package/es2018.esm.js +13 -13
- package/esnext.cjs.js +10 -10
- package/esnext.esm.js +12 -12
- package/evergreen.esm.js +5 -5
- package/package.json +2 -2
- package/types/player/types.d.ts +1 -1
- package/types/providers/MpegProvider/index.d.ts +1 -0
package/esnext.esm.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.124-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.124-dev.6f019bb5.0
|
|
3
|
+
* Tue, 28 Jan 2025 10:43:43 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-124/doc/
|
|
5
5
|
*/
|
|
6
|
-
var Ty=Object.create;var Ul=Object.defineProperty;var Iy=Object.getOwnPropertyDescriptor;var Ey=Object.getOwnPropertyNames;var xy=Object.getPrototypeOf,Py=Object.prototype.hasOwnProperty;var h=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var wy=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ey(e))!Py.call(i,a)&&a!==t&&Ul(i,a,{get:()=>e[a],enumerable:!(r=Iy(e,a))||r.enumerable});return i};var D=(i,e,t)=>(t=i!=null?Ty(xy(i)):{},wy(e||!i||!i.__esModule?Ul(t,"default",{value:i,enumerable:!0}):t,i));var Y=h((En,jl)=>{"use strict";var Zr=function(i){return i&&i.Math===Math&&i};jl.exports=Zr(typeof globalThis=="object"&&globalThis)||Zr(typeof window=="object"&&window)||Zr(typeof self=="object"&&self)||Zr(typeof global=="object"&&global)||Zr(typeof En=="object"&&En)||function(){return this}()||Function("return this")()});var re=h((a0,Ql)=>{"use strict";Ql.exports=function(i){try{return!!i()}catch{return!0}}});var ei=h((s0,Gl)=>{"use strict";var ky=re();Gl.exports=!ky(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var xn=h((n0,Kl)=>{"use strict";var Ay=ei(),zl=Function.prototype,Wl=zl.apply,Yl=zl.call;Kl.exports=typeof Reflect=="object"&&Reflect.apply||(Ay?Yl.bind(Wl):function(){return Yl.apply(Wl,arguments)})});var J=h((o0,Zl)=>{"use strict";var Xl=ei(),Jl=Function.prototype,Pn=Jl.call,Ly=Xl&&Jl.bind.bind(Pn,Pn);Zl.exports=Xl?Ly:function(i){return function(){return Pn.apply(i,arguments)}}});var Ut=h((u0,tc)=>{"use strict";var ec=J(),Ry=ec({}.toString),$y=ec("".slice);tc.exports=function(i){return $y(Ry(i),8,-1)}});var wn=h((l0,rc)=>{"use strict";var My=Ut(),Dy=J();rc.exports=function(i){if(My(i)==="Function")return Dy(i)}});var W=h((c0,ic)=>{"use strict";var kn=typeof document=="object"&&document.all;ic.exports=typeof kn>"u"&&kn!==void 0?function(i){return typeof i=="function"||i===kn}:function(i){return typeof i=="function"}});var Ee=h((d0,ac)=>{"use strict";var Cy=re();ac.exports=!Cy(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var xe=h((p0,sc)=>{"use strict";var Vy=ei(),Ha=Function.prototype.call;sc.exports=Vy?Ha.bind(Ha):function(){return Ha.apply(Ha,arguments)}});var An=h(uc=>{"use strict";var nc={}.propertyIsEnumerable,oc=Object.getOwnPropertyDescriptor,By=oc&&!nc.call({1:2},1);uc.f=By?function(e){var t=oc(this,e);return!!t&&t.enumerable}:nc});var ti=h((m0,lc)=>{"use strict";lc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var dc=h((f0,cc)=>{"use strict";var Oy=J(),_y=re(),Ny=Ut(),Ln=Object,Fy=Oy("".split);cc.exports=_y(function(){return!Ln("z").propertyIsEnumerable(0)})?function(i){return Ny(i)==="String"?Fy(i,""):Ln(i)}:Ln});var br=h((b0,pc)=>{"use strict";pc.exports=function(i){return i==null}});var Tt=h((g0,hc)=>{"use strict";var qy=br(),Uy=TypeError;hc.exports=function(i){if(qy(i))throw new Uy("Can't call method on "+i);return i}});var Ht=h((v0,mc)=>{"use strict";var Hy=dc(),jy=Tt();mc.exports=function(i){return Hy(jy(i))}});var Pe=h((S0,fc)=>{"use strict";var Qy=W();fc.exports=function(i){return typeof i=="object"?i!==null:Qy(i)}});var gr=h((y0,bc)=>{"use strict";bc.exports={}});var ut=h((T0,vc)=>{"use strict";var Rn=gr(),$n=Y(),Gy=W(),gc=function(i){return Gy(i)?i:void 0};vc.exports=function(i,e){return arguments.length<2?gc(Rn[i])||gc($n[i]):Rn[i]&&Rn[i][e]||$n[i]&&$n[i][e]}});var ri=h((I0,Sc)=>{"use strict";var Wy=J();Sc.exports=Wy({}.isPrototypeOf)});var jt=h((E0,Ic)=>{"use strict";var Yy=Y(),yc=Yy.navigator,Tc=yc&&yc.userAgent;Ic.exports=Tc?String(Tc):""});var Dn=h((x0,Ac)=>{"use strict";var kc=Y(),Mn=jt(),Ec=kc.process,xc=kc.Deno,Pc=Ec&&Ec.versions||xc&&xc.version,wc=Pc&&Pc.v8,qe,ja;wc&&(qe=wc.split("."),ja=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!ja&&Mn&&(qe=Mn.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=Mn.match(/Chrome\/(\d+)/),qe&&(ja=+qe[1])));Ac.exports=ja});var Cn=h((P0,Rc)=>{"use strict";var Lc=Dn(),zy=re(),Ky=Y(),Xy=Ky.String;Rc.exports=!!Object.getOwnPropertySymbols&&!zy(function(){var i=Symbol("symbol detection");return!Xy(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Lc&&Lc<41})});var Vn=h((w0,$c)=>{"use strict";var Jy=Cn();$c.exports=Jy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Bn=h((k0,Mc)=>{"use strict";var Zy=ut(),eT=W(),tT=ri(),rT=Vn(),iT=Object;Mc.exports=rT?function(i){return typeof i=="symbol"}:function(i){var e=Zy("Symbol");return eT(e)&&tT(e.prototype,iT(i))}});var ii=h((A0,Dc)=>{"use strict";var aT=String;Dc.exports=function(i){try{return aT(i)}catch{return"Object"}}});var Ze=h((L0,Cc)=>{"use strict";var sT=W(),nT=ii(),oT=TypeError;Cc.exports=function(i){if(sT(i))return i;throw new oT(nT(i)+" is not a function")}});var ai=h((R0,Vc)=>{"use strict";var uT=Ze(),lT=br();Vc.exports=function(i,e){var t=i[e];return lT(t)?void 0:uT(t)}});var Oc=h(($0,Bc)=>{"use strict";var On=xe(),_n=W(),Nn=Pe(),cT=TypeError;Bc.exports=function(i,e){var t,r;if(e==="string"&&_n(t=i.toString)&&!Nn(r=On(t,i))||_n(t=i.valueOf)&&!Nn(r=On(t,i))||e!=="string"&&_n(t=i.toString)&&!Nn(r=On(t,i)))return r;throw new cT("Can't convert object to primitive value")}});var Ue=h((M0,_c)=>{"use strict";_c.exports=!0});var qc=h((D0,Fc)=>{"use strict";var Nc=Y(),dT=Object.defineProperty;Fc.exports=function(i,e){try{dT(Nc,i,{value:e,configurable:!0,writable:!0})}catch{Nc[i]=e}return e}});var si=h((C0,jc)=>{"use strict";var pT=Ue(),hT=Y(),mT=qc(),Uc="__core-js_shared__",Hc=jc.exports=hT[Uc]||mT(Uc,{});(Hc.versions||(Hc.versions=[])).push({version:"3.38.0",mode:pT?"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 Fn=h((V0,Gc)=>{"use strict";var Qc=si();Gc.exports=function(i,e){return Qc[i]||(Qc[i]=e||{})}});var vr=h((B0,Wc)=>{"use strict";var fT=Tt(),bT=Object;Wc.exports=function(i){return bT(fT(i))}});var He=h((O0,Yc)=>{"use strict";var gT=J(),vT=vr(),ST=gT({}.hasOwnProperty);Yc.exports=Object.hasOwn||function(e,t){return ST(vT(e),t)}});var qn=h((_0,zc)=>{"use strict";var yT=J(),TT=0,IT=Math.random(),ET=yT(1 .toString);zc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+ET(++TT+IT,36)}});var ie=h((N0,Xc)=>{"use strict";var xT=Y(),PT=Fn(),Kc=He(),wT=qn(),kT=Cn(),AT=Vn(),Sr=xT.Symbol,Un=PT("wks"),LT=AT?Sr.for||Sr:Sr&&Sr.withoutSetter||wT;Xc.exports=function(i){return Kc(Un,i)||(Un[i]=kT&&Kc(Sr,i)?Sr[i]:LT("Symbol."+i)),Un[i]}});var td=h((F0,ed)=>{"use strict";var RT=xe(),Jc=Pe(),Zc=Bn(),$T=ai(),MT=Oc(),DT=ie(),CT=TypeError,VT=DT("toPrimitive");ed.exports=function(i,e){if(!Jc(i)||Zc(i))return i;var t=$T(i,VT),r;if(t){if(e===void 0&&(e="default"),r=RT(t,i,e),!Jc(r)||Zc(r))return r;throw new CT("Can't convert object to primitive value")}return e===void 0&&(e="number"),MT(i,e)}});var Hn=h((q0,rd)=>{"use strict";var BT=td(),OT=Bn();rd.exports=function(i){var e=BT(i,"string");return OT(e)?e:e+""}});var Qa=h((U0,ad)=>{"use strict";var _T=Y(),id=Pe(),jn=_T.document,NT=id(jn)&&id(jn.createElement);ad.exports=function(i){return NT?jn.createElement(i):{}}});var Qn=h((H0,sd)=>{"use strict";var FT=Ee(),qT=re(),UT=Qa();sd.exports=!FT&&!qT(function(){return Object.defineProperty(UT("div"),"a",{get:function(){return 7}}).a!==7})});var ud=h(od=>{"use strict";var HT=Ee(),jT=xe(),QT=An(),GT=ti(),WT=Ht(),YT=Hn(),zT=He(),KT=Qn(),nd=Object.getOwnPropertyDescriptor;od.f=HT?nd:function(e,t){if(e=WT(e),t=YT(t),KT)try{return nd(e,t)}catch{}if(zT(e,t))return GT(!jT(QT.f,e,t),e[t])}});var Gn=h((Q0,ld)=>{"use strict";var XT=re(),JT=W(),ZT=/#|\.prototype\./,ni=function(i,e){var t=tI[eI(i)];return t===iI?!0:t===rI?!1:JT(e)?XT(e):!!e},eI=ni.normalize=function(i){return String(i).replace(ZT,".").toLowerCase()},tI=ni.data={},rI=ni.NATIVE="N",iI=ni.POLYFILL="P";ld.exports=ni});var yr=h((G0,dd)=>{"use strict";var cd=wn(),aI=Ze(),sI=ei(),nI=cd(cd.bind);dd.exports=function(i,e){return aI(i),e===void 0?i:sI?nI(i,e):function(){return i.apply(e,arguments)}}});var Wn=h((W0,pd)=>{"use strict";var oI=Ee(),uI=re();pd.exports=oI&&uI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var et=h((Y0,hd)=>{"use strict";var lI=Pe(),cI=String,dI=TypeError;hd.exports=function(i){if(lI(i))return i;throw new dI(cI(i)+" is not an object")}});var Qt=h(fd=>{"use strict";var pI=Ee(),hI=Qn(),mI=Wn(),Ga=et(),md=Hn(),fI=TypeError,Yn=Object.defineProperty,bI=Object.getOwnPropertyDescriptor,zn="enumerable",Kn="configurable",Xn="writable";fd.f=pI?mI?function(e,t,r){if(Ga(e),t=md(t),Ga(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Xn in r&&!r[Xn]){var a=bI(e,t);a&&a[Xn]&&(e[t]=r.value,r={configurable:Kn in r?r[Kn]:a[Kn],enumerable:zn in r?r[zn]:a[zn],writable:!1})}return Yn(e,t,r)}:Yn:function(e,t,r){if(Ga(e),t=md(t),Ga(r),hI)try{return Yn(e,t,r)}catch{}if("get"in r||"set"in r)throw new fI("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Tr=h((K0,bd)=>{"use strict";var gI=Ee(),vI=Qt(),SI=ti();bd.exports=gI?function(i,e,t){return vI.f(i,e,SI(1,t))}:function(i,e,t){return i[e]=t,i}});var K=h((X0,vd)=>{"use strict";var oi=Y(),yI=xn(),TI=wn(),II=W(),EI=ud().f,xI=Gn(),Ir=gr(),PI=yr(),Er=Tr(),gd=He();si();var wI=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 yI(i,this,arguments)};return e.prototype=i.prototype,e};vd.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?oi:a?oi[t]:oi[t]&&oi[t].prototype,o=r?Ir:Ir[t]||Er(Ir,t,{})[t],u=o.prototype,l,d,c,p,m,f,b,g,v;for(p in e)l=xI(r?p:t+(a?".":"#")+p,i.forced),d=!l&&n&&gd(n,p),f=o[p],d&&(i.dontCallGetSet?(v=EI(n,p),b=v&&v.value):b=n[p]),m=d&&b?b:e[p],!(!l&&!s&&typeof f==typeof m)&&(i.bind&&d?g=PI(m,oi):i.wrap&&d?g=wI(m):s&&II(m)?g=TI(m):g=m,(i.sham||m&&m.sham||f&&f.sham)&&Er(g,"sham",!0),Er(o,p,g),s&&(c=t+"Prototype",gd(Ir,c)||Er(Ir,c,{}),Er(Ir[c],p,m),i.real&&u&&(l||!u[p])&&Er(u,p,m)))}});var yd=h((J0,Sd)=>{"use strict";var kI=Math.ceil,AI=Math.floor;Sd.exports=Math.trunc||function(e){var t=+e;return(t>0?AI:kI)(t)}});var ui=h((Z0,Td)=>{"use strict";var LI=yd();Td.exports=function(i){var e=+i;return e!==e||e===0?0:LI(e)}});var Ed=h((eC,Id)=>{"use strict";var RI=ui(),$I=Math.max,MI=Math.min;Id.exports=function(i,e){var t=RI(i);return t<0?$I(t+e,0):MI(t,e)}});var Jn=h((tC,xd)=>{"use strict";var DI=ui(),CI=Math.min;xd.exports=function(i){var e=DI(i);return e>0?CI(e,9007199254740991):0}});var xr=h((rC,Pd)=>{"use strict";var VI=Jn();Pd.exports=function(i){return VI(i.length)}});var Zn=h((iC,kd)=>{"use strict";var BI=Ht(),OI=Ed(),_I=xr(),wd=function(i){return function(e,t,r){var a=BI(e),s=_I(a);if(s===0)return!i&&-1;var n=OI(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}};kd.exports={includes:wd(!0),indexOf:wd(!1)}});var li=h((aC,Ad)=>{"use strict";Ad.exports=function(){}});var Ld=h(()=>{"use strict";var NI=K(),FI=Zn().includes,qI=re(),UI=li(),HI=qI(function(){return!Array(1).includes()});NI({target:"Array",proto:!0,forced:HI},{includes:function(e){return FI(this,e,arguments.length>1?arguments[1]:void 0)}});UI("includes")});var It=h((oC,Rd)=>{"use strict";var jI=ut();Rd.exports=jI});var Md=h((uC,$d)=>{"use strict";Ld();var QI=It();$d.exports=QI("Array","includes")});var Cd=h((lC,Dd)=>{"use strict";var GI=Md();Dd.exports=GI});var je=h((cC,Vd)=>{"use strict";var WI=Cd();Vd.exports=WI});var za=h((IC,Hd)=>{"use strict";var tE=Fn(),rE=qn(),Ud=tE("keys");Hd.exports=function(i){return Ud[i]||(Ud[i]=rE(i))}});var Qd=h((EC,jd)=>{"use strict";var iE=re();jd.exports=!iE(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Ka=h((xC,Wd)=>{"use strict";var aE=He(),sE=W(),nE=vr(),oE=za(),uE=Qd(),Gd=oE("IE_PROTO"),ro=Object,lE=ro.prototype;Wd.exports=uE?ro.getPrototypeOf:function(i){var e=nE(i);if(aE(e,Gd))return e[Gd];var t=e.constructor;return sE(t)&&e instanceof t?t.prototype:e instanceof ro?lE:null}});var Xa=h((PC,Yd)=>{"use strict";Yd.exports={}});var Xd=h((wC,Kd)=>{"use strict";var cE=J(),io=He(),dE=Ht(),pE=Zn().indexOf,hE=Xa(),zd=cE([].push);Kd.exports=function(i,e){var t=dE(i),r=0,a=[],s;for(s in t)!io(hE,s)&&io(t,s)&&zd(a,s);for(;e.length>r;)io(t,s=e[r++])&&(~pE(a,s)||zd(a,s));return a}});var ao=h((kC,Jd)=>{"use strict";Jd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var so=h((AC,Zd)=>{"use strict";var mE=Xd(),fE=ao();Zd.exports=Object.keys||function(e){return mE(e,fE)}});var no=h((LC,ap)=>{"use strict";var tp=Ee(),bE=re(),rp=J(),gE=Ka(),vE=so(),SE=Ht(),yE=An().f,ip=rp(yE),TE=rp([].push),IE=tp&&bE(function(){var i=Object.create(null);return i[2]=2,!ip(i,2)}),ep=function(i){return function(e){for(var t=SE(e),r=vE(t),a=IE&&gE(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!tp||(a?u in t:ip(t,u)))&&TE(o,i?[u,t[u]]:t[u]);return o}};ap.exports={entries:ep(!0),values:ep(!1)}});var sp=h(()=>{"use strict";var EE=K(),xE=no().entries;EE({target:"Object",stat:!0},{entries:function(e){return xE(e)}})});var op=h((MC,np)=>{"use strict";sp();var PE=gr();np.exports=PE.Object.entries});var lp=h((DC,up)=>{"use strict";var wE=op();up.exports=wE});var Pr=h((CC,cp)=>{"use strict";var kE=lp();cp.exports=kE});var Gt=h((VC,dp)=>{"use strict";dp.exports={}});var mp=h((BC,hp)=>{"use strict";var AE=Y(),LE=W(),pp=AE.WeakMap;hp.exports=LE(pp)&&/native code/.test(String(pp))});var co=h((OC,gp)=>{"use strict";var RE=mp(),bp=Y(),$E=Pe(),ME=Tr(),oo=He(),uo=si(),DE=za(),CE=Xa(),fp="Object already initialized",lo=bp.TypeError,VE=bp.WeakMap,Ja,ci,Za,BE=function(i){return Za(i)?ci(i):Ja(i,{})},OE=function(i){return function(e){var t;if(!$E(e)||(t=ci(e)).type!==i)throw new lo("Incompatible receiver, "+i+" required");return t}};RE||uo.state?(Qe=uo.state||(uo.state=new VE),Qe.get=Qe.get,Qe.has=Qe.has,Qe.set=Qe.set,Ja=function(i,e){if(Qe.has(i))throw new lo(fp);return e.facade=i,Qe.set(i,e),e},ci=function(i){return Qe.get(i)||{}},Za=function(i){return Qe.has(i)}):(Wt=DE("state"),CE[Wt]=!0,Ja=function(i,e){if(oo(i,Wt))throw new lo(fp);return e.facade=i,ME(i,Wt,e),e},ci=function(i){return oo(i,Wt)?i[Wt]:{}},Za=function(i){return oo(i,Wt)});var Qe,Wt;gp.exports={set:Ja,get:ci,has:Za,enforce:BE,getterFor:OE}});var mo=h((_C,Sp)=>{"use strict";var po=Ee(),_E=He(),vp=Function.prototype,NE=po&&Object.getOwnPropertyDescriptor,ho=_E(vp,"name"),FE=ho&&function(){}.name==="something",qE=ho&&(!po||po&&NE(vp,"name").configurable);Sp.exports={EXISTS:ho,PROPER:FE,CONFIGURABLE:qE}});var Tp=h(yp=>{"use strict";var UE=Ee(),HE=Wn(),jE=Qt(),QE=et(),GE=Ht(),WE=so();yp.f=UE&&!HE?Object.defineProperties:function(e,t){QE(e);for(var r=GE(t),a=WE(t),s=a.length,n=0,o;s>n;)jE.f(e,o=a[n++],r[o]);return e}});var fo=h((FC,Ip)=>{"use strict";var YE=ut();Ip.exports=YE("document","documentElement")});var So=h((qC,Lp)=>{"use strict";var zE=et(),KE=Tp(),Ep=ao(),XE=Xa(),JE=fo(),ZE=Qa(),ex=za(),xp=">",Pp="<",go="prototype",vo="script",kp=ex("IE_PROTO"),bo=function(){},Ap=function(i){return Pp+vo+xp+i+Pp+"/"+vo+xp},wp=function(i){i.write(Ap("")),i.close();var e=i.parentWindow.Object;return i=null,e},tx=function(){var i=ZE("iframe"),e="java"+vo+":",t;return i.style.display="none",JE.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Ap("document.F=Object")),t.close(),t.F},es,ts=function(){try{es=new ActiveXObject("htmlfile")}catch{}ts=typeof document<"u"?document.domain&&es?wp(es):tx():wp(es);for(var i=Ep.length;i--;)delete ts[go][Ep[i]];return ts()};XE[kp]=!0;Lp.exports=Object.create||function(e,t){var r;return e!==null?(bo[go]=zE(e),r=new bo,bo[go]=null,r[kp]=e):r=ts(),t===void 0?r:KE.f(r,t)}});var wr=h((UC,Rp)=>{"use strict";var rx=Tr();Rp.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:rx(i,e,t),i}});var Eo=h((HC,Dp)=>{"use strict";var ix=re(),ax=W(),sx=Pe(),nx=So(),$p=Ka(),ox=wr(),ux=ie(),lx=Ue(),Io=ux("iterator"),Mp=!1,lt,yo,To;[].keys&&(To=[].keys(),"next"in To?(yo=$p($p(To)),yo!==Object.prototype&&(lt=yo)):Mp=!0);var cx=!sx(lt)||ix(function(){var i={};return lt[Io].call(i)!==i});cx?lt={}:lx&&(lt=nx(lt));ax(lt[Io])||ox(lt,Io,function(){return this});Dp.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Mp}});var rs=h((jC,Vp)=>{"use strict";var dx=ie(),px=dx("toStringTag"),Cp={};Cp[px]="z";Vp.exports=String(Cp)==="[object z]"});var di=h((QC,Bp)=>{"use strict";var hx=rs(),mx=W(),is=Ut(),fx=ie(),bx=fx("toStringTag"),gx=Object,vx=is(function(){return arguments}())==="Arguments",Sx=function(i,e){try{return i[e]}catch{}};Bp.exports=hx?is:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Sx(e=gx(i),bx))=="string"?t:vx?is(e):(r=is(e))==="Object"&&mx(e.callee)?"Arguments":r}});var _p=h((GC,Op)=>{"use strict";var yx=rs(),Tx=di();Op.exports=yx?{}.toString:function(){return"[object "+Tx(this)+"]"}});var pi=h((WC,Fp)=>{"use strict";var Ix=rs(),Ex=Qt().f,xx=Tr(),Px=He(),wx=_p(),kx=ie(),Np=kx("toStringTag");Fp.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(Px(a,Np)||Ex(a,Np,{configurable:!0,value:e}),r&&!Ix&&xx(a,"toString",wx))}});var Up=h((YC,qp)=>{"use strict";var Ax=Eo().IteratorPrototype,Lx=So(),Rx=ti(),$x=pi(),Mx=Gt(),Dx=function(){return this};qp.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=Lx(Ax,{next:Rx(+!r,t)}),$x(i,a,!1,!0),Mx[a]=Dx,i}});var jp=h((zC,Hp)=>{"use strict";var Cx=J(),Vx=Ze();Hp.exports=function(i,e,t){try{return Cx(Vx(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Gp=h((KC,Qp)=>{"use strict";var Bx=Pe();Qp.exports=function(i){return Bx(i)||i===null}});var Yp=h((XC,Wp)=>{"use strict";var Ox=Gp(),_x=String,Nx=TypeError;Wp.exports=function(i){if(Ox(i))return i;throw new Nx("Can't set "+_x(i)+" as a prototype")}});var xo=h((JC,zp)=>{"use strict";var Fx=jp(),qx=Pe(),Ux=Tt(),Hx=Yp();zp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=Fx(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return Ux(a),Hx(s),qx(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var nh=h((ZC,sh)=>{"use strict";var jx=K(),Qx=xe(),as=Ue(),ih=mo(),Gx=W(),Wx=Up(),Kp=Ka(),Xp=xo(),Yx=pi(),zx=Tr(),Po=wr(),Kx=ie(),Jp=Gt(),ah=Eo(),Xx=ih.PROPER,Jx=ih.CONFIGURABLE,Zp=ah.IteratorPrototype,ss=ah.BUGGY_SAFARI_ITERATORS,hi=Kx("iterator"),eh="keys",mi="values",th="entries",rh=function(){return this};sh.exports=function(i,e,t,r,a,s,n){Wx(t,e,r);var o=function(v){if(v===a&&p)return p;if(!ss&&v&&v in d)return d[v];switch(v){case eh:return function(){return new t(this,v)};case mi:return function(){return new t(this,v)};case th:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=i.prototype,c=d[hi]||d["@@iterator"]||a&&d[a],p=!ss&&c||o(a),m=e==="Array"&&d.entries||c,f,b,g;if(m&&(f=Kp(m.call(new i)),f!==Object.prototype&&f.next&&(!as&&Kp(f)!==Zp&&(Xp?Xp(f,Zp):Gx(f[hi])||Po(f,hi,rh)),Yx(f,u,!0,!0),as&&(Jp[u]=rh))),Xx&&a===mi&&c&&c.name!==mi&&(!as&&Jx?zx(d,"name",mi):(l=!0,p=function(){return Qx(c,this)})),a)if(b={values:o(mi),keys:s?p:o(eh),entries:o(th)},n)for(g in b)(ss||l||!(g in d))&&Po(d,g,b[g]);else jx({target:e,proto:!0,forced:ss||l},b);return(!as||n)&&d[hi]!==p&&Po(d,hi,p,{name:a}),Jp[e]=p,b}});var uh=h((eV,oh)=>{"use strict";oh.exports=function(i,e){return{value:i,done:e}}});var ko=h((tV,hh)=>{"use strict";var Zx=Ht(),wo=li(),lh=Gt(),dh=co(),eP=Qt().f,tP=nh(),ns=uh(),rP=Ue(),iP=Ee(),ph="Array Iterator",aP=dh.set,sP=dh.getterFor(ph);hh.exports=tP(Array,"Array",function(i,e){aP(this,{type:ph,target:Zx(i),index:0,kind:e})},function(){var i=sP(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,ns(void 0,!0);switch(i.kind){case"keys":return ns(t,!1);case"values":return ns(e[t],!1)}return ns([t,e[t]],!1)},"values");var ch=lh.Arguments=lh.Array;wo("keys");wo("values");wo("entries");if(!rP&&iP&&ch.name!=="values")try{eP(ch,"name",{value:"values"})}catch{}});var fh=h((rV,mh)=>{"use strict";var nP=ie(),oP=Gt(),uP=nP("iterator"),lP=Array.prototype;mh.exports=function(i){return i!==void 0&&(oP.Array===i||lP[uP]===i)}});var Ao=h((iV,gh)=>{"use strict";var cP=di(),bh=ai(),dP=br(),pP=Gt(),hP=ie(),mP=hP("iterator");gh.exports=function(i){if(!dP(i))return bh(i,mP)||bh(i,"@@iterator")||pP[cP(i)]}});var Sh=h((aV,vh)=>{"use strict";var fP=xe(),bP=Ze(),gP=et(),vP=ii(),SP=Ao(),yP=TypeError;vh.exports=function(i,e){var t=arguments.length<2?SP(i):e;if(bP(t))return gP(fP(t,i));throw new yP(vP(i)+" is not iterable")}});var Ih=h((sV,Th)=>{"use strict";var TP=xe(),yh=et(),IP=ai();Th.exports=function(i,e,t){var r,a;yh(i);try{if(r=IP(i,"return"),!r){if(e==="throw")throw t;return t}r=TP(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return yh(r),t}});var us=h((nV,wh)=>{"use strict";var EP=yr(),xP=xe(),PP=et(),wP=ii(),kP=fh(),AP=xr(),Eh=ri(),LP=Sh(),RP=Ao(),xh=Ih(),$P=TypeError,os=function(i,e){this.stopped=i,this.result=e},Ph=os.prototype;wh.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=EP(e,r),l,d,c,p,m,f,b,g=function(w){return l&&xh(l,"normal",w),new os(!0,w)},v=function(w){return a?(PP(w),o?u(w[0],w[1],g):u(w[0],w[1])):o?u(w,g):u(w)};if(s)l=i.iterator;else if(n)l=i;else{if(d=RP(i),!d)throw new $P(wP(i)+" is not iterable");if(kP(d)){for(c=0,p=AP(i);p>c;c++)if(m=v(i[c]),m&&Eh(Ph,m))return m;return new os(!1)}l=LP(i,d)}for(f=s?i.next:l.next;!(b=xP(f,l)).done;){try{m=v(b.value)}catch(w){xh(l,"throw",w)}if(typeof m=="object"&&m&&Eh(Ph,m))return m}return new os(!1)}});var Ah=h((oV,kh)=>{"use strict";var MP=Ee(),DP=Qt(),CP=ti();kh.exports=function(i,e,t){MP?DP.f(i,e,CP(0,t)):i[e]=t}});var Lh=h(()=>{"use strict";var VP=K(),BP=us(),OP=Ah();VP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return BP(e,function(r,a){OP(t,r,a)},{AS_ENTRIES:!0}),t}})});var $h=h((cV,Rh)=>{"use strict";ko();Lh();var _P=gr();Rh.exports=_P.Object.fromEntries});var Dh=h((dV,Mh)=>{"use strict";Mh.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 Vh=h(()=>{"use strict";ko();var NP=Dh(),FP=Y(),qP=pi(),Ch=Gt();for(ls in NP)qP(FP[ls],ls),Ch[ls]=Ch.Array;var ls});var Oh=h((mV,Bh)=>{"use strict";var UP=$h();Vh();Bh.exports=UP});var Lo=h((fV,_h)=>{"use strict";var HP=Oh();_h.exports=HP});var Nh=h(()=>{"use strict"});var Ro=h((vV,Fh)=>{"use strict";var fi=Y(),jP=jt(),QP=Ut(),cs=function(i){return jP.slice(0,i.length)===i};Fh.exports=function(){return cs("Bun/")?"BUN":cs("Cloudflare-Workers")?"CLOUDFLARE":cs("Deno/")?"DENO":cs("Node.js/")?"NODE":fi.Bun&&typeof Bun.version=="string"?"BUN":fi.Deno&&typeof Deno.version=="object"?"DENO":QP(fi.process)==="process"?"NODE":fi.window&&fi.document?"BROWSER":"REST"}()});var ds=h((SV,qh)=>{"use strict";var GP=Ro();qh.exports=GP==="NODE"});var Hh=h((yV,Uh)=>{"use strict";var WP=Qt();Uh.exports=function(i,e,t){return WP.f(i,e,t)}});var Gh=h((TV,Qh)=>{"use strict";var YP=ut(),zP=Hh(),KP=ie(),XP=Ee(),jh=KP("species");Qh.exports=function(i){var e=YP(i);XP&&e&&!e[jh]&&zP(e,jh,{configurable:!0,get:function(){return this}})}});var Yh=h((IV,Wh)=>{"use strict";var JP=ri(),ZP=TypeError;Wh.exports=function(i,e){if(JP(e,i))return i;throw new ZP("Incorrect invocation")}});var Mo=h((EV,zh)=>{"use strict";var ew=J(),tw=W(),$o=si(),rw=ew(Function.toString);tw($o.inspectSource)||($o.inspectSource=function(i){return rw(i)});zh.exports=$o.inspectSource});var Co=h((xV,em)=>{"use strict";var iw=J(),aw=re(),Kh=W(),sw=di(),nw=ut(),ow=Mo(),Xh=function(){},Jh=nw("Reflect","construct"),Do=/^\s*(?:class|function)\b/,uw=iw(Do.exec),lw=!Do.test(Xh),bi=function(e){if(!Kh(e))return!1;try{return Jh(Xh,[],e),!0}catch{return!1}},Zh=function(e){if(!Kh(e))return!1;switch(sw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return lw||!!uw(Do,ow(e))}catch{return!0}};Zh.sham=!0;em.exports=!Jh||aw(function(){var i;return bi(bi.call)||!bi(Object)||!bi(function(){i=!0})||i})?Zh:bi});var rm=h((PV,tm)=>{"use strict";var cw=Co(),dw=ii(),pw=TypeError;tm.exports=function(i){if(cw(i))return i;throw new pw(dw(i)+" is not a constructor")}});var Vo=h((wV,am)=>{"use strict";var im=et(),hw=rm(),mw=br(),fw=ie(),bw=fw("species");am.exports=function(i,e){var t=im(i).constructor,r;return t===void 0||mw(r=im(t)[bw])?e:hw(r)}});var nm=h((kV,sm)=>{"use strict";var gw=J();sm.exports=gw([].slice)});var um=h((AV,om)=>{"use strict";var vw=TypeError;om.exports=function(i,e){if(i<e)throw new vw("Not enough arguments");return i}});var Bo=h((LV,lm)=>{"use strict";var Sw=jt();lm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Sw)});var Qo=h((RV,vm)=>{"use strict";var we=Y(),yw=xn(),Tw=yr(),cm=W(),Iw=He(),gm=re(),dm=fo(),Ew=nm(),pm=Qa(),xw=um(),Pw=Bo(),ww=ds(),Uo=we.setImmediate,Ho=we.clearImmediate,kw=we.process,Oo=we.Dispatch,Aw=we.Function,hm=we.MessageChannel,Lw=we.String,_o=0,gi={},mm="onreadystatechange",vi,Yt,No,Fo;gm(function(){vi=we.location});var jo=function(i){if(Iw(gi,i)){var e=gi[i];delete gi[i],e()}},qo=function(i){return function(){jo(i)}},fm=function(i){jo(i.data)},bm=function(i){we.postMessage(Lw(i),vi.protocol+"//"+vi.host)};(!Uo||!Ho)&&(Uo=function(e){xw(arguments.length,1);var t=cm(e)?e:Aw(e),r=Ew(arguments,1);return gi[++_o]=function(){yw(t,void 0,r)},Yt(_o),_o},Ho=function(e){delete gi[e]},ww?Yt=function(i){kw.nextTick(qo(i))}:Oo&&Oo.now?Yt=function(i){Oo.now(qo(i))}:hm&&!Pw?(No=new hm,Fo=No.port2,No.port1.onmessage=fm,Yt=Tw(Fo.postMessage,Fo)):we.addEventListener&&cm(we.postMessage)&&!we.importScripts&&vi&&vi.protocol!=="file:"&&!gm(bm)?(Yt=bm,we.addEventListener("message",fm,!1)):mm in pm("script")?Yt=function(i){dm.appendChild(pm("script"))[mm]=function(){dm.removeChild(this),jo(i)}}:Yt=function(i){setTimeout(qo(i),0)});vm.exports={set:Uo,clear:Ho}});var Tm=h(($V,ym)=>{"use strict";var Sm=Y(),Rw=Ee(),$w=Object.getOwnPropertyDescriptor;ym.exports=function(i){if(!Rw)return Sm[i];var e=$w(Sm,i);return e&&e.value}});var Go=h((MV,Em)=>{"use strict";var Im=function(){this.head=null,this.tail=null};Im.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}}};Em.exports=Im});var Pm=h((DV,xm)=>{"use strict";var Mw=jt();xm.exports=/ipad|iphone|ipod/i.test(Mw)&&typeof Pebble<"u"});var km=h((CV,wm)=>{"use strict";var Dw=jt();wm.exports=/web0s(?!.*chrome)/i.test(Dw)});var Cm=h((VV,Dm)=>{"use strict";var Ar=Y(),Cw=Tm(),Am=yr(),Wo=Qo().set,Vw=Go(),Bw=Bo(),Ow=Pm(),_w=km(),Yo=ds(),Lm=Ar.MutationObserver||Ar.WebKitMutationObserver,Rm=Ar.document,$m=Ar.process,ps=Ar.Promise,Xo=Cw("queueMicrotask"),kr,zo,Ko,hs,Mm;Xo||(Si=new Vw,yi=function(){var i,e;for(Yo&&(i=$m.domain)&&i.exit();e=Si.get();)try{e()}catch(t){throw Si.head&&kr(),t}i&&i.enter()},!Bw&&!Yo&&!_w&&Lm&&Rm?(zo=!0,Ko=Rm.createTextNode(""),new Lm(yi).observe(Ko,{characterData:!0}),kr=function(){Ko.data=zo=!zo}):!Ow&&ps&&ps.resolve?(hs=ps.resolve(void 0),hs.constructor=ps,Mm=Am(hs.then,hs),kr=function(){Mm(yi)}):Yo?kr=function(){$m.nextTick(yi)}:(Wo=Am(Wo,Ar),kr=function(){Wo(yi)}),Xo=function(i){Si.head||kr(),Si.add(i)});var Si,yi;Dm.exports=Xo});var Bm=h((BV,Vm)=>{"use strict";Vm.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var ms=h((OV,Om)=>{"use strict";Om.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var zt=h((_V,_m)=>{"use strict";var Nw=Y();_m.exports=Nw.Promise});var Lr=h((NV,Um)=>{"use strict";var Fw=Y(),Ti=zt(),qw=W(),Uw=Gn(),Hw=Mo(),jw=ie(),Nm=Ro(),Qw=Ue(),Jo=Dn(),Fm=Ti&&Ti.prototype,Gw=jw("species"),Zo=!1,qm=qw(Fw.PromiseRejectionEvent),Ww=Uw("Promise",function(){var i=Hw(Ti),e=i!==String(Ti);if(!e&&Jo===66||Qw&&!(Fm.catch&&Fm.finally))return!0;if(!Jo||Jo<51||!/native code/.test(i)){var t=new Ti(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Gw]=r,Zo=t.then(function(){})instanceof r,!Zo)return!0}return!e&&(Nm==="BROWSER"||Nm==="DENO")&&!qm});Um.exports={CONSTRUCTOR:Ww,REJECTION_EVENT:qm,SUBCLASSING:Zo}});var Rr=h((FV,jm)=>{"use strict";var Hm=Ze(),Yw=TypeError,zw=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new Yw("Bad Promise constructor");e=r,t=a}),this.resolve=Hm(e),this.reject=Hm(t)};jm.exports.f=function(i){return new zw(i)}});var cf=h(()=>{"use strict";var Kw=K(),Xw=Ue(),vs=ds(),Et=Y(),Cr=xe(),Qm=wr(),Gm=xo(),Jw=pi(),Zw=Gh(),ek=Ze(),gs=W(),tk=Pe(),rk=Yh(),ik=Vo(),Xm=Qo().set,au=Cm(),ak=Bm(),sk=ms(),nk=Go(),Jm=co(),Ss=zt(),su=Lr(),Zm=Rr(),ys="Promise",ef=su.CONSTRUCTOR,ok=su.REJECTION_EVENT,uk=su.SUBCLASSING,eu=Jm.getterFor(ys),lk=Jm.set,$r=Ss&&Ss.prototype,Kt=Ss,fs=$r,tf=Et.TypeError,tu=Et.document,nu=Et.process,ru=Zm.f,ck=ru,dk=!!(tu&&tu.createEvent&&Et.dispatchEvent),rf="unhandledrejection",pk="rejectionhandled",Wm=0,af=1,hk=2,ou=1,sf=2,bs,Ym,mk,zm,nf=function(i){var e;return tk(i)&&gs(e=i.then)?e:!1},of=function(i,e){var t=e.value,r=e.state===af,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,d;try{a?(r||(e.rejection===sf&&bk(e),e.rejection=ou),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),d=!0)),u===i.promise?n(new tf("Promise-chain cycle")):(l=nf(u))?Cr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},uf=function(i,e){i.notified||(i.notified=!0,au(function(){for(var t=i.reactions,r;r=t.get();)of(r,i);i.notified=!1,e&&!i.rejection&&fk(i)}))},lf=function(i,e,t){var r,a;dk?(r=tu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Et.dispatchEvent(r)):r={promise:e,reason:t},!ok&&(a=Et["on"+i])?a(r):i===rf&&ak("Unhandled promise rejection",t)},fk=function(i){Cr(Xm,Et,function(){var e=i.facade,t=i.value,r=Km(i),a;if(r&&(a=sk(function(){vs?nu.emit("unhandledRejection",t,e):lf(rf,e,t)}),i.rejection=vs||Km(i)?sf:ou,a.error))throw a.value})},Km=function(i){return i.rejection!==ou&&!i.parent},bk=function(i){Cr(Xm,Et,function(){var e=i.facade;vs?nu.emit("rejectionHandled",e):lf(pk,e,i.value)})},Mr=function(i,e,t){return function(r){i(e,r,t)}},Dr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=hk,uf(i,!0))},iu=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new tf("Promise can't be resolved itself");var r=nf(e);r?au(function(){var a={done:!1};try{Cr(r,e,Mr(iu,a,i),Mr(Dr,a,i))}catch(s){Dr(a,s,i)}}):(i.value=e,i.state=af,uf(i,!1))}catch(a){Dr({done:!1},a,i)}}};if(ef&&(Kt=function(e){rk(this,fs),ek(e),Cr(bs,this);var t=eu(this);try{e(Mr(iu,t),Mr(Dr,t))}catch(r){Dr(t,r)}},fs=Kt.prototype,bs=function(e){lk(this,{type:ys,done:!1,notified:!1,parent:!1,reactions:new nk,rejection:!1,state:Wm,value:void 0})},bs.prototype=Qm(fs,"then",function(e,t){var r=eu(this),a=ru(ik(this,Kt));return r.parent=!0,a.ok=gs(e)?e:!0,a.fail=gs(t)&&t,a.domain=vs?nu.domain:void 0,r.state===Wm?r.reactions.add(a):au(function(){of(a,r)}),a.promise}),Ym=function(){var i=new bs,e=eu(i);this.promise=i,this.resolve=Mr(iu,e),this.reject=Mr(Dr,e)},Zm.f=ru=function(i){return i===Kt||i===mk?new Ym(i):ck(i)},!Xw&&gs(Ss)&&$r!==Object.prototype)){zm=$r.then,uk||Qm($r,"then",function(e,t){var r=this;return new Kt(function(a,s){Cr(zm,r,a,s)}).then(e,t)},{unsafe:!0});try{delete $r.constructor}catch{}Gm&&Gm($r,fs)}Kw({global:!0,constructor:!0,wrap:!0,forced:ef},{Promise:Kt});Jw(Kt,ys,!1,!0);Zw(ys)});var ff=h((HV,mf)=>{"use strict";var gk=ie(),pf=gk("iterator"),hf=!1;try{df=0,uu={next:function(){return{done:!!df++}},return:function(){hf=!0}},uu[pf]=function(){return this},Array.from(uu,function(){throw 2})}catch{}var df,uu;mf.exports=function(i,e){try{if(!e&&!hf)return!1}catch{return!1}var t=!1;try{var r={};r[pf]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var lu=h((jV,bf)=>{"use strict";var vk=zt(),Sk=ff(),yk=Lr().CONSTRUCTOR;bf.exports=yk||!Sk(function(i){vk.all(i).then(void 0,function(){})})});var gf=h(()=>{"use strict";var Tk=K(),Ik=xe(),Ek=Ze(),xk=Rr(),Pk=ms(),wk=us(),kk=lu();Tk({target:"Promise",stat:!0,forced:kk},{all:function(e){var t=this,r=xk.f(t),a=r.resolve,s=r.reject,n=Pk(function(){var o=Ek(t.resolve),u=[],l=0,d=1;wk(e,function(c){var p=l++,m=!1;d++,Ik(o,t,c).then(function(f){m||(m=!0,u[p]=f,--d||a(u))},s)}),--d||a(u)});return n.error&&s(n.value),r.promise}})});var Sf=h(()=>{"use strict";var Ak=K(),Lk=Ue(),Rk=Lr().CONSTRUCTOR,du=zt(),$k=ut(),Mk=W(),Dk=wr(),vf=du&&du.prototype;Ak({target:"Promise",proto:!0,forced:Rk,real:!0},{catch:function(i){return this.then(void 0,i)}});!Lk&&Mk(du)&&(cu=$k("Promise").prototype.catch,vf.catch!==cu&&Dk(vf,"catch",cu,{unsafe:!0}));var cu});var yf=h(()=>{"use strict";var Ck=K(),Vk=xe(),Bk=Ze(),Ok=Rr(),_k=ms(),Nk=us(),Fk=lu();Ck({target:"Promise",stat:!0,forced:Fk},{race:function(e){var t=this,r=Ok.f(t),a=r.reject,s=_k(function(){var n=Bk(t.resolve);Nk(e,function(o){Vk(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Tf=h(()=>{"use strict";var qk=K(),Uk=Rr(),Hk=Lr().CONSTRUCTOR;qk({target:"Promise",stat:!0,forced:Hk},{reject:function(e){var t=Uk.f(this),r=t.reject;return r(e),t.promise}})});var pu=h((ZV,If)=>{"use strict";var jk=et(),Qk=Pe(),Gk=Rr();If.exports=function(i,e){if(jk(i),Qk(e)&&e.constructor===i)return e;var t=Gk.f(i),r=t.resolve;return r(e),t.promise}});var Pf=h(()=>{"use strict";var Wk=K(),Yk=ut(),Ef=Ue(),zk=zt(),xf=Lr().CONSTRUCTOR,Kk=pu(),Xk=Yk("Promise"),Jk=Ef&&!xf;Wk({target:"Promise",stat:!0,forced:Ef||xf},{resolve:function(e){return Kk(Jk&&this===Xk?zk:this,e)}})});var wf=h(()=>{"use strict";cf();gf();Sf();yf();Tf();Pf()});var Rf=h(()=>{"use strict";var Zk=K(),eA=Ue(),Ts=zt(),tA=re(),Af=ut(),Lf=W(),rA=Vo(),kf=pu(),iA=wr(),mu=Ts&&Ts.prototype,aA=!!Ts&&tA(function(){mu.finally.call({then:function(){}},function(){})});Zk({target:"Promise",proto:!0,real:!0,forced:aA},{finally:function(i){var e=rA(this,Af("Promise")),t=Lf(i);return this.then(t?function(r){return kf(e,i()).then(function(){return r})}:i,t?function(r){return kf(e,i()).then(function(){throw r})}:i)}});!eA&&Lf(Ts)&&(hu=Af("Promise").prototype.finally,mu.finally!==hu&&iA(mu,"finally",hu,{unsafe:!0}));var hu});var Mf=h((nB,$f)=>{"use strict";Nh();wf();Rf();var sA=It();$f.exports=sA("Promise","finally")});var Cf=h((oB,Df)=>{"use strict";var nA=Mf();Df.exports=nA});var Is=h((uB,Vf)=>{"use strict";var oA=Cf();Vf.exports=oA});var Yf=h(()=>{"use strict";var TA=K(),IA=no().values;TA({target:"Object",stat:!0},{values:function(e){return IA(e)}})});var Kf=h((GB,zf)=>{"use strict";Yf();var EA=gr();zf.exports=EA.Object.values});var Jf=h((WB,Xf)=>{"use strict";var xA=Kf();Xf.exports=xA});var Br=h((YB,Zf)=>{"use strict";var PA=Jf();Zf.exports=PA});var pb=h(()=>{"use strict";var qA=K(),UA=vr(),HA=xr(),jA=ui(),QA=li();qA({target:"Array",proto:!0},{at:function(e){var t=UA(this),r=HA(t),a=jA(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});QA("at")});var mb=h((IO,hb)=>{"use strict";pb();var GA=It();hb.exports=GA("Array","at")});var bb=h((EO,fb)=>{"use strict";var WA=mb();fb.exports=WA});var Zt=h((xO,gb)=>{"use strict";var YA=bb();gb.exports=YA});var _u=h((aN,Kb)=>{"use strict";var DL=Ut();Kb.exports=Array.isArray||function(e){return DL(e)==="Array"}});var Jb=h((sN,Xb)=>{"use strict";var CL=TypeError,VL=9007199254740991;Xb.exports=function(i){if(i>VL)throw CL("Maximum allowed index exceeded");return i}});var tg=h((nN,eg)=>{"use strict";var BL=_u(),OL=xr(),_L=Jb(),NL=yr(),Zb=function(i,e,t,r,a,s,n,o){for(var u=a,l=0,d=n?NL(n,o):!1,c,p;l<r;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&BL(c)?(p=OL(c),u=Zb(i,e,c,p,u,s-1)-1):(_L(u+1),i[u]=c),u++),l++;return u};eg.exports=Zb});var sg=h((oN,ag)=>{"use strict";var rg=_u(),FL=Co(),qL=Pe(),UL=ie(),HL=UL("species"),ig=Array;ag.exports=function(i){var e;return rg(i)&&(e=i.constructor,FL(e)&&(e===ig||rg(e.prototype))?e=void 0:qL(e)&&(e=e[HL],e===null&&(e=void 0))),e===void 0?ig:e}});var og=h((uN,ng)=>{"use strict";var jL=sg();ng.exports=function(i,e){return new(jL(i))(e===0?0:e)}});var ug=h(()=>{"use strict";var QL=K(),GL=tg(),WL=Ze(),YL=vr(),zL=xr(),KL=og();QL({target:"Array",proto:!0},{flatMap:function(e){var t=YL(this),r=zL(t),a;return WL(e),a=KL(t,0),a.length=GL(a,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var lg=h(()=>{"use strict";var XL=li();XL("flatMap")});var dg=h((hN,cg)=>{"use strict";ug();lg();var JL=It();cg.exports=JL("Array","flatMap")});var hg=h((mN,pg)=>{"use strict";var ZL=dg();pg.exports=ZL});var Nu=h((fN,mg)=>{"use strict";var eR=hg();mg.exports=eR});var Bi=h((PN,xg)=>{"use strict";var uR=di(),lR=String;xg.exports=function(i){if(uR(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return lR(i)}});var qu=h((wN,Pg)=>{"use strict";Pg.exports=`
|
|
7
|
-
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Ag=h((kN,kg)=>{"use strict";var cR=J(),dR=Tt(),pR=Bi(),Hu=qu(),wg=cR("".replace),hR=RegExp("^["+Hu+"]+"),mR=RegExp("(^|[^"+Hu+"])["+Hu+"]+$"),Uu=function(i){return function(e){var t=pR(dR(e));return i&1&&(t=wg(t,hR,"")),i&2&&(t=wg(t,mR,"$1")),t}};kg.exports={start:Uu(1),end:Uu(2),trim:Uu(3)}});var Mg=h((AN,$g)=>{"use strict";var fR=mo().PROPER,bR=re(),Lg=qu(),Rg="\u200B\x85\u180E";$g.exports=function(i){return bR(function(){return!!Lg[i]()||Rg[i]()!==Rg||fR&&Lg[i].name!==i})}});var ju=h((LN,Dg)=>{"use strict";var gR=Ag().start,vR=Mg();Dg.exports=vR("trimStart")?function(){return gR(this)}:"".trimStart});var Vg=h(()=>{"use strict";var SR=K(),Cg=ju();SR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Cg},{trimLeft:Cg})});var Og=h(()=>{"use strict";Vg();var yR=K(),Bg=ju();yR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Bg},{trimStart:Bg})});var Ng=h((CN,_g)=>{"use strict";Og();var TR=It();_g.exports=TR("String","trimLeft")});var qg=h((VN,Fg)=>{"use strict";var IR=Ng();Fg.exports=IR});var Hg=h((BN,Ug)=>{"use strict";var ER=qg();Ug.exports=ER});var sv=h(()=>{"use strict"});var nv=h(()=>{"use strict"});var uv=h((fU,ov)=>{"use strict";var GR=Pe(),WR=Ut(),YR=ie(),zR=YR("match");ov.exports=function(i){var e;return GR(i)&&((e=i[zR])!==void 0?!!e:WR(i)==="RegExp")}});var cv=h((bU,lv)=>{"use strict";var KR=et();lv.exports=function(){var i=KR(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 hv=h((gU,pv)=>{"use strict";var XR=xe(),JR=He(),ZR=ri(),e$=cv(),dv=RegExp.prototype;pv.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in dv)&&!JR(i,"flags")&&ZR(dv,i)?XR(e$,i):e}});var fv=h((vU,mv)=>{"use strict";var Zu=J(),t$=vr(),r$=Math.floor,Xu=Zu("".charAt),i$=Zu("".replace),Ju=Zu("".slice),a$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,s$=/\$([$&'`]|\d{1,2})/g;mv.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=s$;return a!==void 0&&(a=t$(a),u=a$),i$(s,u,function(l,d){var c;switch(Xu(d,0)){case"$":return"$";case"&":return i;case"`":return Ju(e,0,t);case"'":return Ju(e,n);case"<":c=a[Ju(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var m=r$(p/10);return m===0?l:m<=o?r[m-1]===void 0?Xu(d,1):r[m-1]+Xu(d,1):l}c=r[p-1]}return c===void 0?"":c})}});var vv=h(()=>{"use strict";var n$=K(),o$=xe(),tl=J(),bv=Tt(),u$=W(),l$=br(),c$=uv(),Hr=Bi(),d$=ai(),p$=hv(),h$=fv(),m$=ie(),f$=Ue(),b$=m$("replace"),g$=TypeError,el=tl("".indexOf),v$=tl("".replace),gv=tl("".slice),S$=Math.max;n$({target:"String",proto:!0},{replaceAll:function(e,t){var r=bv(this),a,s,n,o,u,l,d,c,p,m,f=0,b="";if(!l$(e)){if(a=c$(e),a&&(s=Hr(bv(p$(e))),!~el(s,"g")))throw new g$("`.replaceAll` does not allow non-global regexes");if(n=d$(e,b$),n)return o$(n,e,r,t);if(f$&&a)return v$(Hr(r),e,t)}for(o=Hr(r),u=Hr(e),l=u$(t),l||(t=Hr(t)),d=u.length,c=S$(1,d),p=el(o,u);p!==-1;)m=l?Hr(t(u,p,o)):h$(u,o,p,[],void 0,t),b+=gv(o,f,p)+m,f=p+d,p=p+c>o.length?-1:el(o,u,p+c);return f<o.length&&(b+=gv(o,f)),b}})});var yv=h((TU,Sv)=>{"use strict";sv();nv();vv();var y$=It();Sv.exports=y$("String","replaceAll")});var Iv=h((IU,Tv)=>{"use strict";var T$=yv();Tv.exports=T$});var xv=h((EU,Ev)=>{"use strict";var I$=Iv();Ev.exports=I$});var wv=h((xU,Pv)=>{"use strict";var E$=ui(),x$=Bi(),P$=Tt(),w$=RangeError;Pv.exports=function(e){var t=x$(P$(this)),r="",a=E$(e);if(a<0||a===1/0)throw new w$("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(r+=t);return r}});var $v=h((PU,Rv)=>{"use strict";var Lv=J(),k$=Jn(),kv=Bi(),A$=wv(),L$=Tt(),R$=Lv(A$),$$=Lv("".slice),M$=Math.ceil,Av=function(i){return function(e,t,r){var a=kv(L$(e)),s=k$(t),n=a.length,o=r===void 0?" ":kv(r),u,l;return s<=n||o===""?a:(u=s-n,l=R$(o,M$(u/o.length)),l.length>u&&(l=$$(l,0,u)),i?a+l:l+a)}};Rv.exports={start:Av(!1),end:Av(!0)}});var Dv=h((wU,Mv)=>{"use strict";var D$=jt();Mv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(D$)});var Cv=h(()=>{"use strict";var C$=K(),V$=$v().start,B$=Dv();C$({target:"String",proto:!0,forced:B$},{padStart:function(e){return V$(this,e,arguments.length>1?arguments[1]:void 0)}})});var Bv=h((LU,Vv)=>{"use strict";Cv();var O$=It();Vv.exports=O$("String","padStart")});var _v=h((RU,Ov)=>{"use strict";var _$=Bv();Ov.exports=_$});var Fv=h(($U,Nv)=>{"use strict";var N$=_v();Nv.exports=N$});var Hl="2.0.124-dev.594551f7.0";var he=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(he||{}),yt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(yt||{});var qa=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(qa||{}),Tn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Tn||{});var In=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(In||{}),Ua=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(Ua||{});var by=D(je(),1);import{assertNever as qd,assertNonNullable as YI,isNonNullable as Wa,ValueSubject as eo,Subject as zI,Subscription as KI,merge as XI,observableFrom as JI,fromEvent as Od,map as _d,tap as Nd,filterChanged as ZI,isNullable as to,ErrorCategory as Fd}from"@vkontakte/videoplayer-shared";var Bd=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e(),r.onerror=a=>t(a),document.body.appendChild(r)});var Ya=class{constructor(e){this.connection$=new eo(void 0);this.castState$=new eo("NOT_AVAILABLE");this.errorEvent$=new zI;this.realCastState$=new eo("NOT_AVAILABLE");this.subscription=new KI;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Wa(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},a||Bd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Fd.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(){Wa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();to(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();to(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Od(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 qd(a.sessionState)}})).add(XI(Od(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Nd(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),_d(a=>a.castState)),JI([r.getCastState()])).pipe(ZI(),_d(eE),Nd(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Wa(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();YI(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(to(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"?Wa(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:Fd.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},eE=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 qd(i)}};var Cl=D(je(),1),XS=D(Pr(),1),JS=D(Lo(),1);var Qf=D(Is(),1);import{assertNever as Bf}from"@vkontakte/videoplayer-shared";var ae=(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:Bf(t)}return i},Es=(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:Bf(e)}};var T=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as uA,Subject as xs,merge as Of}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new xs;this.transitionEnded$=new xs;this.transitionUpdated$=new xs;this.forceChanged$=new xs;this.stateChangeStarted$=Of(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Of(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||uA(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 lA}from"@vkontakte/videoplayer-shared";var _f=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 lA(i)}};import{assertNever as Vr,assertNonNullable as Xt,debounce as Nf,ErrorCategory as Ff,fromEvent as Jt,isNonNullable as qf,map as Uf,merge as Hf,observableFrom as cA,Subject as dA,Subscription as fu,timeout as pA,getHighestQuality as hA}from"@vkontakte/videoplayer-shared";var mA=5,fA=5,bA=500,jf=7e3,Ii=class{constructor(e){this.subscription=new fu;this.loadMediaTimeoutSubscription=new fu;this.videoState=new $("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:Vr(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:Vr(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:Vr(e)}break}default:Vr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_f(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 fu;this.subscription.add(e),this.subscription.add(Hf(this.videoState.stateChangeStarted$.pipe(Uf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Uf(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 dA;e.add(a.pipe(Nf(bA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Jt(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)>mA)&&a.next(o),s=o})),e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Jt(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<fA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(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:Vr(n)}}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Hf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cA(["init"])).pipe(Nf(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"),T(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),T(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"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&T(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];Xt(l);let d=hA(Object.keys(l));Xt(d);let c=l[d];Xt(c),r=c,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Xt(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];Xt(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Xt(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];Xt(l),r=ae(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",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ff.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Vr(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 qf(o)&&(n.metadata.title=o),qf(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(pA(jf).subscribe(()=>s(`timeout(${jf})`)))});(0,Qf.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:Ff.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Bu=D(je(),1);import{clearVideoElement as Wf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as gA}from"@vkontakte/videoplayer-shared";var Gf=i=>{try{i.pause(),i.playbackRate=0,gA(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as vA,Subscription as SA}from"@vkontakte/videoplayer-shared";var bu=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)}},gu=window.WeakMap?new WeakMap:new bu,vu=window.WeakMap?new WeakMap:new Map,yA=(i,e=20)=>{let t=0;return vA(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},me=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Wf(t):(t=document.createElement("video"),i.appendChild(t)),gu.set(t,r);let a=new SA;return a.add(yA(t,e)),vu.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.setAttribute("x-yandex-pip","false"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},fe=i=>{vu.get(i)?.unsubscribe(),vu.delete(i);let t=gu.get(i);gu.delete(i),t?Wf(i):Gf(i)};var yu=D(Br(),1);import{assertNonNullable as Ei,isNonNullable as rt,isNullable as AA,fromEvent as Or,merge as eb,observableFrom as tb,filterChanged as rb,map as xi,Subject as ib,Subscription as LA,ValueSubject as RA,ErrorCategory as $A}from"@vkontakte/videoplayer-shared";import{isNonNullable as Su,isNullable as wA,Subscription as kA}from"@vkontakte/videoplayer-shared";var Ps=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=wA(a),l=new kA;return a&&l.add(a.subscribe(d=>{let c=i.getState();r(d,c)&&i.setState(d)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),u&&i.setState(d.to)},s)),l},tt=(i,e,t)=>Ps(e,()=>i.loop,r=>{Su(r)&&(i.loop=r)},{onError:t}),be=(i,e,t,r)=>Ps(e,()=>({muted:i.muted,volume:i.volume}),a=>{Su(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}),De=(i,e,t,r)=>Ps(e,()=>i.playbackRate,a=>{Su(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),xt=Ps;var MA=i=>["__",i.language,i.label].join("|"),DA=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Tu=class i{constructor(e){this.available$=new ib;this.current$=new RA(void 0);this.error$=new ib;this.subscription=new LA;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:$A.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,yu.default)(this.internalTracks),s=>{rt(s)&&this.setInternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(xi(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(xt(t.externalTextTracks,()=>(0,yu.default)(this.externalTracks),s=>{rt(s)&&this.setExternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(xi(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(){Ei(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(eb(Or(e,"addtrack"),Or(e,"removetrack"),tb(["init"])).pipe(xi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),rb((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(eb(Or(e,"change"),tb(["init"])).pipe(xi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),xi(r=>r&&this.htmlTextTrackToITextTrack(r).id),rb()).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;rt(t.align)&&(a.align=t.align),rt(t.position)&&(a.position=t.position),rt(t.size)&&(a.size=t.size),rt(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){Ei(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:MA(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){Ei(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(AA(e)||!DA(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){Ei(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Ei(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)}},Ce=Tu;var dt=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 ab=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Iu=i=>{let e=ab(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},sb=i=>{let e=ab(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Ve,map as Pt,merge as ob,filterChanged as VA,isNonNullable as ub,Subject as BA,filter as lb,mapTo as cb,combine as OA,once as _A,ErrorCategory as NA,ValueSubject as db,clientChecker as FA}from"@vkontakte/videoplayer-shared";var CA=3,nb=(i,e,t=CA)=>{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 ge=i=>{let e=x=>Ve(i,x).pipe(cb(void 0)),r=ob(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>Ve(i,x))).pipe(Pt(x=>x.type==="ended"?i.readyState<2:i.readyState<3),VA()),a=ob(Ve(i,"progress"),Ve(i,"timeupdate")).pipe(Pt(()=>nb(i.buffered,i.currentTime))),s=FA.isSafari?OA({play:e("play").pipe(_A()),playing:e("playing")}).pipe(cb(void 0)):e("playing"),n=Ve(i,"volumechange").pipe(Pt(()=>({muted:i.muted,volume:i.volume}))),o=Ve(i,"ratechange").pipe(Pt(()=>i.playbackRate)),u=Ve(i,"error").pipe(lb(()=>!!(i.error||i.played.length)),Pt(()=>{let x=i.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:NA.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:i.error??void 0}})),l=Ve(i,"timeupdate").pipe(Pt(()=>i.currentTime)),d=new BA,c=.3,p;l.subscribe(x=>{i.loop&&ub(p)&&ub(x)&&p>=i.duration-c&&x<=c&&d.next(p),p=x});let m=e("pause").pipe(lb(()=>!i.error&&p!==i.duration)),f=Ve(i,"enterpictureinpicture"),b=Ve(i,"leavepictureinpicture"),g=new db(sb(i));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new db(Iu(i));return Ve(i,"fullscreenchange").pipe(Pt(()=>Iu(i))).subscribe(v),{playing$:s,pause$:m,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ve(i,"durationchange").pipe(Pt(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:f,leavePip$:b}};import{VideoQuality as wt}from"@vkontakte/videoplayer-shared";var kt=i=>{switch(i){case"mobile":return wt.Q_144P;case"lowest":return wt.Q_240P;case"low":return wt.Q_360P;case"sd":case"medium":return wt.Q_480P;case"hd":case"high":return wt.Q_720P;case"fullhd":case"full":return wt.Q_1080P;case"quadhd":case"quad":return wt.Q_1440P;case"ultrahd":case"ultra":return wt.Q_2160P}};var At=D(Zt(),1),kb=D(je(),1),As=D(Pr(),1);import{isNonNullable as ke,isNullable as Eb,now as Ab,isHigher as xb,isHigherOrEqual as ku,isInvariantQuality as Pb,isLowerOrEqual as Au,videoSizeToQuality as JA,assertNotEmptyArray as Lb,assertNonNullable as ZA}from"@vkontakte/videoplayer-shared";var Eu=!1,pt={},vb=i=>{Eu=i},Sb=()=>{pt={}},yb=i=>{i(pt)},Pi=(i,e)=>{Eu&&(pt.meta=pt.meta??{},pt.meta[i]=e)},le=class{constructor(e){this.name=e}next(e){if(!Eu)return;pt.series=pt.series??{};let t=pt.series[this.name]??[];t.push([Date.now(),e]),pt.series[this.name]=t}};import{isHigher as zA,isHigherOrEqual as KA,isLower as Tb,isLowerOrEqual as XA,isNonNullable as ws,isNullable as xu}from"@vkontakte/videoplayer-shared";function Pu({limits:i,highQualityLimit:e,trafficSavingLimit:t}){return!i.max&&i.min===e?"high_quality":!i.min&&i.max===t?"traffic_saving":"unknown"}function wu({limits:i,highQualityLimit:e,trafficSavingLimit:t}){return!!i&&Pu({limits:i,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function ks({limits:i,highestAvailableQuality:e,lowestAvailableQuality:t}){return xu(i)||ws(i.min)&&ws(i.max)&&Tb(i.max,i.min)||ws(i.min)&&e&&zA(i.min,e)||ws(i.max)&&t&&Tb(i.max,t)}function Ib({limits:i,track:e}){return(xu(i?.max)||XA(e.quality,i.max))&&(xu(i?.min)||KA(e.quality,i.min))}var eL=new le("best_bitrate"),Rb=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var Lu=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),wi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ab()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},$b='Assertion "ABR Tracks is empty array" failed',Ls=(i,e,t,r)=>{let a=[...e].sort(Lu(1)),s=[...t].sort(Lu(1)),n=s.filter(u=>ke(u.bitrate)&&ke(i.bitrate)?i.bitrate/u.bitrate>r:!0),o=(0,At.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,At.default)(s,-1);return o&&(0,kb.default)(n,o)?o:n.length?(0,At.default)(n,-1):(0,At.default)(s,0)},wb=i=>"quality"in i,Mb=(i,e,t,r)=>{let a=ke(r?.last?.bitrate)&&ke(t?.bitrate)&&r.last.bitrate<t.bitrate?i.trackCooldownIncreaseQuality:i.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Ab()-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=wb(n)?"video":"audio",u=wb(n)?n.quality:n.bitrate;return e({message:`
|
|
6
|
+
var Ty=Object.create;var Ul=Object.defineProperty;var Iy=Object.getOwnPropertyDescriptor;var Ey=Object.getOwnPropertyNames;var xy=Object.getPrototypeOf,Py=Object.prototype.hasOwnProperty;var h=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var ky=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ey(e))!Py.call(i,a)&&a!==t&&Ul(i,a,{get:()=>e[a],enumerable:!(r=Iy(e,a))||r.enumerable});return i};var D=(i,e,t)=>(t=i!=null?Ty(xy(i)):{},ky(e||!i||!i.__esModule?Ul(t,"default",{value:i,enumerable:!0}):t,i));var Y=h((En,jl)=>{"use strict";var Zr=function(i){return i&&i.Math===Math&&i};jl.exports=Zr(typeof globalThis=="object"&&globalThis)||Zr(typeof window=="object"&&window)||Zr(typeof self=="object"&&self)||Zr(typeof global=="object"&&global)||Zr(typeof En=="object"&&En)||function(){return this}()||Function("return this")()});var re=h((a0,Ql)=>{"use strict";Ql.exports=function(i){try{return!!i()}catch{return!0}}});var ei=h((s0,Gl)=>{"use strict";var wy=re();Gl.exports=!wy(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var xn=h((n0,Kl)=>{"use strict";var Ay=ei(),zl=Function.prototype,Wl=zl.apply,Yl=zl.call;Kl.exports=typeof Reflect=="object"&&Reflect.apply||(Ay?Yl.bind(Wl):function(){return Yl.apply(Wl,arguments)})});var J=h((o0,Zl)=>{"use strict";var Xl=ei(),Jl=Function.prototype,Pn=Jl.call,Ly=Xl&&Jl.bind.bind(Pn,Pn);Zl.exports=Xl?Ly:function(i){return function(){return Pn.apply(i,arguments)}}});var Ut=h((u0,tc)=>{"use strict";var ec=J(),Ry=ec({}.toString),$y=ec("".slice);tc.exports=function(i){return $y(Ry(i),8,-1)}});var kn=h((l0,rc)=>{"use strict";var My=Ut(),Dy=J();rc.exports=function(i){if(My(i)==="Function")return Dy(i)}});var W=h((c0,ic)=>{"use strict";var wn=typeof document=="object"&&document.all;ic.exports=typeof wn>"u"&&wn!==void 0?function(i){return typeof i=="function"||i===wn}:function(i){return typeof i=="function"}});var Ee=h((d0,ac)=>{"use strict";var Cy=re();ac.exports=!Cy(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var xe=h((p0,sc)=>{"use strict";var Vy=ei(),Ha=Function.prototype.call;sc.exports=Vy?Ha.bind(Ha):function(){return Ha.apply(Ha,arguments)}});var An=h(uc=>{"use strict";var nc={}.propertyIsEnumerable,oc=Object.getOwnPropertyDescriptor,By=oc&&!nc.call({1:2},1);uc.f=By?function(e){var t=oc(this,e);return!!t&&t.enumerable}:nc});var ti=h((m0,lc)=>{"use strict";lc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var dc=h((f0,cc)=>{"use strict";var Oy=J(),_y=re(),Ny=Ut(),Ln=Object,Fy=Oy("".split);cc.exports=_y(function(){return!Ln("z").propertyIsEnumerable(0)})?function(i){return Ny(i)==="String"?Fy(i,""):Ln(i)}:Ln});var br=h((b0,pc)=>{"use strict";pc.exports=function(i){return i==null}});var Tt=h((g0,hc)=>{"use strict";var qy=br(),Uy=TypeError;hc.exports=function(i){if(qy(i))throw new Uy("Can't call method on "+i);return i}});var Ht=h((v0,mc)=>{"use strict";var Hy=dc(),jy=Tt();mc.exports=function(i){return Hy(jy(i))}});var Pe=h((S0,fc)=>{"use strict";var Qy=W();fc.exports=function(i){return typeof i=="object"?i!==null:Qy(i)}});var gr=h((y0,bc)=>{"use strict";bc.exports={}});var ut=h((T0,vc)=>{"use strict";var Rn=gr(),$n=Y(),Gy=W(),gc=function(i){return Gy(i)?i:void 0};vc.exports=function(i,e){return arguments.length<2?gc(Rn[i])||gc($n[i]):Rn[i]&&Rn[i][e]||$n[i]&&$n[i][e]}});var ri=h((I0,Sc)=>{"use strict";var Wy=J();Sc.exports=Wy({}.isPrototypeOf)});var jt=h((E0,Ic)=>{"use strict";var Yy=Y(),yc=Yy.navigator,Tc=yc&&yc.userAgent;Ic.exports=Tc?String(Tc):""});var Dn=h((x0,Ac)=>{"use strict";var wc=Y(),Mn=jt(),Ec=wc.process,xc=wc.Deno,Pc=Ec&&Ec.versions||xc&&xc.version,kc=Pc&&Pc.v8,qe,ja;kc&&(qe=kc.split("."),ja=qe[0]>0&&qe[0]<4?1:+(qe[0]+qe[1]));!ja&&Mn&&(qe=Mn.match(/Edge\/(\d+)/),(!qe||qe[1]>=74)&&(qe=Mn.match(/Chrome\/(\d+)/),qe&&(ja=+qe[1])));Ac.exports=ja});var Cn=h((P0,Rc)=>{"use strict";var Lc=Dn(),zy=re(),Ky=Y(),Xy=Ky.String;Rc.exports=!!Object.getOwnPropertySymbols&&!zy(function(){var i=Symbol("symbol detection");return!Xy(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Lc&&Lc<41})});var Vn=h((k0,$c)=>{"use strict";var Jy=Cn();$c.exports=Jy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var Bn=h((w0,Mc)=>{"use strict";var Zy=ut(),eT=W(),tT=ri(),rT=Vn(),iT=Object;Mc.exports=rT?function(i){return typeof i=="symbol"}:function(i){var e=Zy("Symbol");return eT(e)&&tT(e.prototype,iT(i))}});var ii=h((A0,Dc)=>{"use strict";var aT=String;Dc.exports=function(i){try{return aT(i)}catch{return"Object"}}});var Ze=h((L0,Cc)=>{"use strict";var sT=W(),nT=ii(),oT=TypeError;Cc.exports=function(i){if(sT(i))return i;throw new oT(nT(i)+" is not a function")}});var ai=h((R0,Vc)=>{"use strict";var uT=Ze(),lT=br();Vc.exports=function(i,e){var t=i[e];return lT(t)?void 0:uT(t)}});var Oc=h(($0,Bc)=>{"use strict";var On=xe(),_n=W(),Nn=Pe(),cT=TypeError;Bc.exports=function(i,e){var t,r;if(e==="string"&&_n(t=i.toString)&&!Nn(r=On(t,i))||_n(t=i.valueOf)&&!Nn(r=On(t,i))||e!=="string"&&_n(t=i.toString)&&!Nn(r=On(t,i)))return r;throw new cT("Can't convert object to primitive value")}});var Ue=h((M0,_c)=>{"use strict";_c.exports=!0});var qc=h((D0,Fc)=>{"use strict";var Nc=Y(),dT=Object.defineProperty;Fc.exports=function(i,e){try{dT(Nc,i,{value:e,configurable:!0,writable:!0})}catch{Nc[i]=e}return e}});var si=h((C0,jc)=>{"use strict";var pT=Ue(),hT=Y(),mT=qc(),Uc="__core-js_shared__",Hc=jc.exports=hT[Uc]||mT(Uc,{});(Hc.versions||(Hc.versions=[])).push({version:"3.38.0",mode:pT?"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 Fn=h((V0,Gc)=>{"use strict";var Qc=si();Gc.exports=function(i,e){return Qc[i]||(Qc[i]=e||{})}});var vr=h((B0,Wc)=>{"use strict";var fT=Tt(),bT=Object;Wc.exports=function(i){return bT(fT(i))}});var He=h((O0,Yc)=>{"use strict";var gT=J(),vT=vr(),ST=gT({}.hasOwnProperty);Yc.exports=Object.hasOwn||function(e,t){return ST(vT(e),t)}});var qn=h((_0,zc)=>{"use strict";var yT=J(),TT=0,IT=Math.random(),ET=yT(1 .toString);zc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+ET(++TT+IT,36)}});var ie=h((N0,Xc)=>{"use strict";var xT=Y(),PT=Fn(),Kc=He(),kT=qn(),wT=Cn(),AT=Vn(),Sr=xT.Symbol,Un=PT("wks"),LT=AT?Sr.for||Sr:Sr&&Sr.withoutSetter||kT;Xc.exports=function(i){return Kc(Un,i)||(Un[i]=wT&&Kc(Sr,i)?Sr[i]:LT("Symbol."+i)),Un[i]}});var td=h((F0,ed)=>{"use strict";var RT=xe(),Jc=Pe(),Zc=Bn(),$T=ai(),MT=Oc(),DT=ie(),CT=TypeError,VT=DT("toPrimitive");ed.exports=function(i,e){if(!Jc(i)||Zc(i))return i;var t=$T(i,VT),r;if(t){if(e===void 0&&(e="default"),r=RT(t,i,e),!Jc(r)||Zc(r))return r;throw new CT("Can't convert object to primitive value")}return e===void 0&&(e="number"),MT(i,e)}});var Hn=h((q0,rd)=>{"use strict";var BT=td(),OT=Bn();rd.exports=function(i){var e=BT(i,"string");return OT(e)?e:e+""}});var Qa=h((U0,ad)=>{"use strict";var _T=Y(),id=Pe(),jn=_T.document,NT=id(jn)&&id(jn.createElement);ad.exports=function(i){return NT?jn.createElement(i):{}}});var Qn=h((H0,sd)=>{"use strict";var FT=Ee(),qT=re(),UT=Qa();sd.exports=!FT&&!qT(function(){return Object.defineProperty(UT("div"),"a",{get:function(){return 7}}).a!==7})});var ud=h(od=>{"use strict";var HT=Ee(),jT=xe(),QT=An(),GT=ti(),WT=Ht(),YT=Hn(),zT=He(),KT=Qn(),nd=Object.getOwnPropertyDescriptor;od.f=HT?nd:function(e,t){if(e=WT(e),t=YT(t),KT)try{return nd(e,t)}catch{}if(zT(e,t))return GT(!jT(QT.f,e,t),e[t])}});var Gn=h((Q0,ld)=>{"use strict";var XT=re(),JT=W(),ZT=/#|\.prototype\./,ni=function(i,e){var t=tI[eI(i)];return t===iI?!0:t===rI?!1:JT(e)?XT(e):!!e},eI=ni.normalize=function(i){return String(i).replace(ZT,".").toLowerCase()},tI=ni.data={},rI=ni.NATIVE="N",iI=ni.POLYFILL="P";ld.exports=ni});var yr=h((G0,dd)=>{"use strict";var cd=kn(),aI=Ze(),sI=ei(),nI=cd(cd.bind);dd.exports=function(i,e){return aI(i),e===void 0?i:sI?nI(i,e):function(){return i.apply(e,arguments)}}});var Wn=h((W0,pd)=>{"use strict";var oI=Ee(),uI=re();pd.exports=oI&&uI(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var et=h((Y0,hd)=>{"use strict";var lI=Pe(),cI=String,dI=TypeError;hd.exports=function(i){if(lI(i))return i;throw new dI(cI(i)+" is not an object")}});var Qt=h(fd=>{"use strict";var pI=Ee(),hI=Qn(),mI=Wn(),Ga=et(),md=Hn(),fI=TypeError,Yn=Object.defineProperty,bI=Object.getOwnPropertyDescriptor,zn="enumerable",Kn="configurable",Xn="writable";fd.f=pI?mI?function(e,t,r){if(Ga(e),t=md(t),Ga(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Xn in r&&!r[Xn]){var a=bI(e,t);a&&a[Xn]&&(e[t]=r.value,r={configurable:Kn in r?r[Kn]:a[Kn],enumerable:zn in r?r[zn]:a[zn],writable:!1})}return Yn(e,t,r)}:Yn:function(e,t,r){if(Ga(e),t=md(t),Ga(r),hI)try{return Yn(e,t,r)}catch{}if("get"in r||"set"in r)throw new fI("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Tr=h((K0,bd)=>{"use strict";var gI=Ee(),vI=Qt(),SI=ti();bd.exports=gI?function(i,e,t){return vI.f(i,e,SI(1,t))}:function(i,e,t){return i[e]=t,i}});var K=h((X0,vd)=>{"use strict";var oi=Y(),yI=xn(),TI=kn(),II=W(),EI=ud().f,xI=Gn(),Ir=gr(),PI=yr(),Er=Tr(),gd=He();si();var kI=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 yI(i,this,arguments)};return e.prototype=i.prototype,e};vd.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?oi:a?oi[t]:oi[t]&&oi[t].prototype,o=r?Ir:Ir[t]||Er(Ir,t,{})[t],u=o.prototype,l,d,c,p,m,f,b,g,v;for(p in e)l=xI(r?p:t+(a?".":"#")+p,i.forced),d=!l&&n&&gd(n,p),f=o[p],d&&(i.dontCallGetSet?(v=EI(n,p),b=v&&v.value):b=n[p]),m=d&&b?b:e[p],!(!l&&!s&&typeof f==typeof m)&&(i.bind&&d?g=PI(m,oi):i.wrap&&d?g=kI(m):s&&II(m)?g=TI(m):g=m,(i.sham||m&&m.sham||f&&f.sham)&&Er(g,"sham",!0),Er(o,p,g),s&&(c=t+"Prototype",gd(Ir,c)||Er(Ir,c,{}),Er(Ir[c],p,m),i.real&&u&&(l||!u[p])&&Er(u,p,m)))}});var yd=h((J0,Sd)=>{"use strict";var wI=Math.ceil,AI=Math.floor;Sd.exports=Math.trunc||function(e){var t=+e;return(t>0?AI:wI)(t)}});var ui=h((Z0,Td)=>{"use strict";var LI=yd();Td.exports=function(i){var e=+i;return e!==e||e===0?0:LI(e)}});var Ed=h((eC,Id)=>{"use strict";var RI=ui(),$I=Math.max,MI=Math.min;Id.exports=function(i,e){var t=RI(i);return t<0?$I(t+e,0):MI(t,e)}});var Jn=h((tC,xd)=>{"use strict";var DI=ui(),CI=Math.min;xd.exports=function(i){var e=DI(i);return e>0?CI(e,9007199254740991):0}});var xr=h((rC,Pd)=>{"use strict";var VI=Jn();Pd.exports=function(i){return VI(i.length)}});var Zn=h((iC,wd)=>{"use strict";var BI=Ht(),OI=Ed(),_I=xr(),kd=function(i){return function(e,t,r){var a=BI(e),s=_I(a);if(s===0)return!i&&-1;var n=OI(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}};wd.exports={includes:kd(!0),indexOf:kd(!1)}});var li=h((aC,Ad)=>{"use strict";Ad.exports=function(){}});var Ld=h(()=>{"use strict";var NI=K(),FI=Zn().includes,qI=re(),UI=li(),HI=qI(function(){return!Array(1).includes()});NI({target:"Array",proto:!0,forced:HI},{includes:function(e){return FI(this,e,arguments.length>1?arguments[1]:void 0)}});UI("includes")});var It=h((oC,Rd)=>{"use strict";var jI=ut();Rd.exports=jI});var Md=h((uC,$d)=>{"use strict";Ld();var QI=It();$d.exports=QI("Array","includes")});var Cd=h((lC,Dd)=>{"use strict";var GI=Md();Dd.exports=GI});var je=h((cC,Vd)=>{"use strict";var WI=Cd();Vd.exports=WI});var za=h((IC,Hd)=>{"use strict";var tE=Fn(),rE=qn(),Ud=tE("keys");Hd.exports=function(i){return Ud[i]||(Ud[i]=rE(i))}});var Qd=h((EC,jd)=>{"use strict";var iE=re();jd.exports=!iE(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Ka=h((xC,Wd)=>{"use strict";var aE=He(),sE=W(),nE=vr(),oE=za(),uE=Qd(),Gd=oE("IE_PROTO"),ro=Object,lE=ro.prototype;Wd.exports=uE?ro.getPrototypeOf:function(i){var e=nE(i);if(aE(e,Gd))return e[Gd];var t=e.constructor;return sE(t)&&e instanceof t?t.prototype:e instanceof ro?lE:null}});var Xa=h((PC,Yd)=>{"use strict";Yd.exports={}});var Xd=h((kC,Kd)=>{"use strict";var cE=J(),io=He(),dE=Ht(),pE=Zn().indexOf,hE=Xa(),zd=cE([].push);Kd.exports=function(i,e){var t=dE(i),r=0,a=[],s;for(s in t)!io(hE,s)&&io(t,s)&&zd(a,s);for(;e.length>r;)io(t,s=e[r++])&&(~pE(a,s)||zd(a,s));return a}});var ao=h((wC,Jd)=>{"use strict";Jd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var so=h((AC,Zd)=>{"use strict";var mE=Xd(),fE=ao();Zd.exports=Object.keys||function(e){return mE(e,fE)}});var no=h((LC,ap)=>{"use strict";var tp=Ee(),bE=re(),rp=J(),gE=Ka(),vE=so(),SE=Ht(),yE=An().f,ip=rp(yE),TE=rp([].push),IE=tp&&bE(function(){var i=Object.create(null);return i[2]=2,!ip(i,2)}),ep=function(i){return function(e){for(var t=SE(e),r=vE(t),a=IE&&gE(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!tp||(a?u in t:ip(t,u)))&&TE(o,i?[u,t[u]]:t[u]);return o}};ap.exports={entries:ep(!0),values:ep(!1)}});var sp=h(()=>{"use strict";var EE=K(),xE=no().entries;EE({target:"Object",stat:!0},{entries:function(e){return xE(e)}})});var op=h((MC,np)=>{"use strict";sp();var PE=gr();np.exports=PE.Object.entries});var lp=h((DC,up)=>{"use strict";var kE=op();up.exports=kE});var Pr=h((CC,cp)=>{"use strict";var wE=lp();cp.exports=wE});var Gt=h((VC,dp)=>{"use strict";dp.exports={}});var mp=h((BC,hp)=>{"use strict";var AE=Y(),LE=W(),pp=AE.WeakMap;hp.exports=LE(pp)&&/native code/.test(String(pp))});var co=h((OC,gp)=>{"use strict";var RE=mp(),bp=Y(),$E=Pe(),ME=Tr(),oo=He(),uo=si(),DE=za(),CE=Xa(),fp="Object already initialized",lo=bp.TypeError,VE=bp.WeakMap,Ja,ci,Za,BE=function(i){return Za(i)?ci(i):Ja(i,{})},OE=function(i){return function(e){var t;if(!$E(e)||(t=ci(e)).type!==i)throw new lo("Incompatible receiver, "+i+" required");return t}};RE||uo.state?(Qe=uo.state||(uo.state=new VE),Qe.get=Qe.get,Qe.has=Qe.has,Qe.set=Qe.set,Ja=function(i,e){if(Qe.has(i))throw new lo(fp);return e.facade=i,Qe.set(i,e),e},ci=function(i){return Qe.get(i)||{}},Za=function(i){return Qe.has(i)}):(Wt=DE("state"),CE[Wt]=!0,Ja=function(i,e){if(oo(i,Wt))throw new lo(fp);return e.facade=i,ME(i,Wt,e),e},ci=function(i){return oo(i,Wt)?i[Wt]:{}},Za=function(i){return oo(i,Wt)});var Qe,Wt;gp.exports={set:Ja,get:ci,has:Za,enforce:BE,getterFor:OE}});var mo=h((_C,Sp)=>{"use strict";var po=Ee(),_E=He(),vp=Function.prototype,NE=po&&Object.getOwnPropertyDescriptor,ho=_E(vp,"name"),FE=ho&&function(){}.name==="something",qE=ho&&(!po||po&&NE(vp,"name").configurable);Sp.exports={EXISTS:ho,PROPER:FE,CONFIGURABLE:qE}});var Tp=h(yp=>{"use strict";var UE=Ee(),HE=Wn(),jE=Qt(),QE=et(),GE=Ht(),WE=so();yp.f=UE&&!HE?Object.defineProperties:function(e,t){QE(e);for(var r=GE(t),a=WE(t),s=a.length,n=0,o;s>n;)jE.f(e,o=a[n++],r[o]);return e}});var fo=h((FC,Ip)=>{"use strict";var YE=ut();Ip.exports=YE("document","documentElement")});var So=h((qC,Lp)=>{"use strict";var zE=et(),KE=Tp(),Ep=ao(),XE=Xa(),JE=fo(),ZE=Qa(),ex=za(),xp=">",Pp="<",go="prototype",vo="script",wp=ex("IE_PROTO"),bo=function(){},Ap=function(i){return Pp+vo+xp+i+Pp+"/"+vo+xp},kp=function(i){i.write(Ap("")),i.close();var e=i.parentWindow.Object;return i=null,e},tx=function(){var i=ZE("iframe"),e="java"+vo+":",t;return i.style.display="none",JE.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Ap("document.F=Object")),t.close(),t.F},es,ts=function(){try{es=new ActiveXObject("htmlfile")}catch{}ts=typeof document<"u"?document.domain&&es?kp(es):tx():kp(es);for(var i=Ep.length;i--;)delete ts[go][Ep[i]];return ts()};XE[wp]=!0;Lp.exports=Object.create||function(e,t){var r;return e!==null?(bo[go]=zE(e),r=new bo,bo[go]=null,r[wp]=e):r=ts(),t===void 0?r:KE.f(r,t)}});var kr=h((UC,Rp)=>{"use strict";var rx=Tr();Rp.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:rx(i,e,t),i}});var Eo=h((HC,Dp)=>{"use strict";var ix=re(),ax=W(),sx=Pe(),nx=So(),$p=Ka(),ox=kr(),ux=ie(),lx=Ue(),Io=ux("iterator"),Mp=!1,lt,yo,To;[].keys&&(To=[].keys(),"next"in To?(yo=$p($p(To)),yo!==Object.prototype&&(lt=yo)):Mp=!0);var cx=!sx(lt)||ix(function(){var i={};return lt[Io].call(i)!==i});cx?lt={}:lx&&(lt=nx(lt));ax(lt[Io])||ox(lt,Io,function(){return this});Dp.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:Mp}});var rs=h((jC,Vp)=>{"use strict";var dx=ie(),px=dx("toStringTag"),Cp={};Cp[px]="z";Vp.exports=String(Cp)==="[object z]"});var di=h((QC,Bp)=>{"use strict";var hx=rs(),mx=W(),is=Ut(),fx=ie(),bx=fx("toStringTag"),gx=Object,vx=is(function(){return arguments}())==="Arguments",Sx=function(i,e){try{return i[e]}catch{}};Bp.exports=hx?is:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Sx(e=gx(i),bx))=="string"?t:vx?is(e):(r=is(e))==="Object"&&mx(e.callee)?"Arguments":r}});var _p=h((GC,Op)=>{"use strict";var yx=rs(),Tx=di();Op.exports=yx?{}.toString:function(){return"[object "+Tx(this)+"]"}});var pi=h((WC,Fp)=>{"use strict";var Ix=rs(),Ex=Qt().f,xx=Tr(),Px=He(),kx=_p(),wx=ie(),Np=wx("toStringTag");Fp.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(Px(a,Np)||Ex(a,Np,{configurable:!0,value:e}),r&&!Ix&&xx(a,"toString",kx))}});var Up=h((YC,qp)=>{"use strict";var Ax=Eo().IteratorPrototype,Lx=So(),Rx=ti(),$x=pi(),Mx=Gt(),Dx=function(){return this};qp.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=Lx(Ax,{next:Rx(+!r,t)}),$x(i,a,!1,!0),Mx[a]=Dx,i}});var jp=h((zC,Hp)=>{"use strict";var Cx=J(),Vx=Ze();Hp.exports=function(i,e,t){try{return Cx(Vx(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Gp=h((KC,Qp)=>{"use strict";var Bx=Pe();Qp.exports=function(i){return Bx(i)||i===null}});var Yp=h((XC,Wp)=>{"use strict";var Ox=Gp(),_x=String,Nx=TypeError;Wp.exports=function(i){if(Ox(i))return i;throw new Nx("Can't set "+_x(i)+" as a prototype")}});var xo=h((JC,zp)=>{"use strict";var Fx=jp(),qx=Pe(),Ux=Tt(),Hx=Yp();zp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=Fx(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return Ux(a),Hx(s),qx(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var nh=h((ZC,sh)=>{"use strict";var jx=K(),Qx=xe(),as=Ue(),ih=mo(),Gx=W(),Wx=Up(),Kp=Ka(),Xp=xo(),Yx=pi(),zx=Tr(),Po=kr(),Kx=ie(),Jp=Gt(),ah=Eo(),Xx=ih.PROPER,Jx=ih.CONFIGURABLE,Zp=ah.IteratorPrototype,ss=ah.BUGGY_SAFARI_ITERATORS,hi=Kx("iterator"),eh="keys",mi="values",th="entries",rh=function(){return this};sh.exports=function(i,e,t,r,a,s,n){Wx(t,e,r);var o=function(v){if(v===a&&p)return p;if(!ss&&v&&v in d)return d[v];switch(v){case eh:return function(){return new t(this,v)};case mi:return function(){return new t(this,v)};case th:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=i.prototype,c=d[hi]||d["@@iterator"]||a&&d[a],p=!ss&&c||o(a),m=e==="Array"&&d.entries||c,f,b,g;if(m&&(f=Kp(m.call(new i)),f!==Object.prototype&&f.next&&(!as&&Kp(f)!==Zp&&(Xp?Xp(f,Zp):Gx(f[hi])||Po(f,hi,rh)),Yx(f,u,!0,!0),as&&(Jp[u]=rh))),Xx&&a===mi&&c&&c.name!==mi&&(!as&&Jx?zx(d,"name",mi):(l=!0,p=function(){return Qx(c,this)})),a)if(b={values:o(mi),keys:s?p:o(eh),entries:o(th)},n)for(g in b)(ss||l||!(g in d))&&Po(d,g,b[g]);else jx({target:e,proto:!0,forced:ss||l},b);return(!as||n)&&d[hi]!==p&&Po(d,hi,p,{name:a}),Jp[e]=p,b}});var uh=h((eV,oh)=>{"use strict";oh.exports=function(i,e){return{value:i,done:e}}});var wo=h((tV,hh)=>{"use strict";var Zx=Ht(),ko=li(),lh=Gt(),dh=co(),eP=Qt().f,tP=nh(),ns=uh(),rP=Ue(),iP=Ee(),ph="Array Iterator",aP=dh.set,sP=dh.getterFor(ph);hh.exports=tP(Array,"Array",function(i,e){aP(this,{type:ph,target:Zx(i),index:0,kind:e})},function(){var i=sP(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,ns(void 0,!0);switch(i.kind){case"keys":return ns(t,!1);case"values":return ns(e[t],!1)}return ns([t,e[t]],!1)},"values");var ch=lh.Arguments=lh.Array;ko("keys");ko("values");ko("entries");if(!rP&&iP&&ch.name!=="values")try{eP(ch,"name",{value:"values"})}catch{}});var fh=h((rV,mh)=>{"use strict";var nP=ie(),oP=Gt(),uP=nP("iterator"),lP=Array.prototype;mh.exports=function(i){return i!==void 0&&(oP.Array===i||lP[uP]===i)}});var Ao=h((iV,gh)=>{"use strict";var cP=di(),bh=ai(),dP=br(),pP=Gt(),hP=ie(),mP=hP("iterator");gh.exports=function(i){if(!dP(i))return bh(i,mP)||bh(i,"@@iterator")||pP[cP(i)]}});var Sh=h((aV,vh)=>{"use strict";var fP=xe(),bP=Ze(),gP=et(),vP=ii(),SP=Ao(),yP=TypeError;vh.exports=function(i,e){var t=arguments.length<2?SP(i):e;if(bP(t))return gP(fP(t,i));throw new yP(vP(i)+" is not iterable")}});var Ih=h((sV,Th)=>{"use strict";var TP=xe(),yh=et(),IP=ai();Th.exports=function(i,e,t){var r,a;yh(i);try{if(r=IP(i,"return"),!r){if(e==="throw")throw t;return t}r=TP(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return yh(r),t}});var us=h((nV,kh)=>{"use strict";var EP=yr(),xP=xe(),PP=et(),kP=ii(),wP=fh(),AP=xr(),Eh=ri(),LP=Sh(),RP=Ao(),xh=Ih(),$P=TypeError,os=function(i,e){this.stopped=i,this.result=e},Ph=os.prototype;kh.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=EP(e,r),l,d,c,p,m,f,b,g=function(k){return l&&xh(l,"normal",k),new os(!0,k)},v=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(d=RP(i),!d)throw new $P(kP(i)+" is not iterable");if(wP(d)){for(c=0,p=AP(i);p>c;c++)if(m=v(i[c]),m&&Eh(Ph,m))return m;return new os(!1)}l=LP(i,d)}for(f=s?i.next:l.next;!(b=xP(f,l)).done;){try{m=v(b.value)}catch(k){xh(l,"throw",k)}if(typeof m=="object"&&m&&Eh(Ph,m))return m}return new os(!1)}});var Ah=h((oV,wh)=>{"use strict";var MP=Ee(),DP=Qt(),CP=ti();wh.exports=function(i,e,t){MP?DP.f(i,e,CP(0,t)):i[e]=t}});var Lh=h(()=>{"use strict";var VP=K(),BP=us(),OP=Ah();VP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return BP(e,function(r,a){OP(t,r,a)},{AS_ENTRIES:!0}),t}})});var $h=h((cV,Rh)=>{"use strict";wo();Lh();var _P=gr();Rh.exports=_P.Object.fromEntries});var Dh=h((dV,Mh)=>{"use strict";Mh.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 Vh=h(()=>{"use strict";wo();var NP=Dh(),FP=Y(),qP=pi(),Ch=Gt();for(ls in NP)qP(FP[ls],ls),Ch[ls]=Ch.Array;var ls});var Oh=h((mV,Bh)=>{"use strict";var UP=$h();Vh();Bh.exports=UP});var Lo=h((fV,_h)=>{"use strict";var HP=Oh();_h.exports=HP});var Nh=h(()=>{"use strict"});var Ro=h((vV,Fh)=>{"use strict";var fi=Y(),jP=jt(),QP=Ut(),cs=function(i){return jP.slice(0,i.length)===i};Fh.exports=function(){return cs("Bun/")?"BUN":cs("Cloudflare-Workers")?"CLOUDFLARE":cs("Deno/")?"DENO":cs("Node.js/")?"NODE":fi.Bun&&typeof Bun.version=="string"?"BUN":fi.Deno&&typeof Deno.version=="object"?"DENO":QP(fi.process)==="process"?"NODE":fi.window&&fi.document?"BROWSER":"REST"}()});var ds=h((SV,qh)=>{"use strict";var GP=Ro();qh.exports=GP==="NODE"});var Hh=h((yV,Uh)=>{"use strict";var WP=Qt();Uh.exports=function(i,e,t){return WP.f(i,e,t)}});var Gh=h((TV,Qh)=>{"use strict";var YP=ut(),zP=Hh(),KP=ie(),XP=Ee(),jh=KP("species");Qh.exports=function(i){var e=YP(i);XP&&e&&!e[jh]&&zP(e,jh,{configurable:!0,get:function(){return this}})}});var Yh=h((IV,Wh)=>{"use strict";var JP=ri(),ZP=TypeError;Wh.exports=function(i,e){if(JP(e,i))return i;throw new ZP("Incorrect invocation")}});var Mo=h((EV,zh)=>{"use strict";var ek=J(),tk=W(),$o=si(),rk=ek(Function.toString);tk($o.inspectSource)||($o.inspectSource=function(i){return rk(i)});zh.exports=$o.inspectSource});var Co=h((xV,em)=>{"use strict";var ik=J(),ak=re(),Kh=W(),sk=di(),nk=ut(),ok=Mo(),Xh=function(){},Jh=nk("Reflect","construct"),Do=/^\s*(?:class|function)\b/,uk=ik(Do.exec),lk=!Do.test(Xh),bi=function(e){if(!Kh(e))return!1;try{return Jh(Xh,[],e),!0}catch{return!1}},Zh=function(e){if(!Kh(e))return!1;switch(sk(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return lk||!!uk(Do,ok(e))}catch{return!0}};Zh.sham=!0;em.exports=!Jh||ak(function(){var i;return bi(bi.call)||!bi(Object)||!bi(function(){i=!0})||i})?Zh:bi});var rm=h((PV,tm)=>{"use strict";var ck=Co(),dk=ii(),pk=TypeError;tm.exports=function(i){if(ck(i))return i;throw new pk(dk(i)+" is not a constructor")}});var Vo=h((kV,am)=>{"use strict";var im=et(),hk=rm(),mk=br(),fk=ie(),bk=fk("species");am.exports=function(i,e){var t=im(i).constructor,r;return t===void 0||mk(r=im(t)[bk])?e:hk(r)}});var nm=h((wV,sm)=>{"use strict";var gk=J();sm.exports=gk([].slice)});var um=h((AV,om)=>{"use strict";var vk=TypeError;om.exports=function(i,e){if(i<e)throw new vk("Not enough arguments");return i}});var Bo=h((LV,lm)=>{"use strict";var Sk=jt();lm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Sk)});var Qo=h((RV,vm)=>{"use strict";var ke=Y(),yk=xn(),Tk=yr(),cm=W(),Ik=He(),gm=re(),dm=fo(),Ek=nm(),pm=Qa(),xk=um(),Pk=Bo(),kk=ds(),Uo=ke.setImmediate,Ho=ke.clearImmediate,wk=ke.process,Oo=ke.Dispatch,Ak=ke.Function,hm=ke.MessageChannel,Lk=ke.String,_o=0,gi={},mm="onreadystatechange",vi,Yt,No,Fo;gm(function(){vi=ke.location});var jo=function(i){if(Ik(gi,i)){var e=gi[i];delete gi[i],e()}},qo=function(i){return function(){jo(i)}},fm=function(i){jo(i.data)},bm=function(i){ke.postMessage(Lk(i),vi.protocol+"//"+vi.host)};(!Uo||!Ho)&&(Uo=function(e){xk(arguments.length,1);var t=cm(e)?e:Ak(e),r=Ek(arguments,1);return gi[++_o]=function(){yk(t,void 0,r)},Yt(_o),_o},Ho=function(e){delete gi[e]},kk?Yt=function(i){wk.nextTick(qo(i))}:Oo&&Oo.now?Yt=function(i){Oo.now(qo(i))}:hm&&!Pk?(No=new hm,Fo=No.port2,No.port1.onmessage=fm,Yt=Tk(Fo.postMessage,Fo)):ke.addEventListener&&cm(ke.postMessage)&&!ke.importScripts&&vi&&vi.protocol!=="file:"&&!gm(bm)?(Yt=bm,ke.addEventListener("message",fm,!1)):mm in pm("script")?Yt=function(i){dm.appendChild(pm("script"))[mm]=function(){dm.removeChild(this),jo(i)}}:Yt=function(i){setTimeout(qo(i),0)});vm.exports={set:Uo,clear:Ho}});var Tm=h(($V,ym)=>{"use strict";var Sm=Y(),Rk=Ee(),$k=Object.getOwnPropertyDescriptor;ym.exports=function(i){if(!Rk)return Sm[i];var e=$k(Sm,i);return e&&e.value}});var Go=h((MV,Em)=>{"use strict";var Im=function(){this.head=null,this.tail=null};Im.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}}};Em.exports=Im});var Pm=h((DV,xm)=>{"use strict";var Mk=jt();xm.exports=/ipad|iphone|ipod/i.test(Mk)&&typeof Pebble<"u"});var wm=h((CV,km)=>{"use strict";var Dk=jt();km.exports=/web0s(?!.*chrome)/i.test(Dk)});var Cm=h((VV,Dm)=>{"use strict";var Ar=Y(),Ck=Tm(),Am=yr(),Wo=Qo().set,Vk=Go(),Bk=Bo(),Ok=Pm(),_k=wm(),Yo=ds(),Lm=Ar.MutationObserver||Ar.WebKitMutationObserver,Rm=Ar.document,$m=Ar.process,ps=Ar.Promise,Xo=Ck("queueMicrotask"),wr,zo,Ko,hs,Mm;Xo||(Si=new Vk,yi=function(){var i,e;for(Yo&&(i=$m.domain)&&i.exit();e=Si.get();)try{e()}catch(t){throw Si.head&&wr(),t}i&&i.enter()},!Bk&&!Yo&&!_k&&Lm&&Rm?(zo=!0,Ko=Rm.createTextNode(""),new Lm(yi).observe(Ko,{characterData:!0}),wr=function(){Ko.data=zo=!zo}):!Ok&&ps&&ps.resolve?(hs=ps.resolve(void 0),hs.constructor=ps,Mm=Am(hs.then,hs),wr=function(){Mm(yi)}):Yo?wr=function(){$m.nextTick(yi)}:(Wo=Am(Wo,Ar),wr=function(){Wo(yi)}),Xo=function(i){Si.head||wr(),Si.add(i)});var Si,yi;Dm.exports=Xo});var Bm=h((BV,Vm)=>{"use strict";Vm.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var ms=h((OV,Om)=>{"use strict";Om.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var zt=h((_V,_m)=>{"use strict";var Nk=Y();_m.exports=Nk.Promise});var Lr=h((NV,Um)=>{"use strict";var Fk=Y(),Ti=zt(),qk=W(),Uk=Gn(),Hk=Mo(),jk=ie(),Nm=Ro(),Qk=Ue(),Jo=Dn(),Fm=Ti&&Ti.prototype,Gk=jk("species"),Zo=!1,qm=qk(Fk.PromiseRejectionEvent),Wk=Uk("Promise",function(){var i=Hk(Ti),e=i!==String(Ti);if(!e&&Jo===66||Qk&&!(Fm.catch&&Fm.finally))return!0;if(!Jo||Jo<51||!/native code/.test(i)){var t=new Ti(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Gk]=r,Zo=t.then(function(){})instanceof r,!Zo)return!0}return!e&&(Nm==="BROWSER"||Nm==="DENO")&&!qm});Um.exports={CONSTRUCTOR:Wk,REJECTION_EVENT:qm,SUBCLASSING:Zo}});var Rr=h((FV,jm)=>{"use strict";var Hm=Ze(),Yk=TypeError,zk=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new Yk("Bad Promise constructor");e=r,t=a}),this.resolve=Hm(e),this.reject=Hm(t)};jm.exports.f=function(i){return new zk(i)}});var cf=h(()=>{"use strict";var Kk=K(),Xk=Ue(),vs=ds(),Et=Y(),Cr=xe(),Qm=kr(),Gm=xo(),Jk=pi(),Zk=Gh(),ew=Ze(),gs=W(),tw=Pe(),rw=Yh(),iw=Vo(),Xm=Qo().set,au=Cm(),aw=Bm(),sw=ms(),nw=Go(),Jm=co(),Ss=zt(),su=Lr(),Zm=Rr(),ys="Promise",ef=su.CONSTRUCTOR,ow=su.REJECTION_EVENT,uw=su.SUBCLASSING,eu=Jm.getterFor(ys),lw=Jm.set,$r=Ss&&Ss.prototype,Kt=Ss,fs=$r,tf=Et.TypeError,tu=Et.document,nu=Et.process,ru=Zm.f,cw=ru,dw=!!(tu&&tu.createEvent&&Et.dispatchEvent),rf="unhandledrejection",pw="rejectionhandled",Wm=0,af=1,hw=2,ou=1,sf=2,bs,Ym,mw,zm,nf=function(i){var e;return tw(i)&&gs(e=i.then)?e:!1},of=function(i,e){var t=e.value,r=e.state===af,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,d;try{a?(r||(e.rejection===sf&&bw(e),e.rejection=ou),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),d=!0)),u===i.promise?n(new tf("Promise-chain cycle")):(l=nf(u))?Cr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},uf=function(i,e){i.notified||(i.notified=!0,au(function(){for(var t=i.reactions,r;r=t.get();)of(r,i);i.notified=!1,e&&!i.rejection&&fw(i)}))},lf=function(i,e,t){var r,a;dw?(r=tu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Et.dispatchEvent(r)):r={promise:e,reason:t},!ow&&(a=Et["on"+i])?a(r):i===rf&&aw("Unhandled promise rejection",t)},fw=function(i){Cr(Xm,Et,function(){var e=i.facade,t=i.value,r=Km(i),a;if(r&&(a=sw(function(){vs?nu.emit("unhandledRejection",t,e):lf(rf,e,t)}),i.rejection=vs||Km(i)?sf:ou,a.error))throw a.value})},Km=function(i){return i.rejection!==ou&&!i.parent},bw=function(i){Cr(Xm,Et,function(){var e=i.facade;vs?nu.emit("rejectionHandled",e):lf(pw,e,i.value)})},Mr=function(i,e,t){return function(r){i(e,r,t)}},Dr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=hw,uf(i,!0))},iu=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new tf("Promise can't be resolved itself");var r=nf(e);r?au(function(){var a={done:!1};try{Cr(r,e,Mr(iu,a,i),Mr(Dr,a,i))}catch(s){Dr(a,s,i)}}):(i.value=e,i.state=af,uf(i,!1))}catch(a){Dr({done:!1},a,i)}}};if(ef&&(Kt=function(e){rw(this,fs),ew(e),Cr(bs,this);var t=eu(this);try{e(Mr(iu,t),Mr(Dr,t))}catch(r){Dr(t,r)}},fs=Kt.prototype,bs=function(e){lw(this,{type:ys,done:!1,notified:!1,parent:!1,reactions:new nw,rejection:!1,state:Wm,value:void 0})},bs.prototype=Qm(fs,"then",function(e,t){var r=eu(this),a=ru(iw(this,Kt));return r.parent=!0,a.ok=gs(e)?e:!0,a.fail=gs(t)&&t,a.domain=vs?nu.domain:void 0,r.state===Wm?r.reactions.add(a):au(function(){of(a,r)}),a.promise}),Ym=function(){var i=new bs,e=eu(i);this.promise=i,this.resolve=Mr(iu,e),this.reject=Mr(Dr,e)},Zm.f=ru=function(i){return i===Kt||i===mw?new Ym(i):cw(i)},!Xk&&gs(Ss)&&$r!==Object.prototype)){zm=$r.then,uw||Qm($r,"then",function(e,t){var r=this;return new Kt(function(a,s){Cr(zm,r,a,s)}).then(e,t)},{unsafe:!0});try{delete $r.constructor}catch{}Gm&&Gm($r,fs)}Kk({global:!0,constructor:!0,wrap:!0,forced:ef},{Promise:Kt});Jk(Kt,ys,!1,!0);Zk(ys)});var ff=h((HV,mf)=>{"use strict";var gw=ie(),pf=gw("iterator"),hf=!1;try{df=0,uu={next:function(){return{done:!!df++}},return:function(){hf=!0}},uu[pf]=function(){return this},Array.from(uu,function(){throw 2})}catch{}var df,uu;mf.exports=function(i,e){try{if(!e&&!hf)return!1}catch{return!1}var t=!1;try{var r={};r[pf]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var lu=h((jV,bf)=>{"use strict";var vw=zt(),Sw=ff(),yw=Lr().CONSTRUCTOR;bf.exports=yw||!Sw(function(i){vw.all(i).then(void 0,function(){})})});var gf=h(()=>{"use strict";var Tw=K(),Iw=xe(),Ew=Ze(),xw=Rr(),Pw=ms(),kw=us(),ww=lu();Tw({target:"Promise",stat:!0,forced:ww},{all:function(e){var t=this,r=xw.f(t),a=r.resolve,s=r.reject,n=Pw(function(){var o=Ew(t.resolve),u=[],l=0,d=1;kw(e,function(c){var p=l++,m=!1;d++,Iw(o,t,c).then(function(f){m||(m=!0,u[p]=f,--d||a(u))},s)}),--d||a(u)});return n.error&&s(n.value),r.promise}})});var Sf=h(()=>{"use strict";var Aw=K(),Lw=Ue(),Rw=Lr().CONSTRUCTOR,du=zt(),$w=ut(),Mw=W(),Dw=kr(),vf=du&&du.prototype;Aw({target:"Promise",proto:!0,forced:Rw,real:!0},{catch:function(i){return this.then(void 0,i)}});!Lw&&Mw(du)&&(cu=$w("Promise").prototype.catch,vf.catch!==cu&&Dw(vf,"catch",cu,{unsafe:!0}));var cu});var yf=h(()=>{"use strict";var Cw=K(),Vw=xe(),Bw=Ze(),Ow=Rr(),_w=ms(),Nw=us(),Fw=lu();Cw({target:"Promise",stat:!0,forced:Fw},{race:function(e){var t=this,r=Ow.f(t),a=r.reject,s=_w(function(){var n=Bw(t.resolve);Nw(e,function(o){Vw(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Tf=h(()=>{"use strict";var qw=K(),Uw=Rr(),Hw=Lr().CONSTRUCTOR;qw({target:"Promise",stat:!0,forced:Hw},{reject:function(e){var t=Uw.f(this),r=t.reject;return r(e),t.promise}})});var pu=h((ZV,If)=>{"use strict";var jw=et(),Qw=Pe(),Gw=Rr();If.exports=function(i,e){if(jw(i),Qw(e)&&e.constructor===i)return e;var t=Gw.f(i),r=t.resolve;return r(e),t.promise}});var Pf=h(()=>{"use strict";var Ww=K(),Yw=ut(),Ef=Ue(),zw=zt(),xf=Lr().CONSTRUCTOR,Kw=pu(),Xw=Yw("Promise"),Jw=Ef&&!xf;Ww({target:"Promise",stat:!0,forced:Ef||xf},{resolve:function(e){return Kw(Jw&&this===Xw?zw:this,e)}})});var kf=h(()=>{"use strict";cf();gf();Sf();yf();Tf();Pf()});var Rf=h(()=>{"use strict";var Zw=K(),eA=Ue(),Ts=zt(),tA=re(),Af=ut(),Lf=W(),rA=Vo(),wf=pu(),iA=kr(),mu=Ts&&Ts.prototype,aA=!!Ts&&tA(function(){mu.finally.call({then:function(){}},function(){})});Zw({target:"Promise",proto:!0,real:!0,forced:aA},{finally:function(i){var e=rA(this,Af("Promise")),t=Lf(i);return this.then(t?function(r){return wf(e,i()).then(function(){return r})}:i,t?function(r){return wf(e,i()).then(function(){throw r})}:i)}});!eA&&Lf(Ts)&&(hu=Af("Promise").prototype.finally,mu.finally!==hu&&iA(mu,"finally",hu,{unsafe:!0}));var hu});var Mf=h((nB,$f)=>{"use strict";Nh();kf();Rf();var sA=It();$f.exports=sA("Promise","finally")});var Cf=h((oB,Df)=>{"use strict";var nA=Mf();Df.exports=nA});var Is=h((uB,Vf)=>{"use strict";var oA=Cf();Vf.exports=oA});var Yf=h(()=>{"use strict";var TA=K(),IA=no().values;TA({target:"Object",stat:!0},{values:function(e){return IA(e)}})});var Kf=h((GB,zf)=>{"use strict";Yf();var EA=gr();zf.exports=EA.Object.values});var Jf=h((WB,Xf)=>{"use strict";var xA=Kf();Xf.exports=xA});var Br=h((YB,Zf)=>{"use strict";var PA=Jf();Zf.exports=PA});var pb=h(()=>{"use strict";var qA=K(),UA=vr(),HA=xr(),jA=ui(),QA=li();qA({target:"Array",proto:!0},{at:function(e){var t=UA(this),r=HA(t),a=jA(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});QA("at")});var mb=h((IO,hb)=>{"use strict";pb();var GA=It();hb.exports=GA("Array","at")});var bb=h((EO,fb)=>{"use strict";var WA=mb();fb.exports=WA});var Zt=h((xO,gb)=>{"use strict";var YA=bb();gb.exports=YA});var _u=h((aN,Kb)=>{"use strict";var DL=Ut();Kb.exports=Array.isArray||function(e){return DL(e)==="Array"}});var Jb=h((sN,Xb)=>{"use strict";var CL=TypeError,VL=9007199254740991;Xb.exports=function(i){if(i>VL)throw CL("Maximum allowed index exceeded");return i}});var tg=h((nN,eg)=>{"use strict";var BL=_u(),OL=xr(),_L=Jb(),NL=yr(),Zb=function(i,e,t,r,a,s,n,o){for(var u=a,l=0,d=n?NL(n,o):!1,c,p;l<r;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&BL(c)?(p=OL(c),u=Zb(i,e,c,p,u,s-1)-1):(_L(u+1),i[u]=c),u++),l++;return u};eg.exports=Zb});var sg=h((oN,ag)=>{"use strict";var rg=_u(),FL=Co(),qL=Pe(),UL=ie(),HL=UL("species"),ig=Array;ag.exports=function(i){var e;return rg(i)&&(e=i.constructor,FL(e)&&(e===ig||rg(e.prototype))?e=void 0:qL(e)&&(e=e[HL],e===null&&(e=void 0))),e===void 0?ig:e}});var og=h((uN,ng)=>{"use strict";var jL=sg();ng.exports=function(i,e){return new(jL(i))(e===0?0:e)}});var ug=h(()=>{"use strict";var QL=K(),GL=tg(),WL=Ze(),YL=vr(),zL=xr(),KL=og();QL({target:"Array",proto:!0},{flatMap:function(e){var t=YL(this),r=zL(t),a;return WL(e),a=KL(t,0),a.length=GL(a,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var lg=h(()=>{"use strict";var XL=li();XL("flatMap")});var dg=h((hN,cg)=>{"use strict";ug();lg();var JL=It();cg.exports=JL("Array","flatMap")});var hg=h((mN,pg)=>{"use strict";var ZL=dg();pg.exports=ZL});var Nu=h((fN,mg)=>{"use strict";var eR=hg();mg.exports=eR});var Bi=h((PN,xg)=>{"use strict";var uR=di(),lR=String;xg.exports=function(i){if(uR(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return lR(i)}});var qu=h((kN,Pg)=>{"use strict";Pg.exports=`
|
|
7
|
+
\v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var Ag=h((wN,wg)=>{"use strict";var cR=J(),dR=Tt(),pR=Bi(),Hu=qu(),kg=cR("".replace),hR=RegExp("^["+Hu+"]+"),mR=RegExp("(^|[^"+Hu+"])["+Hu+"]+$"),Uu=function(i){return function(e){var t=pR(dR(e));return i&1&&(t=kg(t,hR,"")),i&2&&(t=kg(t,mR,"$1")),t}};wg.exports={start:Uu(1),end:Uu(2),trim:Uu(3)}});var Mg=h((AN,$g)=>{"use strict";var fR=mo().PROPER,bR=re(),Lg=qu(),Rg="\u200B\x85\u180E";$g.exports=function(i){return bR(function(){return!!Lg[i]()||Rg[i]()!==Rg||fR&&Lg[i].name!==i})}});var ju=h((LN,Dg)=>{"use strict";var gR=Ag().start,vR=Mg();Dg.exports=vR("trimStart")?function(){return gR(this)}:"".trimStart});var Vg=h(()=>{"use strict";var SR=K(),Cg=ju();SR({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Cg},{trimLeft:Cg})});var Og=h(()=>{"use strict";Vg();var yR=K(),Bg=ju();yR({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Bg},{trimStart:Bg})});var Ng=h((CN,_g)=>{"use strict";Og();var TR=It();_g.exports=TR("String","trimLeft")});var qg=h((VN,Fg)=>{"use strict";var IR=Ng();Fg.exports=IR});var Hg=h((BN,Ug)=>{"use strict";var ER=qg();Ug.exports=ER});var sv=h(()=>{"use strict"});var nv=h(()=>{"use strict"});var uv=h((fU,ov)=>{"use strict";var GR=Pe(),WR=Ut(),YR=ie(),zR=YR("match");ov.exports=function(i){var e;return GR(i)&&((e=i[zR])!==void 0?!!e:WR(i)==="RegExp")}});var cv=h((bU,lv)=>{"use strict";var KR=et();lv.exports=function(){var i=KR(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 hv=h((gU,pv)=>{"use strict";var XR=xe(),JR=He(),ZR=ri(),e$=cv(),dv=RegExp.prototype;pv.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in dv)&&!JR(i,"flags")&&ZR(dv,i)?XR(e$,i):e}});var fv=h((vU,mv)=>{"use strict";var Zu=J(),t$=vr(),r$=Math.floor,Xu=Zu("".charAt),i$=Zu("".replace),Ju=Zu("".slice),a$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,s$=/\$([$&'`]|\d{1,2})/g;mv.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=s$;return a!==void 0&&(a=t$(a),u=a$),i$(s,u,function(l,d){var c;switch(Xu(d,0)){case"$":return"$";case"&":return i;case"`":return Ju(e,0,t);case"'":return Ju(e,n);case"<":c=a[Ju(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var m=r$(p/10);return m===0?l:m<=o?r[m-1]===void 0?Xu(d,1):r[m-1]+Xu(d,1):l}c=r[p-1]}return c===void 0?"":c})}});var vv=h(()=>{"use strict";var n$=K(),o$=xe(),tl=J(),bv=Tt(),u$=W(),l$=br(),c$=uv(),Hr=Bi(),d$=ai(),p$=hv(),h$=fv(),m$=ie(),f$=Ue(),b$=m$("replace"),g$=TypeError,el=tl("".indexOf),v$=tl("".replace),gv=tl("".slice),S$=Math.max;n$({target:"String",proto:!0},{replaceAll:function(e,t){var r=bv(this),a,s,n,o,u,l,d,c,p,m,f=0,b="";if(!l$(e)){if(a=c$(e),a&&(s=Hr(bv(p$(e))),!~el(s,"g")))throw new g$("`.replaceAll` does not allow non-global regexes");if(n=d$(e,b$),n)return o$(n,e,r,t);if(f$&&a)return v$(Hr(r),e,t)}for(o=Hr(r),u=Hr(e),l=u$(t),l||(t=Hr(t)),d=u.length,c=S$(1,d),p=el(o,u);p!==-1;)m=l?Hr(t(u,p,o)):h$(u,o,p,[],void 0,t),b+=gv(o,f,p)+m,f=p+d,p=p+c>o.length?-1:el(o,u,p+c);return f<o.length&&(b+=gv(o,f)),b}})});var yv=h((TU,Sv)=>{"use strict";sv();nv();vv();var y$=It();Sv.exports=y$("String","replaceAll")});var Iv=h((IU,Tv)=>{"use strict";var T$=yv();Tv.exports=T$});var xv=h((EU,Ev)=>{"use strict";var I$=Iv();Ev.exports=I$});var kv=h((xU,Pv)=>{"use strict";var E$=ui(),x$=Bi(),P$=Tt(),k$=RangeError;Pv.exports=function(e){var t=x$(P$(this)),r="",a=E$(e);if(a<0||a===1/0)throw new k$("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(r+=t);return r}});var $v=h((PU,Rv)=>{"use strict";var Lv=J(),w$=Jn(),wv=Bi(),A$=kv(),L$=Tt(),R$=Lv(A$),$$=Lv("".slice),M$=Math.ceil,Av=function(i){return function(e,t,r){var a=wv(L$(e)),s=w$(t),n=a.length,o=r===void 0?" ":wv(r),u,l;return s<=n||o===""?a:(u=s-n,l=R$(o,M$(u/o.length)),l.length>u&&(l=$$(l,0,u)),i?a+l:l+a)}};Rv.exports={start:Av(!1),end:Av(!0)}});var Dv=h((kU,Mv)=>{"use strict";var D$=jt();Mv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(D$)});var Cv=h(()=>{"use strict";var C$=K(),V$=$v().start,B$=Dv();C$({target:"String",proto:!0,forced:B$},{padStart:function(e){return V$(this,e,arguments.length>1?arguments[1]:void 0)}})});var Bv=h((LU,Vv)=>{"use strict";Cv();var O$=It();Vv.exports=O$("String","padStart")});var _v=h((RU,Ov)=>{"use strict";var _$=Bv();Ov.exports=_$});var Fv=h(($U,Nv)=>{"use strict";var N$=_v();Nv.exports=N$});var Hl="2.0.124-dev.6f019bb5.0";var he=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(he||{}),yt=(x=>(x.MPEG="MPEG",x.DASH="DASH",x.DASH_SEP="DASH_SEP",x.DASH_SEP_VK="DASH_SEP",x.DASH_WEBM="DASH_WEBM",x.DASH_WEBM_AV1="DASH_WEBM_AV1",x.DASH_STREAMS="DASH_STREAMS",x.DASH_WEBM_VK="DASH_WEBM",x.DASH_ONDEMAND="DASH_ONDEMAND",x.DASH_ONDEMAND_VK="DASH_ONDEMAND",x.DASH_LIVE="DASH_LIVE",x.DASH_LIVE_CMAF="DASH_LIVE_CMAF",x.DASH_LIVE_WEBM="DASH_LIVE_WEBM",x.HLS="HLS",x.HLS_ONDEMAND="HLS_ONDEMAND",x.HLS_JS="HLS",x.HLS_LIVE="HLS_LIVE",x.HLS_LIVE_CMAF="HLS_LIVE_CMAF",x.WEB_RTC_LIVE="WEB_RTC_LIVE",x))(yt||{});var qa=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(qa||{}),Tn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Tn||{});var In=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(In||{}),Ua=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(Ua||{});var by=D(je(),1);import{assertNever as qd,assertNonNullable as YI,isNonNullable as Wa,ValueSubject as eo,Subject as zI,Subscription as KI,merge as XI,observableFrom as JI,fromEvent as Od,map as _d,tap as Nd,filterChanged as ZI,isNullable as to,ErrorCategory as Fd}from"@vkontakte/videoplayer-shared";var Bd=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e(),r.onerror=a=>t(a),document.body.appendChild(r)});var Ya=class{constructor(e){this.connection$=new eo(void 0);this.castState$=new eo("NOT_AVAILABLE");this.errorEvent$=new zI;this.realCastState$=new eo("NOT_AVAILABLE");this.subscription=new KI;this.isDestroyed=!1;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Wa(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},a||Bd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Fd.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(){Wa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();to(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();to(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Od(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 qd(a.sessionState)}})).add(XI(Od(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Nd(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),_d(a=>a.castState)),JI([r.getCastState()])).pipe(ZI(),_d(eE),Nd(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=Wa(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();YI(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(to(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"?Wa(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:Fd.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},eE=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 qd(i)}};var Cl=D(je(),1),XS=D(Pr(),1),JS=D(Lo(),1);var Qf=D(Is(),1);import{assertNever as Bf}from"@vkontakte/videoplayer-shared";var ae=(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:Bf(t)}return i},Es=(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:Bf(e)}};var T=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as uA,Subject as xs,merge as Of}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new xs;this.transitionEnded$=new xs;this.transitionUpdated$=new xs;this.forceChanged$=new xs;this.stateChangeStarted$=Of(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Of(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||uA(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 lA}from"@vkontakte/videoplayer-shared";var _f=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 lA(i)}};import{assertNever as Vr,assertNonNullable as Xt,debounce as Nf,ErrorCategory as Ff,fromEvent as Jt,isNonNullable as qf,map as Uf,merge as Hf,observableFrom as cA,Subject as dA,Subscription as fu,timeout as pA,getHighestQuality as hA}from"@vkontakte/videoplayer-shared";var mA=5,fA=5,bA=500,jf=7e3,Ii=class{constructor(e){this.subscription=new fu;this.loadMediaTimeoutSubscription=new fu;this.videoState=new $("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:Vr(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:Vr(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:Vr(e)}break}default:Vr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_f(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 fu;this.subscription.add(e),this.subscription.add(Hf(this.videoState.stateChangeStarted$.pipe(Uf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Uf(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 dA;e.add(a.pipe(Nf(bA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Jt(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)>mA)&&a.next(o),s=o})),e.add(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Jt(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<fA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(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:Vr(n)}}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Jt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Hf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cA(["init"])).pipe(Nf(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"),T(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),T(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"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&T(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];Xt(l);let d=hA(Object.keys(l));Xt(d);let c=l[d];Xt(c),r=c,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Xt(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];Xt(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Xt(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];Xt(l),r=ae(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",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Ff.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Vr(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 qf(o)&&(n.metadata.title=o),qf(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(pA(jf).subscribe(()=>s(`timeout(${jf})`)))});(0,Qf.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:Ff.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Bu=D(je(),1);import{clearVideoElement as Wf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as gA}from"@vkontakte/videoplayer-shared";var Gf=i=>{try{i.pause(),i.playbackRate=0,gA(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as vA,Subscription as SA}from"@vkontakte/videoplayer-shared";var bu=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)}},gu=window.WeakMap?new WeakMap:new bu,vu=window.WeakMap?new WeakMap:new Map,yA=(i,e=20)=>{let t=0;return vA(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},me=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Wf(t):(t=document.createElement("video"),i.appendChild(t)),gu.set(t,r);let a=new SA;return a.add(yA(t,e)),vu.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.setAttribute("x-yandex-pip","false"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},fe=i=>{vu.get(i)?.unsubscribe(),vu.delete(i);let t=gu.get(i);gu.delete(i),t?Wf(i):Gf(i)};var yu=D(Br(),1);import{assertNonNullable as Ei,isNonNullable as rt,isNullable as AA,fromEvent as Or,merge as eb,observableFrom as tb,filterChanged as rb,map as xi,Subject as ib,Subscription as LA,ValueSubject as RA,ErrorCategory as $A}from"@vkontakte/videoplayer-shared";import{isNonNullable as Su,isNullable as kA,Subscription as wA}from"@vkontakte/videoplayer-shared";var Ps=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=kA(a),l=new wA;return a&&l.add(a.subscribe(d=>{let c=i.getState();r(d,c)&&i.setState(d)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),u&&i.setState(d.to)},s)),l},tt=(i,e,t)=>Ps(e,()=>i.loop,r=>{Su(r)&&(i.loop=r)},{onError:t}),be=(i,e,t,r)=>Ps(e,()=>({muted:i.muted,volume:i.volume}),a=>{Su(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}),De=(i,e,t,r)=>Ps(e,()=>i.playbackRate,a=>{Su(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),xt=Ps;var MA=i=>["__",i.language,i.label].join("|"),DA=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Tu=class i{constructor(e){this.available$=new ib;this.current$=new RA(void 0);this.error$=new ib;this.subscription=new LA;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:$A.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,yu.default)(this.internalTracks),s=>{rt(s)&&this.setInternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(xi(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(xt(t.externalTextTracks,()=>(0,yu.default)(this.externalTracks),s=>{rt(s)&&this.setExternal(s)},{equal:(s,n)=>rt(s)&&rt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(xi(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(){Ei(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(eb(Or(e,"addtrack"),Or(e,"removetrack"),tb(["init"])).pipe(xi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),rb((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(eb(Or(e,"change"),tb(["init"])).pipe(xi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),xi(r=>r&&this.htmlTextTrackToITextTrack(r).id),rb()).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;rt(t.align)&&(a.align=t.align),rt(t.position)&&(a.position=t.position),rt(t.size)&&(a.size=t.size),rt(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){Ei(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:MA(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){Ei(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(AA(e)||!DA(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){Ei(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Ei(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)}},Ce=Tu;var dt=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 ab=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},Iu=i=>{let e=ab(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},sb=i=>{let e=ab(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Ve,map as Pt,merge as ob,filterChanged as VA,isNonNullable as ub,Subject as BA,filter as lb,mapTo as cb,combine as OA,once as _A,ErrorCategory as NA,ValueSubject as db,clientChecker as FA}from"@vkontakte/videoplayer-shared";var CA=3,nb=(i,e,t=CA)=>{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 ge=i=>{let e=x=>Ve(i,x).pipe(cb(void 0)),r=ob(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(x=>Ve(i,x))).pipe(Pt(x=>x.type==="ended"?i.readyState<2:i.readyState<3),VA()),a=ob(Ve(i,"progress"),Ve(i,"timeupdate")).pipe(Pt(()=>nb(i.buffered,i.currentTime))),s=FA.isSafari?OA({play:e("play").pipe(_A()),playing:e("playing")}).pipe(cb(void 0)):e("playing"),n=Ve(i,"volumechange").pipe(Pt(()=>({muted:i.muted,volume:i.volume}))),o=Ve(i,"ratechange").pipe(Pt(()=>i.playbackRate)),u=Ve(i,"error").pipe(lb(()=>!!(i.error||i.played.length)),Pt(()=>{let x=i.error;return{id:x?`MediaError#${x.code}`:"HtmlVideoError",category:NA.VIDEO_PIPELINE,message:x?x.message:"Error event from HTML video element",thrown:i.error??void 0}})),l=Ve(i,"timeupdate").pipe(Pt(()=>i.currentTime)),d=new BA,c=.3,p;l.subscribe(x=>{i.loop&&ub(p)&&ub(x)&&p>=i.duration-c&&x<=c&&d.next(p),p=x});let m=e("pause").pipe(lb(()=>!i.error&&p!==i.duration)),f=Ve(i,"enterpictureinpicture"),b=Ve(i,"leavepictureinpicture"),g=new db(sb(i));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new db(Iu(i));return Ve(i,"fullscreenchange").pipe(Pt(()=>Iu(i))).subscribe(v),{playing$:s,pause$:m,canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ve(i,"durationchange").pipe(Pt(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:f,leavePip$:b}};import{VideoQuality as kt}from"@vkontakte/videoplayer-shared";var wt=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 At=D(Zt(),1),wb=D(je(),1),As=D(Pr(),1);import{isNonNullable as we,isNullable as Eb,now as Ab,isHigher as xb,isHigherOrEqual as wu,isInvariantQuality as Pb,isLowerOrEqual as Au,videoSizeToQuality as JA,assertNotEmptyArray as Lb,assertNonNullable as ZA}from"@vkontakte/videoplayer-shared";var Eu=!1,pt={},vb=i=>{Eu=i},Sb=()=>{pt={}},yb=i=>{i(pt)},Pi=(i,e)=>{Eu&&(pt.meta=pt.meta??{},pt.meta[i]=e)},le=class{constructor(e){this.name=e}next(e){if(!Eu)return;pt.series=pt.series??{};let t=pt.series[this.name]??[];t.push([Date.now(),e]),pt.series[this.name]=t}};import{isHigher as zA,isHigherOrEqual as KA,isLower as Tb,isLowerOrEqual as XA,isNonNullable as ks,isNullable as xu}from"@vkontakte/videoplayer-shared";function Pu({limits:i,highQualityLimit:e,trafficSavingLimit:t}){return!i.max&&i.min===e?"high_quality":!i.min&&i.max===t?"traffic_saving":"unknown"}function ku({limits:i,highQualityLimit:e,trafficSavingLimit:t}){return!!i&&Pu({limits:i,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function ws({limits:i,highestAvailableQuality:e,lowestAvailableQuality:t}){return xu(i)||ks(i.min)&&ks(i.max)&&Tb(i.max,i.min)||ks(i.min)&&e&&zA(i.min,e)||ks(i.max)&&t&&Tb(i.max,t)}function Ib({limits:i,track:e}){return(xu(i?.max)||XA(e.quality,i.max))&&(xu(i?.min)||KA(e.quality,i.min))}var eL=new le("best_bitrate"),Rb=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var Lu=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),ki=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Ab()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},$b='Assertion "ABR Tracks is empty array" failed',Ls=(i,e,t,r)=>{let a=[...e].sort(Lu(1)),s=[...t].sort(Lu(1)),n=s.filter(u=>we(u.bitrate)&&we(i.bitrate)?i.bitrate/u.bitrate>r:!0),o=(0,At.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,At.default)(s,-1);return o&&(0,wb.default)(n,o)?o:n.length?(0,At.default)(n,-1):(0,At.default)(s,0)},kb=i=>"quality"in i,Mb=(i,e,t,r)=>{let a=we(r?.last?.bitrate)&&we(t?.bitrate)&&r.last.bitrate<t.bitrate?i.trackCooldownIncreaseQuality:i.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Ab()-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=kb(n)?"video":"audio",u=kb(n)?n.quality:n.bitrate;return e({message:`
|
|
8
8
|
[last ${o} selected] ${u}
|
|
9
|
-
`}),n}return r?.recordSwitch(t),t},tL=(i,e)=>Math.log(e)/Math.log(i),rL=({tuning:i,container:e,limits:t})=>{let r=i.containerSizeFactor;if(i.usePixelRatio&&window.devicePixelRatio){let a=window.devicePixelRatio;if(i.pixelRatioMultiplier)r*=i.pixelRatioMultiplier*(a-1)+1;else{let s=i.pixelRatioLogBase,[n=0,o=0,u=0]=i.pixelRatioLogCoefficients,l=tL(s,n*a+o)+u;Number.isFinite(l)&&(r*=l)}}return
|
|
9
|
+
`}),n}return r?.recordSwitch(t),t},tL=(i,e)=>Math.log(e)/Math.log(i),rL=({tuning:i,container:e,limits:t})=>{let r=i.containerSizeFactor;if(i.usePixelRatio&&window.devicePixelRatio){let a=window.devicePixelRatio;if(i.pixelRatioMultiplier)r*=i.pixelRatioMultiplier*(a-1)+1;else{let s=i.pixelRatioLogBase,[n=0,o=0,u=0]=i.pixelRatioLogCoefficients,l=tL(s,n*a+o)+u;Number.isFinite(l)&&(r*=l)}}return ku({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:t})&&(r*=2),{containerSizeLimit:i.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Lt=(i,{container:e,estimatedThroughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:m,abrLogger:f})=>{Lb(i,$b);let{containerSizeFactor:b,containerSizeLimit:g}=rL({container:e,tuning:r,limits:a}),v=r.considerPlaybackRate&&we(o)?o:1,k=i.filter(S=>!Pb(S.quality)).sort((S,P)=>xb(S.quality,P.quality)?-1:1),x=(0,At.default)(k,-1)?.quality,R=(0,At.default)(k,0)?.quality,y=ws({limits:a,lowestAvailableQuality:x,highestAvailableQuality:R}),I=v*Rb(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),A={},N=k.filter(S=>{let P=!0;if(g)if(S.size)P=S.size.width<=g.width&&S.size.height<=g.height;else{let $e=g&&JA(g);P=$e?Au(S.quality,$e):!0}if(!P)return A[S.quality]="FitsContainer",!1;let U=m||t,Le=we(U)&&isFinite(U)&&we(S.bitrate)?U-s>=S.bitrate*I:!0,Re=ku({highQualityLimit:r.highQualityLimit,trafficSavingLimit:r.trafficSavingLimit,limits:a})&&a?.min===S.quality;if(!Le&&!Re)return A[S.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&we(r.minBufferToSwitchUp)&&u&&!Pb(u.quality)&&(n??0)<r.minBufferToSwitchUp&&xb(S.quality,u.quality))return A[S.quality]="Buffer",!1;if(!!c&&wu(S.quality,c)&&!Re)return A[S.quality]="DroppedFramesLimit",!1;if(!!p&&wu(S.quality,p)&&!Re)return A[S.quality]="StallsLimit",!1;let L=y||(Eb(a?.max)||Au(S.quality,a.max))&&(Eb(a?.min)||wu(S.quality,a.min)),G=we(d)&&!d?Au(S.quality,r.backgroundVideoQualityLimit):!0;return!L||!G?(A[S.quality]="FitsQualityLimits",!1):!0})[0];N&&N.bitrate&&eL.next(N.bitrate);let q=N??(0,At.default)(k,-1)??i[0];return q.quality!==l?.last?.quality&&f({message:`
|
|
10
10
|
[VIDEO TRACKS ABR]
|
|
11
11
|
[available video tracks]
|
|
12
12
|
${i.map(S=>`{ id: ${S.id}, quality: ${S.quality}, bitrate: ${S.bitrate}, size: ${S.size?.width}:${S.size?.height} }`).join(`
|
|
@@ -39,14 +39,14 @@ var Ty=Object.create;var Ul=Object.defineProperty;var Iy=Object.getOwnPropertyDe
|
|
|
39
39
|
|
|
40
40
|
[best video track] ${N?.quality}
|
|
41
41
|
[selected video track] ${q?.quality}
|
|
42
|
-
`}),Mb(r,f,q,l)},Db=(i,e,t,{estimatedThroughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Lb(t,$b);let d=a.considerPlaybackRate&&
|
|
42
|
+
`}),Mb(r,f,q,l)},Db=(i,e,t,{estimatedThroughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Lb(t,$b);let d=a.considerPlaybackRate&&we(s)?s:1,c=[...t].sort(Lu(-1)),p=i.bitrate;ZA(p);let m=d*Rb(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),f,b=Ls(i,e,t,a.minVideoAudioRatio),g=l||r;return we(g)&&isFinite(g)&&(f=c.find(v=>we(v.bitrate)&&we(b?.bitrate)?g-p>=v.bitrate*m&&v.bitrate>=b.bitrate:!1)),f||(f=b),f?.bitrate!==o?.last?.bitrate&&u({message:`
|
|
43
43
|
[AUDIO TRACKS ABR]
|
|
44
44
|
[available audio tracks]
|
|
45
45
|
${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
|
|
46
46
|
`)}
|
|
47
47
|
|
|
48
48
|
[tuning]
|
|
49
|
-
${(0,As.default)(a??{}).map(([v,
|
|
49
|
+
${(0,As.default)(a??{}).map(([v,k])=>`${v}: ${k}`).join(`
|
|
50
50
|
`)}
|
|
51
51
|
|
|
52
52
|
[limit params]
|
|
@@ -60,14 +60,14 @@ var Ty=Object.create;var Ul=Object.defineProperty;var Iy=Object.getOwnPropertyDe
|
|
|
60
60
|
minBufferToSwitchUp: ${a.minBufferToSwitchUp},
|
|
61
61
|
|
|
62
62
|
[selected audio track] ${f?.id}
|
|
63
|
-
`}),f&&Mb(a,u,f,o)};var Z=i=>new URL(i).hostname;import{assertNever as Hb,assertNonNullable as jb,combine as EL,debounce as xL,ErrorCategory as Qb,filter as Gb,filterChanged as PL,isNonNullable as Cu,map as Cs,merge as Wb,observableFrom as wL,once as kL,Subscription as AL,ValueSubject as Vu,videoQualityToHeight as LL,videoSizeToQuality as RL}from"@vkontakte/videoplayer-shared";var Vb=D(je(),1),Cb=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"))},ve=async(i,e)=>{let t=i.muted;try{await i.play()}catch(r){if(!Cb(r))return!1;if(e&&e(),t)return console.warn(r),!1;i.muted=!0;try{await i.play()}catch(a){return Cb(a)&&(i.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as $s,isNullable as sL,assertNonNullable as Li}from"@vkontakte/videoplayer-shared";var Ob=D(Br(),1);import{isNonNullable as Bb,assertNonNullable as Rs,now as iL}from"@vkontakte/videoplayer-shared";function ee(){return iL()}function Ru(i){return ee()-i}function $u(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 _b(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function _r(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,m="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Rs(d);let P=Ru(d),U;if(P<b){U=b-P,setTimeout(g,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,I()},v=P=>(s=P,S),w=P=>(c=P,S),x=()=>(m="json",S),R=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,c&&c(),t&&t()}},y=P=>(p=P,S),I=()=>{d=ee(),n=new a,n.open("get",i);let P=0,U,Le=0,Re=()=>(Rs(d),Math.max(d,Math.max(U||0,Le||0)));if(s&&n.addEventListener("progress",k=>{let B=ee();s.updateChunk&&k.loaded>P&&(s.updateChunk(Re(),k.loaded-P),P=k.loaded,U=B)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>R())),n.addEventListener("load",()=>{if(u)return;Rs(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let B=n.response.byteLength-P;B&&s.updateChunk&&s.updateChunk(Re(),B)}n.responseType==="json"&&!(0,Ob.default)(n.response).length?R():(c&&c(),e(n.response))}else R()}),n.addEventListener("error",()=>{R()}),p){let k=()=>{Rs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Le=ee(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=m,n.send(),S},S={withBitrateReporting:v,withParallel:y,withJSONResponse:x,withRetryCount:P=>(l=P,S),withRetryInterval:(P,U)=>(Bb(P)&&(b=P),Bb(U)&&(f=U),S),withTimeout:P=>(o=P,S),withFinally:w,send:I,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return S}var ki=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 Nb=D(Br(),1);var Ai=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=_r(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,Nb.default)(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 nL}from"@vkontakte/videoplayer-shared";var Ms=1e4,Mu=3;var oL=6e4,uL=10,lL=1,cL=500,Ri=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 nL,this.chunkRateEstimator=new ki(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=$u(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=$u(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||$s(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=()=>{_b(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 Ai(Mu,Ms,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,d=!1,c=()=>{let R=s&&(!d||d===this.rep);return R||t("Not running!"),R},p=(R,y,I)=>{u&&u.abort(),u=_r(this.urlResolver.resolve(R,!1),y,I,()=>this._retryCallback()).withTimeout(Ms).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Mu).withFinally(()=>{u=null}).send()},m=(R,y,I)=>{Li(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(R,!1),y,I,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=R=>{let y=r.playbackRate;r.playbackRate!==R&&(t(`Playback rate switch: ${y}=>${R}`),r.playbackRate=R)},b=R=>{this.lowLatency=R,t(`lowLatency changed to ${R}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let R=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let I=ee()-1e4,A=0;for(let N=0;N<this.bufferStates.length;N++){let q=this.bufferStates[N];R=Math.min(R,q.buf),q.ts<I&&A++}this.bufferStates.splice(0,A),t(`update playback rate; minBuffer=${R} drop=${A} jitter=${this.sourceJitter}`);let Q=R-lL;this.sourceJitter>=0?Q-=this.sourceJitter/2:this.sourceJitter-=1,Q>3?f(1.15):Q>1?f(1.1):Q>.3?f(1.05):f(1)}},v=R=>{let y,I=()=>y&&y.start?y.start.length:0,A=k=>y.start[k]/1e3,Q=k=>y.dur[k]/1e3,N=k=>y.fragIndex+k,q=(k,B)=>({chunkIdx:N(k),startTS:A(k),dur:Q(k),discontinuity:B}),S=()=>{let k=0;if(y&&y.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,F=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,L=B;this.sourceJitter>1&&(L+=this.sourceJitter-1);let G=y.dur.length-1;for(;G>=0&&(L-=y.dur[G],!(L<=0));--G);k=Math.min(G,y.dur.length-1-F),k=Math.max(k,0)}return q(k,!0)},P=k=>{let B=I();if(!(B<=0)){if($s(k)){for(let F=0;F<B;F++)if(A(F)>k)return q(F)}return S()}},U=k=>{let B=I(),F=k?k.chunkIdx+1:0,L=F-y.fragIndex;if(!(B<=0)){if(!k||L<0||L-B>uL)return t(`Resync: offset=${L} bChunks=${B} chunk=`+JSON.stringify(k)),S();if(!(L>=B))return q(F-y.fragIndex,!1)}},Le=(k,B,F)=>{l&&l.abort(),l=_r(this.urlResolver.resolve(k,!0,this.lowLatency),B,F,()=>this._retryCallback()).withTimeout(Ms).withRetryCount(Mu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,B)=>{Le(R,F=>{if(!c())return;y=F;let L=!!y.lowLatency;L!==this.lowLatency&&b(L);let G=0;for(let $e=0;$e<y.dur.length;++$e)G+=y.dur[$e];G>0&&(Li(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(G/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(P(B))},()=>this._handleNetworkError())},nextChunk:U}},w=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Li(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:R=>{let{videoElement:y,logger:I}=this.params,A=v(e.jidxUrl),Q,N,q,S,P=0,U,Le,Re,k=()=>{U&&(clearTimeout(U),U=void 0);let C=Math.max(cL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),te=P+C,oe=ee(),X=Math.min(1e4,te-oe);P=oe;let Ke=()=>{l||c()&&A.seek(()=>{c()&&(P=ee(),B(),k())})};X>0?U=window.setTimeout(()=>{this.paused?k():Ke()},X):Ke()},B=()=>{let C;for(;C=A.nextChunk(S);)S=C,cr(C);let te=A.nextChunk(q);if(te){if(q&&te.discontinuity){I("Detected discontinuity; restarting playback"),this.paused?k():(w(),this._initPlayerWith(e));return}$e(te)}else k()},F=(C,te)=>{if(!c()||!this.sourceBuffer)return;let oe,X,Ke,Oe=_e=>{window.setTimeout(()=>{c()&&F(C,te)},_e)};if(this.sourceBuffer.updating)I("Source buffer is updating; delaying appendBuffer"),Oe(100);else{let _e=ee(),st=y.currentTime;!this.paused&&y.buffered.length>1&&Le===st&&_e-Re>500&&(I("Stall suspected; trying to fix"),this._fixupStall()),Le!==st&&(Le=st,Re=_e);let gt=this._getBufferSizeSec();if(gt>30)I(`Buffered ${gt} seconds; delaying appendBuffer`),Oe(2e3);else try{this.sourceBuffer.appendBuffer(C),this.videoPlayStarted?(this.bufferStates.push({ts:_e,buf:gt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),te&&te()}catch(nt){if(nt.name==="QuotaExceededError")I("QuotaExceededError; delaying appendBuffer"),Ke=this.sourceBuffer.buffered.length,Ke!==0&&(oe=this.sourceBuffer.buffered.start(0),X=st,X-oe>4&&this.sourceBuffer.remove(oe,X-3)),Oe(1e3);else throw nt}}},L=()=>{N&&Q&&(I([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(q)]),F(N,function(){N=null,B()}))},G=C=>e.fragUrlTemplate.replace("%%id%%",C.chunkIdx),$e=C=>{c()&&m(G(C),(te,oe)=>{if(c()){if(oe/=1e3,N=te,q=C,n=C.startTS,oe){let X=Math.min(10,C.dur/oe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*X:X}L()}},()=>this._handleNetworkError())},cr=C=>{c()&&(Li(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(G(C),!1)))},ze=C=>{c()&&(e.cachedHeader=C,F(C,()=>{Q=!0,L()}))};s=!0,A.seek(C=>{if(c()){if(P=ee(),!C){k();return}S=C,!sL(R)||C.startTS>R?$e(C):(q=C,B())}},R),e.cachedHeader?ze(e.cachedHeader):p(e.headerUrl,ze,()=>this._handleNetworkError())},stop:w,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),$s(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,Li(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return $s(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=c=>{if(!this.autoQuality)return;let p,m,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(m=this._getBufferSizeSec(),f=c/this.bitrate,m>10&&f>.8||m>15&&f>.5||m>20&&f>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,m)=>{let f=ee();if(this.chunkRateEstimator.addInterval(p,f,m)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,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 c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Ru(n)<3e4)return;r(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let m=s.updateChunk(c,p);return m&&l(),m},notifySwitch:c=>{let p=ee();c<o&&(n=p),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=_r(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ms).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;ve(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))},oL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ub=D(Pr(),1);import{debounce as dL,filter as Fb,fromEvent as pL,interval as hL,isHigher as mL,isInvariantQuality as fL,isLower as bL,merge as gL,Subject as qb,Subscription as vL}from"@vkontakte/videoplayer-shared";var Du=class{constructor(){this.onDroopedVideoFramesLimit$=new qb;this.subscription=new vL;this.playing=!1;this.tracks=[];this.forceChecker$=new qb;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&&!fL(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&&mL(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(pL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=hL(this.droppedFramesChecker.checkTime).pipe(Fb(()=>this.playing),Fb(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(dL(this.droppedFramesChecker.checkTime)),r=gL(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,Ub.default)(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>bL(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}},Ds=Du;import{map as SL,Observable as yL}from"@vkontakte/videoplayer-shared";import{fromEvent as TL}from"@vkontakte/videoplayer-shared";var $i=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var IL=(i,e)=>new yL(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||$i()))},{...r,...e});a.observe(i);let s=TL(document,"visibilitychange").pipe(SL(n=>!document.hidden||$i())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Be=IL;var $L=["paused","playing","ready"],ML=["paused","playing","ready"],Mi=class{constructor(e){this.subscription=new AL;this.videoState=new $("stopped");this.representations$=new Vu([]);this.droppedFramesManager=new Ds;this.maxSeekBackTime$=new Vu(1/0);this.zeroTime$=new Vu(void 0);this.liveOffset=new dt;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:Qb.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=kt(a.name)??RL(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),Cu(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,Bu.default)(ML,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,Bu.default)($L,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(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(ae(this.params.source.url,u))}return;default:return Hb(e)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Qb.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Wb(this.videoState.stateChangeStarted$.pipe(Cs(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Cs(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=me(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=ge(this.video);this.subscription.add(this.representations$.pipe(Cs(a=>a.map(({track:s})=>s)),Gb(a=>!!a.length),kL()).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(PL(),Cs(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(EL({zeroTime:this.zeroTime$.pipe(Gb(Cu)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(tt(this.video,this.params.desiredState.isLooped,t)).add(be(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(De(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(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&LL(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 Hb(a.to)}},t)).add(Wb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,wL(["init"])).pipe(xL(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),fe(this.video)}createLiveDashPlayer(){let e=new Ri({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&&Cu(t)?t:Lt(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:d})=>d.id===s)?.representation;jb(l,"Representations missing"),this.dash.startPlay(l,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;jb(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(ae(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Yb=Mi;var TS=D(je(),1);var it=(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 yM,assertNonNullable as TM,debounce as IM,ErrorCategory as Il,filter as vS,filterChanged as Ia,fromEvent as EM,isNonNullable as SS,map as El,merge as rn,observableFrom as xl,once as yS,Subscription as xM}from"@vkontakte/videoplayer-shared";var Vs=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}},Nr=class extends Vs{constructor(){super(),this.listeners||Vs.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)}},Di=class{constructor(){Object.defineProperty(this,"signal",{value:new Nr,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&&(Di.prototype[Symbol.toStringTag]="AbortController",Nr.prototype[Symbol.toStringTag]="AbortSignal");function Bs(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 Ou(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Bs({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,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((m,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Ci=Bs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zb=Ci?Ou({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ge=Ci?zb.fetch:window.fetch,tN=Ci?zb.Request:window.Request,se=Ci?Di:window.AbortController,rN=Ci?Nr:window.AbortSignal;var vl=D(Nu(),1);var Ns=D(Zt(),1);var ht=()=>window.ManagedMediaSource||window.MediaSource,Os=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),fg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),bg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Us,clientChecker as Fs}from"@vkontakte/videoplayer-shared";var qs=document.createElement("video"),iR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',aR='video/mp4; codecs="hev1.1.6.L93.B0"',gg='video/webm; codecs="vp09.00.10.08"',vg='video/webm; codecs="av01.0.00M.08"',sR='audio/mp4; codecs="mp4a.40.2"',nR='audio/webm; codecs="opus"',Vi={mms:Os(),mse:fg(),hls:!!(qs.canPlayType?.("application/x-mpegurl")||qs.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Se={mp4:!!qs.canPlayType?.("video/mp4"),webm:!!qs.canPlayType?.("video/webm"),cmaf:!0},ye={h264:!!ht()?.isTypeSupported?.(iR),h265:!!ht()?.isTypeSupported?.(aR),vp9:!!ht()?.isTypeSupported?.(gg),av1:!!ht()?.isTypeSupported?.(vg),aac:!!ht()?.isTypeSupported?.(sR),opus:!!ht()?.isTypeSupported?.(nR)},Fr=(ye.h264||ye.h265)&&ye.aac,er,oR=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:vg}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:gg}})]);er={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{oR()}catch(i){console.error(i)}var qr=Vi.hls&&Se.mp4,Sg=()=>Object.keys(ye).filter(i=>ye[i]),yg=(i,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let a=Vi.mse&&(!r||!!window.MediaStreamTrack)||Vi.mms&&t;return i.filter(s=>{switch(s){case"DASH_SEP":return a&&Se.mp4&&Fr;case"DASH_WEBM":return a&&Se.webm&&ye.vp9&&ye.opus;case"DASH_WEBM_AV1":return a&&Se.webm&&ye.av1&&ye.opus;case"DASH_STREAMS":return a&&(Se.mp4&&Fr||Se.webm&&(ye.vp9||ye.av1)&&(ye.opus||ye.aac));case"DASH_LIVE":return a&&Se.mp4&&Fr;case"DASH_LIVE_CMAF":return a&&Se.mp4&&Fr&&Se.cmaf;case"DASH_ONDEMAND":return a&&Se.mp4&&Fr;case"HLS":case"HLS_ONDEMAND":return qr||e&&a&&Se.mp4&&Fr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return qr;case"MPEG":return Se.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Vi.webrtc&&Vi.ws&&ye.h264&&(Se.mp4||Se.webm);default:return Us(s)}})},_s=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 er?er[t].smooth?[t,e]:er[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return er?er[t].powerEfficient?[t,e]:er[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Us(i)}return[e,t]},Tg=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],..._s(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Fs.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",..._s(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[..._s(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",..._s(i),...a,"HLS","HLS_ONDEMAND"];default:Us(e)}return qr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Ig=({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=Fs.isMac&&Fs.isSafari;if(Fs.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:Us(i)}else qr&&!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"]},Fu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Eg=i=>{if(i.size===0)return;if(i.size===1){let t=i.values().next();return(0,Ns.default)(t.value.split("."),0)}for(let t of i){let r=(0,Ns.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=i.values().next();return(0,Ns.default)(e.value.split("."),0)};var jg=D(Hg(),1);import{ErrorCategory as Oi}from"@vkontakte/videoplayer-shared";var Qg=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,jg.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 Rt=(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 bl,assertNonNullable as nr,clientChecker as eM,combine as Wr,ErrorCategory as Vt,filter as va,filterChanged as Ks,flattenObject as Sa,fromEvent as or,getTraceSubscriptionMethod as tM,interval as gl,isNonNullable as cS,map as ya,merge as ur,now as rM,Subject as dS,Subscription as pS,tap as iM,throttle as aM,ValueSubject as z}from"@vkontakte/videoplayer-shared";var js=D(je(),1),Qr=D(Zt(),1),Qs=D(Nu(),1);var xR=(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)},PR=i=>window.clearTimeout(i),Gg=i=>typeof i=="function"&&i?.toString().endsWith("{ [native code] }"),Wg=!Gg(window.requestIdleCallback)||!Gg(window.cancelIdleCallback),Qu=Wg?xR:window.requestIdleCallback,_i=Wg?PR:window.cancelIdleCallback;var rS=D(Is(),1);import{assertNever as wR,ErrorCategory as Yg,clientChecker as Gu,Subject as zg}from"@vkontakte/videoplayer-shared";var kR=18,Kg=!1;try{Kg=Gu.isSafari&&!!Gu.macVersion&&Gu.macVersion<=kR}catch(i){console.error(i)}var Wu=class{constructor(e){this.bufferFull$=new zg;this.error$=new zg;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Yg.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,a=s=>{this.abortRequested=!1,t(s)};Kg&&e?r={operation:"safariAbort",init:e,callback:a}:r={operation:"abort",callback:a};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,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)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:Yg.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:wR(t)}}},Xg=Wu;var Yu=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 Mt,assertNonNullable as Te,clientChecker as H$,ErrorCategory as Dt,fromEvent as dl,getExponentialDelay as pl,isNonNullable as jr,isNullable as ne,now as Hs,once as j$,Subject as Q$,Subscription as G$,ValueSubject as ir}from"@vkontakte/videoplayer-shared";var V=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)}get id(){return this.type}get size(){return this.size32}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 Ur=class extends V{};var Ni=class extends V{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 Fi=class extends V{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 qi=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var j=class extends V{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ui=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 Hi=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ji=class extends V{constructor(e,t){super(e,t),this.data=this.content}};var tr=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 Qi=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gi=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wi=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 Yi=class extends j{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var zi=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 Ki=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xi=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 Ji=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zi=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ea=class extends j{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ta=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ra=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 ia=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 aa=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 sa=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var na=class extends j{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var oa=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var LR={ftyp:Fi,moov:qi,mvhd:Ui,moof:Hi,mdat:ji,sidx:tr,trak:Qi,mdia:Ki,mfhd:ea,tkhd:Xi,traf:ta,tfhd:ra,tfdt:ia,trun:aa,minf:Ji,sv3d:Gi,st3d:Wi,prhd:Yi,proj:Zi,equi:zi,uuid:Ni,stbl:sa,stsd:na,avc1:oa,unknown:Ur},mt=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=LR[e];return r?new r(t,new i):new Ur(t,new i)}};var $t=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 $R=new TextDecoder("ascii"),MR=i=>$R.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",DR=i=>{let e=new tr(i,new mt),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})},CR=(i,e)=>{let r=new mt().parse(i),a=new $t(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,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,c)},VR=i=>{let t=new mt().parse(i),r=new $t(t),a={},s=r.findAll("uuid");return s.length?s[s.length-1]:a},BR=i=>{let t=new mt().parse(i);return new $t(t).find("sidx")?.timescale},OR=(i,e)=>{let r=new mt().parse(i),s=new $t(r).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},_R=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 mt().parse(i),a=new $t(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},Jg={validateData:MR,parseInit:_R,getIndexRange:()=>{},parseSegments:DR,parseFeedableSegmentChunk:CR,getChunkEndTime:OR,getServerLatencyTimestamps:VR,getTimescaleFromIndex:BR};var la=D(je(),1);import{assertNonNullable as Ku,isNonNullable as rv,isNullable as FR}from"@vkontakte/videoplayer-shared";import{assertNever as NR}from"@vkontakte/videoplayer-shared";var Zg={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"}},ev=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=ua(i,t),a=r in Zg,s=a?Zg[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,d=ua(u),c=l*2**((o-1)*8)+d,p=t+o,m;return p+c>i.byteLength?m=new DataView(i.buffer,i.byteOffset+p):m=new DataView(i.buffer,i.byteOffset+p,c),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:m,valueSize:c}},ua=(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},We=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return ua(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:NR(e)}},rr=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=ev(r);if(!e(a))return;a.type==="master"&&rr(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},tv=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=ev(i);return rr(a.value,({tag:s,type:n,value:o})=>(s===17143?e=We(o,n):s===17026?t=We(o,n):s===17029&&(r=We(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var iv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],qR=[231,22612,22743,167,171,163,160,175],UR=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return rr(i,({tag:p,type:m,value:f,valueSize:b})=>{if(p===21419){let g=We(f,m);l=ua(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=We(f,m):p===17545?a=We(f,m):p===21420&&l===475249515?u=We(f,m):p===374648427?rr(f,({tag:g,type:v,value:w})=>g===30321?(d=We(w,v)===1,!1):!0):s&&n&&(0,la.default)(iv,p)&&(o=!0),!o}),Ku(e,"Failed to parse webm Segment start"),Ku(t,"Failed to parse webm Segment end"),Ku(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:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},HR=i=>{if(FR(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},jR=(i,e)=>{let t=!1,r=!1,a=o=>rv(o.time)&&rv(o.position),s=[],n;return rr(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=We(l,u));break;case 183:break;case 241:n&&(n.position=We(l,u));break;default:t&&(0,la.default)(iv,o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},QR=i=>{let e=0,t=!1;try{rr(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,la.default)(qR,r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=(0,la.default)([163,160,175],r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},av={validateData:tv,parseInit:UR,getIndexRange:HR,parseSegments:jR,parseFeedableSegmentChunk:QR};var ca=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return av;case"mp4":return Jg}}throw new ReferenceError(`Unsupported mime type ${i}`)};var ul=D(xv(),1),Kv=D(Pr(),1),Xv=D(Fv(),1),Jv=D(Zt(),1),ll=D(Br(),1);var qv=D(je(),1),rl=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,qv.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as U$,isNullable as Yv}from"@vkontakte/videoplayer-shared";var Uv=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Hv=i=>{try{let e=F$(),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 F$(){let i="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
63
|
+
`}),f&&Mb(a,u,f,o)};var Z=i=>new URL(i).hostname;import{assertNever as Hb,assertNonNullable as jb,combine as EL,debounce as xL,ErrorCategory as Qb,filter as Gb,filterChanged as PL,isNonNullable as Cu,map as Cs,merge as Wb,observableFrom as kL,once as wL,Subscription as AL,ValueSubject as Vu,videoQualityToHeight as LL,videoSizeToQuality as RL}from"@vkontakte/videoplayer-shared";var Vb=D(je(),1),Cb=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"))},ve=async(i,e)=>{let t=i.muted;try{await i.play()}catch(r){if(!Cb(r))return!1;if(e&&e(),t)return console.warn(r),!1;i.muted=!0;try{await i.play()}catch(a){return Cb(a)&&(i.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as $s,isNullable as sL,assertNonNullable as Li}from"@vkontakte/videoplayer-shared";var Ob=D(Br(),1);import{isNonNullable as Bb,assertNonNullable as Rs,now as iL}from"@vkontakte/videoplayer-shared";function ee(){return iL()}function Ru(i){return ee()-i}function $u(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 _b(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function _r(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,d,c,p=!1,m="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Rs(d);let P=Ru(d),U;if(P<b){U=b-P,setTimeout(g,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,I()},v=P=>(s=P,S),k=P=>(c=P,S),x=()=>(m="json",S),R=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,c&&c(),t&&t()}},y=P=>(p=P,S),I=()=>{d=ee(),n=new a,n.open("get",i);let P=0,U,Le=0,Re=()=>(Rs(d),Math.max(d,Math.max(U||0,Le||0)));if(s&&n.addEventListener("progress",w=>{let B=ee();s.updateChunk&&w.loaded>P&&(s.updateChunk(Re(),w.loaded-P),P=w.loaded,U=B)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>R())),n.addEventListener("load",()=>{if(u)return;Rs(n);let w=n.status;if(w>=200&&w<300){if(n.response.byteLength&&s){let B=n.response.byteLength-P;B&&s.updateChunk&&s.updateChunk(Re(),B)}n.responseType==="json"&&!(0,Ob.default)(n.response).length?R():(c&&c(),e(n.response))}else R()}),n.addEventListener("error",()=>{R()}),p){let w=()=>{Rs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Le=ee(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=m,n.send(),S},S={withBitrateReporting:v,withParallel:y,withJSONResponse:x,withRetryCount:P=>(l=P,S),withRetryInterval:(P,U)=>(Bb(P)&&(b=P),Bb(U)&&(f=U),S),withTimeout:P=>(o=P,S),withFinally:k,send:I,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return S}var wi=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 Nb=D(Br(),1);var Ai=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=_r(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,Nb.default)(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 nL}from"@vkontakte/videoplayer-shared";var Ms=1e4,Mu=3;var oL=6e4,uL=10,lL=1,cL=500,Ri=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 nL,this.chunkRateEstimator=new wi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=$u(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=$u(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||$s(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=()=>{_b(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 Ai(Mu,Ms,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,d=!1,c=()=>{let R=s&&(!d||d===this.rep);return R||t("Not running!"),R},p=(R,y,I)=>{u&&u.abort(),u=_r(this.urlResolver.resolve(R,!1),y,I,()=>this._retryCallback()).withTimeout(Ms).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Mu).withFinally(()=>{u=null}).send()},m=(R,y,I)=>{Li(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(R,!1),y,I,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=R=>{let y=r.playbackRate;r.playbackRate!==R&&(t(`Playback rate switch: ${y}=>${R}`),r.playbackRate=R)},b=R=>{this.lowLatency=R,t(`lowLatency changed to ${R}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let R=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let I=ee()-1e4,A=0;for(let N=0;N<this.bufferStates.length;N++){let q=this.bufferStates[N];R=Math.min(R,q.buf),q.ts<I&&A++}this.bufferStates.splice(0,A),t(`update playback rate; minBuffer=${R} drop=${A} jitter=${this.sourceJitter}`);let Q=R-lL;this.sourceJitter>=0?Q-=this.sourceJitter/2:this.sourceJitter-=1,Q>3?f(1.15):Q>1?f(1.1):Q>.3?f(1.05):f(1)}},v=R=>{let y,I=()=>y&&y.start?y.start.length:0,A=w=>y.start[w]/1e3,Q=w=>y.dur[w]/1e3,N=w=>y.fragIndex+w,q=(w,B)=>({chunkIdx:N(w),startTS:A(w),dur:Q(w),discontinuity:B}),S=()=>{let w=0;if(y&&y.dur){let B=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,F=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,L=B;this.sourceJitter>1&&(L+=this.sourceJitter-1);let G=y.dur.length-1;for(;G>=0&&(L-=y.dur[G],!(L<=0));--G);w=Math.min(G,y.dur.length-1-F),w=Math.max(w,0)}return q(w,!0)},P=w=>{let B=I();if(!(B<=0)){if($s(w)){for(let F=0;F<B;F++)if(A(F)>w)return q(F)}return S()}},U=w=>{let B=I(),F=w?w.chunkIdx+1:0,L=F-y.fragIndex;if(!(B<=0)){if(!w||L<0||L-B>uL)return t(`Resync: offset=${L} bChunks=${B} chunk=`+JSON.stringify(w)),S();if(!(L>=B))return q(F-y.fragIndex,!1)}},Le=(w,B,F)=>{l&&l.abort(),l=_r(this.urlResolver.resolve(w,!0,this.lowLatency),B,F,()=>this._retryCallback()).withTimeout(Ms).withRetryCount(Mu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,B)=>{Le(R,F=>{if(!c())return;y=F;let L=!!y.lowLatency;L!==this.lowLatency&&b(L);let G=0;for(let $e=0;$e<y.dur.length;++$e)G+=y.dur[$e];G>0&&(Li(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(G/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,w(P(B))},()=>this._handleNetworkError())},nextChunk:U}},k=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Li(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:R=>{let{videoElement:y,logger:I}=this.params,A=v(e.jidxUrl),Q,N,q,S,P=0,U,Le,Re,w=()=>{U&&(clearTimeout(U),U=void 0);let C=Math.max(cL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),te=P+C,oe=ee(),X=Math.min(1e4,te-oe);P=oe;let Ke=()=>{l||c()&&A.seek(()=>{c()&&(P=ee(),B(),w())})};X>0?U=window.setTimeout(()=>{this.paused?w():Ke()},X):Ke()},B=()=>{let C;for(;C=A.nextChunk(S);)S=C,cr(C);let te=A.nextChunk(q);if(te){if(q&&te.discontinuity){I("Detected discontinuity; restarting playback"),this.paused?w():(k(),this._initPlayerWith(e));return}$e(te)}else w()},F=(C,te)=>{if(!c()||!this.sourceBuffer)return;let oe,X,Ke,Oe=_e=>{window.setTimeout(()=>{c()&&F(C,te)},_e)};if(this.sourceBuffer.updating)I("Source buffer is updating; delaying appendBuffer"),Oe(100);else{let _e=ee(),st=y.currentTime;!this.paused&&y.buffered.length>1&&Le===st&&_e-Re>500&&(I("Stall suspected; trying to fix"),this._fixupStall()),Le!==st&&(Le=st,Re=_e);let gt=this._getBufferSizeSec();if(gt>30)I(`Buffered ${gt} seconds; delaying appendBuffer`),Oe(2e3);else try{this.sourceBuffer.appendBuffer(C),this.videoPlayStarted?(this.bufferStates.push({ts:_e,buf:gt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),te&&te()}catch(nt){if(nt.name==="QuotaExceededError")I("QuotaExceededError; delaying appendBuffer"),Ke=this.sourceBuffer.buffered.length,Ke!==0&&(oe=this.sourceBuffer.buffered.start(0),X=st,X-oe>4&&this.sourceBuffer.remove(oe,X-3)),Oe(1e3);else throw nt}}},L=()=>{N&&Q&&(I([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(q)]),F(N,function(){N=null,B()}))},G=C=>e.fragUrlTemplate.replace("%%id%%",C.chunkIdx),$e=C=>{c()&&m(G(C),(te,oe)=>{if(c()){if(oe/=1e3,N=te,q=C,n=C.startTS,oe){let X=Math.min(10,C.dur/oe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*X:X}L()}},()=>this._handleNetworkError())},cr=C=>{c()&&(Li(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(G(C),!1)))},ze=C=>{c()&&(e.cachedHeader=C,F(C,()=>{Q=!0,L()}))};s=!0,A.seek(C=>{if(c()){if(P=ee(),!C){w();return}S=C,!sL(R)||C.startTS>R?$e(C):(q=C,B())}},R),e.cachedHeader?ze(e.cachedHeader):p(e.headerUrl,ze,()=>this._handleNetworkError())},stop:k,getTimestampSec:()=>n},d}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),$s(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,Li(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return $s(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=c=>{if(!this.autoQuality)return;let p,m,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(m=this._getBufferSizeSec(),f=c/this.bitrate,m>10&&f>.8||m>15&&f>.5||m>20&&f>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}p=this._selectQuality(c),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${c}`)},s={updateChunk:(p,m)=>{let f=ee();if(this.chunkRateEstimator.addInterval(p,f,m)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,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 c=s.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Ru(n)<3e4)return;r(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let m=s.updateChunk(c,p);return m&&l(),m},notifySwitch:c=>{let p=ee();c<o&&(n=p),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=_r(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ms).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;ve(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))},oL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ub=D(Pr(),1);import{debounce as dL,filter as Fb,fromEvent as pL,interval as hL,isHigher as mL,isInvariantQuality as fL,isLower as bL,merge as gL,Subject as qb,Subscription as vL}from"@vkontakte/videoplayer-shared";var Du=class{constructor(){this.onDroopedVideoFramesLimit$=new qb;this.subscription=new vL;this.playing=!1;this.tracks=[];this.forceChecker$=new qb;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&&!fL(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&&mL(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(pL(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=hL(this.droppedFramesChecker.checkTime).pipe(Fb(()=>this.playing),Fb(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(dL(this.droppedFramesChecker.checkTime)),r=gL(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,Ub.default)(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>bL(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}},Ds=Du;import{map as SL,Observable as yL}from"@vkontakte/videoplayer-shared";import{fromEvent as TL}from"@vkontakte/videoplayer-shared";var $i=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var IL=(i,e)=>new yL(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||$i()))},{...r,...e});a.observe(i);let s=TL(document,"visibilitychange").pipe(SL(n=>!document.hidden||$i())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Be=IL;var $L=["paused","playing","ready"],ML=["paused","playing","ready"],Mi=class{constructor(e){this.subscription=new AL;this.videoState=new $("stopped");this.representations$=new Vu([]);this.droppedFramesManager=new Ds;this.maxSeekBackTime$=new Vu(1/0);this.zeroTime$=new Vu(void 0);this.liveOffset=new dt;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:Qb.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=wt(a.name)??RL(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),Cu(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,Bu.default)(ML,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,Bu.default)($L,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ae(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(ae(this.params.source.url,u))}return;default:return Hb(e)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Qb.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Wb(this.videoState.stateChangeStarted$.pipe(Cs(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Cs(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=me(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=ge(this.video);this.subscription.add(this.representations$.pipe(Cs(a=>a.map(({track:s})=>s)),Gb(a=>!!a.length),wL()).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(PL(),Cs(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(EL({zeroTime:this.zeroTime$.pipe(Gb(Cu)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(tt(this.video,this.params.desiredState.isLooped,t)).add(be(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(De(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(Be(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&LL(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 Hb(a.to)}},t)).add(Wb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,kL(["init"])).pipe(xL(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),fe(this.video)}createLiveDashPlayer(){let e=new Ri({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&&Cu(t)?t:Lt(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:d})=>d.id===s)?.representation;jb(l,"Representations missing"),this.dash.startPlay(l,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;jb(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(ae(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Yb=Mi;var TS=D(je(),1);var it=(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 yM,assertNonNullable as TM,debounce as IM,ErrorCategory as Il,filter as vS,filterChanged as Ia,fromEvent as EM,isNonNullable as SS,map as El,merge as rn,observableFrom as xl,once as yS,Subscription as xM}from"@vkontakte/videoplayer-shared";var Vs=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}},Nr=class extends Vs{constructor(){super(),this.listeners||Vs.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)}},Di=class{constructor(){Object.defineProperty(this,"signal",{value:new Nr,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&&(Di.prototype[Symbol.toStringTag]="AbortController",Nr.prototype[Symbol.toStringTag]="AbortSignal");function Bs(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 Ou(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Bs({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,d){let c;d&&d.signal&&(c=d.signal,delete d.signal);let p=new t(l,d);return c&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let d=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(d){let c;try{c=new DOMException("Aborted","AbortError")}catch{c=new Error("Aborted"),c.name="AbortError"}if(d.aborted)return Promise.reject(c);let p=new Promise((m,f)=>{d.addEventListener("abort",()=>f(c),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Ci=Bs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zb=Ci?Ou({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ge=Ci?zb.fetch:window.fetch,tN=Ci?zb.Request:window.Request,se=Ci?Di:window.AbortController,rN=Ci?Nr:window.AbortSignal;var vl=D(Nu(),1);var Ns=D(Zt(),1);var ht=()=>window.ManagedMediaSource||window.MediaSource,Os=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),fg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),bg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Us,clientChecker as Fs}from"@vkontakte/videoplayer-shared";var qs=document.createElement("video"),iR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',aR='video/mp4; codecs="hev1.1.6.L93.B0"',gg='video/webm; codecs="vp09.00.10.08"',vg='video/webm; codecs="av01.0.00M.08"',sR='audio/mp4; codecs="mp4a.40.2"',nR='audio/webm; codecs="opus"',Vi={mms:Os(),mse:fg(),hls:!!(qs.canPlayType?.("application/x-mpegurl")||qs.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Se={mp4:!!qs.canPlayType?.("video/mp4"),webm:!!qs.canPlayType?.("video/webm"),cmaf:!0},ye={h264:!!ht()?.isTypeSupported?.(iR),h265:!!ht()?.isTypeSupported?.(aR),vp9:!!ht()?.isTypeSupported?.(gg),av1:!!ht()?.isTypeSupported?.(vg),aac:!!ht()?.isTypeSupported?.(sR),opus:!!ht()?.isTypeSupported?.(nR)},Fr=(ye.h264||ye.h265)&&ye.aac,er,oR=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:vg}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:gg}})]);er={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{oR()}catch(i){console.error(i)}var qr=Vi.hls&&Se.mp4,Sg=()=>Object.keys(ye).filter(i=>ye[i]),yg=(i,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let a=Vi.mse&&(!r||!!window.MediaStreamTrack)||Vi.mms&&t;return i.filter(s=>{switch(s){case"DASH_SEP":return a&&Se.mp4&&Fr;case"DASH_WEBM":return a&&Se.webm&&ye.vp9&&ye.opus;case"DASH_WEBM_AV1":return a&&Se.webm&&ye.av1&&ye.opus;case"DASH_STREAMS":return a&&(Se.mp4&&Fr||Se.webm&&(ye.vp9||ye.av1)&&(ye.opus||ye.aac));case"DASH_LIVE":return a&&Se.mp4&&Fr;case"DASH_LIVE_CMAF":return a&&Se.mp4&&Fr&&Se.cmaf;case"DASH_ONDEMAND":return a&&Se.mp4&&Fr;case"HLS":case"HLS_ONDEMAND":return qr||e&&a&&Se.mp4&&Fr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return qr;case"MPEG":return Se.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Vi.webrtc&&Vi.ws&&ye.h264&&(Se.mp4||Se.webm);default:return Us(s)}})},_s=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 er?er[t].smooth?[t,e]:er[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return er?er[t].powerEfficient?[t,e]:er[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Us(i)}return[e,t]},Tg=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],..._s(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Fs.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",..._s(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[..._s(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",..._s(i),...a,"HLS","HLS_ONDEMAND"];default:Us(e)}return qr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Ig=({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=Fs.isMac&&Fs.isSafari;if(Fs.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:Us(i)}else qr&&!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"]},Fu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Eg=i=>{if(i.size===0)return;if(i.size===1){let t=i.values().next();return(0,Ns.default)(t.value.split("."),0)}for(let t of i){let r=(0,Ns.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=i.values().next();return(0,Ns.default)(e.value.split("."),0)};var jg=D(Hg(),1);import{ErrorCategory as Oi}from"@vkontakte/videoplayer-shared";var Qg=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,jg.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 Rt=(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 bl,assertNonNullable as nr,clientChecker as eM,combine as Wr,ErrorCategory as Vt,filter as va,filterChanged as Ks,flattenObject as Sa,fromEvent as or,getTraceSubscriptionMethod as tM,interval as gl,isNonNullable as cS,map as ya,merge as ur,now as rM,Subject as dS,Subscription as pS,tap as iM,throttle as aM,ValueSubject as z}from"@vkontakte/videoplayer-shared";var js=D(je(),1),Qr=D(Zt(),1),Qs=D(Nu(),1);var xR=(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)},PR=i=>window.clearTimeout(i),Gg=i=>typeof i=="function"&&i?.toString().endsWith("{ [native code] }"),Wg=!Gg(window.requestIdleCallback)||!Gg(window.cancelIdleCallback),Qu=Wg?xR:window.requestIdleCallback,_i=Wg?PR:window.cancelIdleCallback;var rS=D(Is(),1);import{assertNever as kR,ErrorCategory as Yg,clientChecker as Gu,Subject as zg}from"@vkontakte/videoplayer-shared";var wR=18,Kg=!1;try{Kg=Gu.isSafari&&!!Gu.macVersion&&Gu.macVersion<=wR}catch(i){console.error(i)}var Wu=class{constructor(e){this.bufferFull$=new zg;this.error$=new zg;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Yg.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,a=s=>{this.abortRequested=!1,t(s)};Kg&&e?r={operation:"safariAbort",init:e,callback:a}:r={operation:"abort",callback:a};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,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)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:Yg.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:kR(t)}}},Xg=Wu;var Yu=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 Mt,assertNonNullable as Te,clientChecker as H$,ErrorCategory as Dt,fromEvent as dl,getExponentialDelay as pl,isNonNullable as jr,isNullable as ne,now as Hs,once as j$,Subject as Q$,Subscription as G$,ValueSubject as ir}from"@vkontakte/videoplayer-shared";var V=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)}get id(){return this.type}get size(){return this.size32}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 Ur=class extends V{};var Ni=class extends V{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 Fi=class extends V{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 qi=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var j=class extends V{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Ui=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 Hi=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ji=class extends V{constructor(e,t){super(e,t),this.data=this.content}};var tr=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 Qi=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Gi=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Wi=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 Yi=class extends j{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var zi=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 Ki=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Xi=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 Ji=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Zi=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ea=class extends j{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ta=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ra=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 ia=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 aa=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 sa=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var na=class extends j{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var oa=class extends V{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var LR={ftyp:Fi,moov:qi,mvhd:Ui,moof:Hi,mdat:ji,sidx:tr,trak:Qi,mdia:Ki,mfhd:ea,tkhd:Xi,traf:ta,tfhd:ra,tfdt:ia,trun:aa,minf:Ji,sv3d:Gi,st3d:Wi,prhd:Yi,proj:Zi,equi:zi,uuid:Ni,stbl:sa,stsd:na,avc1:oa,unknown:Ur},mt=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=LR[e];return r?new r(t,new i):new Ur(t,new i)}};var $t=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 $R=new TextDecoder("ascii"),MR=i=>$R.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",DR=i=>{let e=new tr(i,new mt),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})},CR=(i,e)=>{let r=new mt().parse(i),a=new $t(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,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,c)},VR=i=>{let t=new mt().parse(i),r=new $t(t),a={},s=r.findAll("uuid");return s.length?s[s.length-1]:a},BR=i=>{let t=new mt().parse(i);return new $t(t).find("sidx")?.timescale},OR=(i,e)=>{let r=new mt().parse(i),s=new $t(r).findAll("traf"),n=s[s.length-1].children.find(c=>c.type==="tfhd"),o=s[s.length-1].children.find(c=>c.type==="tfdt"),u=s[s.length-1].children.find(c=>c.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((c,p)=>c+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},_R=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 mt().parse(i),a=new $t(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},Jg={validateData:MR,parseInit:_R,getIndexRange:()=>{},parseSegments:DR,parseFeedableSegmentChunk:CR,getChunkEndTime:OR,getServerLatencyTimestamps:VR,getTimescaleFromIndex:BR};var la=D(je(),1);import{assertNonNullable as Ku,isNonNullable as rv,isNullable as FR}from"@vkontakte/videoplayer-shared";import{assertNever as NR}from"@vkontakte/videoplayer-shared";var Zg={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"}},ev=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=ua(i,t),a=r in Zg,s=a?Zg[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,d=ua(u),c=l*2**((o-1)*8)+d,p=t+o,m;return p+c>i.byteLength?m=new DataView(i.buffer,i.byteOffset+p):m=new DataView(i.buffer,i.byteOffset+p,c),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+c,value:m,valueSize:c}},ua=(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},We=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return ua(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:NR(e)}},rr=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=ev(r);if(!e(a))return;a.type==="master"&&rr(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},tv=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=ev(i);return rr(a.value,({tag:s,type:n,value:o})=>(s===17143?e=We(o,n):s===17026?t=We(o,n):s===17029&&(r=We(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var iv=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],qR=[231,22612,22743,167,171,163,160,175],UR=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return rr(i,({tag:p,type:m,value:f,valueSize:b})=>{if(p===21419){let g=We(f,m);l=ua(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=We(f,m):p===17545?a=We(f,m):p===21420&&l===475249515?u=We(f,m):p===374648427?rr(f,({tag:g,type:v,value:k})=>g===30321?(d=We(k,v)===1,!1):!0):s&&n&&(0,la.default)(iv,p)&&(o=!0),!o}),Ku(e,"Failed to parse webm Segment start"),Ku(t,"Failed to parse webm Segment end"),Ku(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:d,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},HR=i=>{if(FR(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},jR=(i,e)=>{let t=!1,r=!1,a=o=>rv(o.time)&&rv(o.position),s=[],n;return rr(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=We(l,u));break;case 183:break;case 241:n&&(n.position=We(l,u));break;default:t&&(0,la.default)(iv,o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:d}=o,c=s[u+1];return{status:"none",time:{from:l,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},QR=i=>{let e=0,t=!1;try{rr(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,la.default)(qR,r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=(0,la.default)([163,160,175],r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},av={validateData:tv,parseInit:UR,getIndexRange:HR,parseSegments:jR,parseFeedableSegmentChunk:QR};var ca=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return av;case"mp4":return Jg}}throw new ReferenceError(`Unsupported mime type ${i}`)};var ul=D(xv(),1),Kv=D(Pr(),1),Xv=D(Fv(),1),Jv=D(Zt(),1),ll=D(Br(),1);var qv=D(je(),1),rl=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,qv.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as U$,isNullable as Yv}from"@vkontakte/videoplayer-shared";var Uv=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Hv=i=>{try{let e=F$(),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 F$(){let i="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
64
64
|
(?<language>${`(?:[a-z]{2,3}(?:-${i})?|[a-z]{4}|[a-z]{5,8})`})
|
|
65
65
|
(-(?<script>[a-z]{4}))?
|
|
66
66
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
67
67
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
68
68
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
69
69
|
(?:-(?<privateuse>(?:${e})))?
|
|
70
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var al=D(Zt(),1);import{videoSizeToQuality as q$}from"@vkontakte/videoplayer-shared";var jv=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s,streamId:n})=>{let o=(s?kt(s):void 0)??q$({width:e,height:t});return o&&{id:i,quality:o,bitrate:r,size:{width:e,height:t},fps:a,streamId:n}},Qv=({id:i,bitrate:e})=>({id:i,bitrate:e}),Gv=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Wv=({language:i,label:e,id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),sl=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,al.default)(r.split("."),0),isDefault:a}),nl=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,al.default)(a.split("."),0)}),ol=i=>"url"in i,ce=i=>i.type==="template",da=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var zv=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},ft=(i,e)=>{let t=i;t=(0,ul.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,Kv.default)(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,ul.default)(t,n,(o,u)=>Yv(s)?o:Yv(u)?s:(0,Xv.default)(s,parseInt(u,10),"0"))}return t},Zv=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(y=>y.textContent?.trim()??""),o=(0,Jv.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,c,p=s.getAttribute("mediaPresentationDuration"),f=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((y,I)=>({...y,[I.id]:I.children}),{}),v=b.reduce((y,I)=>({...y,[I.id]:I.getAttribute("duration")}),{});p?c=zv(p):(0,ll.default)(v).filter(y=>y).length&&!u?c=(0,ll.default)(v).reduce((y,I)=>y+(zv(I)??0),0):f&&(c=parseInt(f,10));let w=0,x=s.getAttribute("profiles")?.split(",")??[];for(let y of b.map(I=>I.id))for(let I of g[y]){let A=I.getAttribute("id")??"id"+(w++).toString(10),Q=I.getAttribute("mimeType")??"",N=I.getAttribute("codecs")??"",q=I.getAttribute("contentType")??Q?.split("/")[0],S=I.getAttribute("profiles")?.split(",")??[],P=Hv(I.getAttribute("lang")??"")??{},U=I.querySelector("Label")?.textContent?.trim()??void 0,Le=I.querySelectorAll("Representation"),Re=I.querySelector("SegmentTemplate"),k=I.querySelector("Role")?.getAttribute("value")??void 0,B=q,F={id:A,language:P.language,isDefault:k==="main",label:U,codecs:N,hdr:B==="video"&&rl(N),mime:Q,representations:[]};for(let L of Le){let G=L.getAttribute("lang")??void 0,$e=U??I.getAttribute("label")??L.getAttribute("label")??void 0,cr=L.querySelector("BaseURL")?.textContent?.trim()??"",ze=new URL(cr||o,e).toString(),C=L.getAttribute("mimeType")??Q,te=L.getAttribute("codecs")??N??"",oe;if(q==="text"){let X=L.getAttribute("id")||"",Ke=P.privateuse?.includes("x-auto")||X.includes("_auto"),Oe=L.querySelector("SegmentTemplate");if(Oe){let _e={representationId:L.getAttribute("id")??void 0,bandwidth:L.getAttribute("bandwidth")??void 0},st=parseInt(L.getAttribute("bandwidth")??"",10)/1e3,gt=parseInt(Oe.getAttribute("startNumber")??"",10)??1,nt=parseInt(Oe.getAttribute("timescale")??"",10),Sn=Oe.querySelectorAll("SegmentTimeline S")??[],dr=Oe.getAttribute("media");if(!dr)continue;let Va=[],Ba=0,Oa="",pr=0,Kr=gt,ue=0;for(let Ne of Sn){let Nt=parseInt(Ne.getAttribute("d")??"",10),Me=parseInt(Ne.getAttribute("r")??"",10)||0,vt=parseInt(Ne.getAttribute("t")??"",10);ue=Number.isFinite(vt)?vt:ue;let Ft=Nt/nt*1e3,hr=ue/nt*1e3;for(let Xe=0;Xe<Me+1;Xe++){let St=ft(dr,{..._e,segmentNumber:Kr.toString(10),segmentTime:(ue+Xe*Nt).toString(10)}),mr=(hr??0)+Xe*Ft,Jr=mr+Ft;Kr++,Va.push({time:{from:mr,to:Jr},url:St})}ue+=(Me+1)*Nt,Ba+=(Me+1)*Ft}pr=ue/nt*1e3,Oa=ft(dr,{..._e,segmentNumber:Kr.toString(10),segmentTime:ue.toString(10)});let Xr={time:{from:pr,to:1/0},url:Oa},ot={type:"template",baseUrl:ze,segmentTemplateUrl:dr,initUrl:"",totalSegmentsDurationMs:Ba,segments:Va,nextSegmentBeyondManifest:Xr,timescale:nt};oe={id:X,kind:"text",segmentReference:ot,profiles:[],duration:c,bitrate:st,mime:"",codecs:"",width:0,height:0,isAuto:Ke}}else oe={id:X,isAuto:Ke,kind:"text",url:ze}}else{let X=L.getAttribute("contentType")??C?.split("/")[0]??q,Ke=I.getAttribute("profiles")?.split(",")??[],Oe=parseInt(L.getAttribute("width")??"",10),_e=parseInt(L.getAttribute("height")??"",10),st=parseInt(L.getAttribute("bandwidth")??"",10)/1e3,gt=L.getAttribute("frameRate")??"",nt=L.getAttribute("quality")??void 0,Sn=gt?Uv(gt):void 0,dr=L.getAttribute("id")??"id"+(w++).toString(10),Va=X==="video"?`${_e}p`:X==="audio"?`${st}Kbps`:te,Ba=`${dr}@${Va}`,Oa=[...x,...S,...Ke],pr,Kr=L.querySelector("SegmentBase"),ue=L.querySelector("SegmentTemplate")??Re;if(Kr){let ot=L.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ne,Nt]=ot.split("-").map(St=>parseInt(St,10)),Me={from:Ne,to:Nt},vt=L.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ft,hr]=vt?vt.split("-").map(St=>parseInt(St,10)):[],Xe=vt?{from:Ft,to:hr}:void 0;pr={type:"byteRange",url:ze,initRange:Me,indexRange:Xe}}else if(ue){let ot={representationId:L.getAttribute("id")??void 0,bandwidth:L.getAttribute("bandwidth")??void 0},Ne=parseInt(ue.getAttribute("timescale")??"",10),Nt=ue.getAttribute("initialization")??"",Me=ue.getAttribute("media"),vt=parseInt(ue.getAttribute("startNumber")??"",10)??1,Ft=ft(Nt,ot);if(!Me)throw new ReferenceError("No media attribute in SegmentTemplate");let hr=ue.querySelectorAll("SegmentTimeline S")??[],Xe=[],St=0,mr="",Jr=0;if(hr.length){let _a=vt,Fe=0;for(let fr of hr){let Je=parseInt(fr.getAttribute("d")??"",10),qt=parseInt(fr.getAttribute("r")??"",10)||0,Na=parseInt(fr.getAttribute("t")??"",10);Fe=Number.isFinite(Na)?Na:Fe;let yn=Je/Ne*1e3,vy=Fe/Ne*1e3;for(let Fa=0;Fa<qt+1;Fa++){let Sy=ft(Me,{...ot,segmentNumber:_a.toString(10),segmentTime:(Fe+Fa*Je).toString(10)}),ql=(vy??0)+Fa*yn,yy=ql+yn;_a++,Xe.push({time:{from:ql,to:yy},url:Sy})}Fe+=(qt+1)*Je,St+=(qt+1)*yn}Jr=Fe/Ne*1e3,mr=ft(Me,{...ot,segmentNumber:_a.toString(10),segmentTime:Fe.toString(10)})}else if(U$(c)){let Fe=parseInt(ue.getAttribute("duration")??"",10)/Ne*1e3,fr=Math.ceil(c/Fe),Je=0;for(let qt=1;qt<fr;qt++){let Na=ft(Me,{...ot,segmentNumber:qt.toString(10),segmentTime:Je.toString(10)});Xe.push({time:{from:Je,to:Je+Fe},url:Na}),Je+=Fe}Jr=Je,mr=ft(Me,{...ot,segmentNumber:fr.toString(10),segmentTime:Je.toString(10)})}let gy={time:{from:Jr,to:1/0},url:mr};pr={type:"template",baseUrl:ze,segmentTemplateUrl:Me,initUrl:Ft,totalSegmentsDurationMs:St,segments:Xe,nextSegmentBeyondManifest:gy,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!X||!C)continue;let Xr={video:"video",audio:"audio",text:"text"}[X];if(!Xr)continue;B||=Xr,oe={id:Ba,kind:Xr,segmentReference:pr,profiles:Oa,duration:c,bitrate:st,mime:C,codecs:te,width:Oe,height:_e,fps:Sn,quality:nt}}F.language||=G,F.label||=$e,F.mime||=C,F.codecs||=te,F.hdr||=B==="video"&&rl(te),F.representations.push(oe)}if(B){let L=a[B].find(G=>G.id===F.id);if(L&&F.representations.every(G=>ce(G.segmentReference)))for(let G of L.representations){let cr=F.representations.find(C=>C.id===G.id)?.segmentReference,ze=G.segmentReference;ze.segments.push(...cr.segments),ze.nextSegmentBeyondManifest=cr.nextSegmentBeyondManifest}else a[B].push(F)}}return{dynamic:u,liveAvailabilityStartTime:d,duration:c,streams:a,baseUrls:n}};var tS=D(je(),1);import{isNonNullable as eS}from"@vkontakte/videoplayer-shared";var de=(i,e)=>eS(i)&&eS(e)&&i.readyState==="open"&&(0,tS.default)([...i.activeSourceBuffers],e);var pa=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ir(0);this.currentLowLatencySegmentLength$=new ir(0);this.currentSegmentLength$=new ir(0);this.onLastSegment$=new ir(!1);this.fullyBuffered$=new ir(!1);this.playingRepresentation$=new ir(void 0);this.playingRepresentationInit$=new ir(void 0);this.error$=new Q$;this.gaps=[];this.subscription=new G$;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new se;this.switchAbortController=new se;this.destroyAbortController=new se;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=Mt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Te(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Xg(this.sourceBuffer),this.subscription.add(dl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(dl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Dt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!de(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Yu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=it(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d)})),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);Te(r,"No init buffer for starting representation"),Te(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.switchTo=Mt(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);Te(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Te(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();jr(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Mt(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);Te(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Te(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();jr(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=Mt(this.destroyAbortController.signal,async function*(e){let t=(0,Qs.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 d=this.representations.get(u);if(!d||!ce(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);Te(a);let s=this.segments.get(r);Te(s,"No segments for starting representation");let n=this.initData.get(r);if(Te(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,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(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new se,Mt(this.switchAbortController.signal,async function*(r,a=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);Te(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(ne(o)||ne(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),Te(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(yield 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();jr(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))}warmUpMediaSource(){!ne(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new se,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ne(e)||ne(this.downloadingRepresentationId)||ne(this.playingRepresentationId)||ne(this.sourceBuffer)||!de(this.mediaSource,this.sourceBuffer)||jr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Te(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);jr(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=it(this.sourceBuffer.buffered,e),c=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=c)}if(isFinite(this.bufferLimit)&&Yu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=it(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<d);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,js.default)(o,a))l="high";else{let d=(0,Qr.default)(o,0);d&&d.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&&it(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Qr.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;jr(t.duration)&&t.duration-r>0&&!this.isLive&&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,Qs.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,Qs.default)(e?.streams[this.kind],r=>r.representations)??[];if(![...this.segments.values()].every(r=>!r.length))for(let r of t){if(!r||!ce(r.segmentReference))return;let a=r.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(r.id)??[],o=(0,Qr.default)(n,-1)?.time.to??0,u=a?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,l)}else{let l=a.slice(u+1);this.segments.set(r.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Te(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!ce(a))return;let s=this.segments.get(r.id)??[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*a.timescale/1e3).toString(10),l=ft(a.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let 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&&_i&&_i(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_i&&_i(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,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:c,time:{from:p,to:m}},f)=>{let b=p<=r&&m>=r,g=p>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),w=this.preloadOnly&&p<=r+v||m<=r+v;return(c==="none"||c==="partially_ejected"&&g&&w&&this.sourceBuffer&&de(this.mediaSource,this.sourceBuffer)&&!(Rt(this.sourceBuffer.buffered,p)&&Rt(this.sourceBuffer.buffered,m)))&&g&&w});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,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=a;c<s.length&&(n<=l||o<=d);c++){let p=s[c];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"){ce(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 Mt(o,async function*(){let d=pl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Hs(),!d)return;let c=new DataView(d),p=ca(t.mime);if(!isFinite(a.segment.time.to)){let b=t.segmentReference.timescale;a.segment.time.to=p.getChunkEndTime(c,b)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:m,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(c);m&&f&&this.currentLiveSegmentServerLatency$.next(f-m),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),da(d)||(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())ce(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 Mt(n,async function*(){let u=pl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),dl(window,"online").pipe(j$()).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=Hs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),da(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ce(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Qr.default)(e,0).byte.from,to:(0,Qr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Hs(),await 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:Dt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ce(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,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Hs();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Dt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,js.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),d=ca(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.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){await n();continue}let d=l.byte.from-r,c=l.byte.to-r,p=c-d+1,m=d<a,f=c<=a;if(!m)continue;let b=ca(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);v?.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(ne(this.sourceBuffer)||!de(this.mediaSource,this.sourceBuffer))){!this.isLive&&H$.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Rt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Rt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Dt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ol(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())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");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[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 r=this.representations.get(e);r&&(this.initLoadIdleCallback=Qu(()=>(0,rS.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?Mt(this.destroyAbortController.signal,async function*(){let o=pl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ca(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&ce(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:Dt.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,r=!1){if(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ne(e))return!1;let a=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],m=l[l.length-1];m.to>=c?m.to=Math.max(m.to,p):l.push(u[d])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=ol(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 d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let m of p)(0,js.default)(["none","partially_ejected"],m.status)&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},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 this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ne(e)?0:it(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)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)));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||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)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=Qu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Dt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ne(this.sourceBuffer)||!de(this.mediaSource,this.sourceBuffer)||ne(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 this.segments.values())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(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var ha=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var iS=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 ma,assertNever as sS,fromEvent as nS,merge as W$,now as fa,Subscription as Y$,ValueSubject as hl,flattenObject as Gr}from"@vkontakte/videoplayer-shared";var aS=i=>{let e=new URL(i);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Gs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new hl(void 0);this.lastConnectionReused$=new hl(void 0);this.lastRequestFirstBytes$=new hl(void 0);this.abortAllController=new se;this.subscription=new Y$;this.fetchManifest=ma(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ha(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=aS(r));let a=yield Ge(r,{signal:this.abortAllController.signal}).catch(ba);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=ma(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,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let S=new URL(l,location.href);S.searchParams.append("bytes",`${r.from}-${r.to}`),l=S.toString();break}default:sS(t)}this.requestQuic&&(l=ha(l));let p=this.abortAllController.signal,m;if(n){let S=new se;if(m=W$(nS(this.abortAllController.signal,"abort"),nS(n,"abort")).subscribe(()=>{try{S.abort()}catch(P){ba(P)}}),this.abortAllController.signal.aborted||n.aborted)try{S.abort()}catch(P){ba(P)}p=S.signal}let f=fa();c.log("startRequest",Gr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield Ge(l,{priority:s,headers:d,signal:p}).catch(ba),g=fa();if(!b)return c.error("error",{message:"No response in request"}),c.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){m?.unsubscribe();let S=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:S}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){m?.unsubscribe();let S=fa(),P={requestStartedAt:f,requestEndedAt:S,duration:S-f};return c.log("endRequest",Gr(P)),c.end(),b.arrayBuffer()}let[v,w]=b.body.tee(),x=v.getReader();o&&this.throughputEstimator?.trackStream(w,u);let R=0,y=new Uint8Array(0),I=!1,A=S=>{m?.unsubscribe(),I=!0,ba(S)},Q=ma(p,async function*({done:S,value:P}){if(R===0&&this.lastRequestFirstBytes$.next(fa()-f),p.aborted){m?.unsubscribe();return}if(!S&&P){let U=new Uint8Array(y.length+P.length);U.set(y),U.set(P,y.length),y=U,R+=P.byteLength,a?.(new DataView(y.buffer),R),yield x?.read().then(Q,A)}}.bind(this));yield x?.read().then(Q,A),m?.unsubscribe();let N=fa(),q={failed:I,requestStartedAt:f,requestEndedAt:N,duration:N-f};return I?(c.error("endRequest",Gr(q)),c.end(),null):(c.log("endRequest",Gr(q)),c.end(),y.buffer)}.bind(this));this.fetchByteRangeRepresentation=ma(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,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!c)return null;let p=new DataView(c,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let m=t.parseInit(p),f=e.indexRange??t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,m,f);return{init:m,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=ma(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}=iS(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:sS(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ba=i=>{if(!da(i))throw i};var ar=(i,e,t)=>t*e+(1-t)*i,ml=(i,e)=>i.reduce((t,r)=>t+r,0)/e,oS=(i,e,t,r)=>{let a=0,s=t,n=ml(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 z$,ValueSubject as uS}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 uS(e.initial),this.debounced$=new uS(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new le(`raw_${t}`),this.smoothedSeries$=new le(`smoothed_${t}`),this.reportedSeries$=new le(`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)&&(z$(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 Ws=class extends Ct{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ar(this.slow,e,this.params.emaAlphaSlow),this.fast=ar(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ys=class extends Ct{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ml(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ar(this.emaSmoothed,e,this.params.emaAlpha);let r=oS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var zs=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?ar(this.smoothed,t,this.params.emaAlpha):t}};var sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Ws({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ys({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 zs({initial:e,label:"liveEdgeDelay",...t})}};var fl=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};import{isNullable as K$,ValueSubject as X$}from"@vkontakte/videoplayer-shared";var ga=class i{constructor(e,t){this.currentRepresentation$=new X$(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(!K$(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&&ce(t.segmentReference))}};var sM=["timeupdate","progress","play","seeked","stalled","waiting"],nM=["timeupdate","progress","loadeddata","playing","seeked"];var Xs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new pS;this.representationSubscription=new pS;this.state$=new $("none");this.currentVideoRepresentation$=new z(void 0);this.currentVideoRepresentationInit$=new z(void 0);this.currentAudioRepresentation$=new z(void 0);this.currentVideoSegmentLength$=new z(0);this.currentAudioSegmentLength$=new z(0);this.error$=new dS;this.lastConnectionType$=new z(void 0);this.lastConnectionReused$=new z(void 0);this.lastRequestFirstBytes$=new z(void 0);this.currentLiveTextRepresentation$=new z(null);this.isLive$=new z(!1);this.liveDuration$=new z(0);this.liveAvailabilityStartTime$=new z(void 0);this.bufferLength$=new z(0);this.liveLatency$=new z(void 0);this.liveLoadBufferLength$=new z(0);this.livePositionFromPlayer$=new z(0);this.isLowLatency$=new z(!1);this.isActiveLowLatency$=new z(!1);this.currentStallDuration$=new z(0);this.videoLastDataObtainedTimestamp$=new z(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new dS;this.gapWatchdogActive=!1;this.destroyController=new se;this.initManifest=bl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(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:Vt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=bl(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:Vt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Zv(e??"",this.manifestUrlString)}catch(n){let o=Qg(e)??{id:"ManifestParsing",category:Vt.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)&&ht()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let n=(t.duration??0)/1e3;this.liveDuration$.next(-1*n)}let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:c,codecs:p})=>r(n,c,p)),l=new Set(u.map(({codecs:c})=>c)),d=Eg(l);if(d&&(a[n]=u.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=a.video.some(f=>f.hdr),m=a.video.some(f=>!f.hdr);eM.isHDR&&c&&p?a.video=a.video.filter(f=>f.hdr):m&&(a.video=a.video.filter(f=>!f.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",Sa(s)),s}.bind(this));this.initRepresentations=bl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",Sa({initialVideo:e,initialAudio:t,sourceHls:r})),nr(this.manifest),nr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=c=>{this.representationSubscription.add(or(c,"error").pipe(va(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Vt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?bg():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Os())if(r){let c=document.createElement("source");a(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}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((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new pa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],cS(t)){let c=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new pa("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}ga.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ga(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.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(gl(1e3).subscribe(c=>{if(this.element?.paused){let p=Es(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,p+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ur(...nM.map(c=>or(this.element,c))).pipe(ya(c=>this.element?it(this.element.buffered,this.element.currentTime*1e3):0),Ks(),iM(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ur(or(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Ks()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||fl(this.element,1)})),this.representationSubscription.add(Wr({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(va(({bufferLength:p,isActiveLowLatency:m})=>m&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(Wr({isActiveLowLatency:this.isActiveLowLatency$.pipe(Ks()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(va(({isActiveLowLatency:p,currentLowLatencySegmentLength:m})=>p&&!!m)).subscribe(({currentLowLatencySegmentLength:p})=>{let m=this.liveDuration$.getValue()-p/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(Wr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(va(({isLive:p})=>p),ya(p=>({...p})),Ks((p,m)=>m.bufferLength<p.bufferLength),ya(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=Es(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Wr({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:p,isActiveLowLatency:m})=>{if(!m)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=p-f;if(this.isManualDecreasePlaybackInLive())return;let w=1;Math.abs(v)>b&&(w=1+Math.sign(v)*g),fl(this.element,w)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=0;this.representationSubscription.add(Wr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(aM(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(nr(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,b=Es(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),w=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,R=isFinite(p)?p:m,y=this.isActiveLowLatency$.getValue(),I=g<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(y&&I);let A="none";if(y?A="active_low_latency":this.isLowLatency$.getValue()&&I?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(Q=>Q.proceedLowLatencyLive()),A="active_low_latency"):b!==0&&R<v?A="live_forward_buffering":R<v+x&&(A="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),A==="live_forward_buffering"||A==="live_with_target_offset"){let Q=c-(v+w),N=this.normolizeLiveOffset(Math.trunc(b+Q/f)),q=Math.abs(N-b),S;!p||q<=this.tuning.dashCmafLive.offsetCalculationError?S=b:N>0&&q>this.tuning.dashCmafLive.offsetCalculationError?S=N:S=0,this.manifestUrlString=ae(this.manifestUrlString,S,2)}A!=="none"&&A!=="active_low_latency"&&(c=0,this.updateLive())}))}let l=ur(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(ya(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),d=ur(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(ya(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue())));if(this.representationSubscription.add(ur(this.forceEnded$,Wr({allBuffersFull:l,someBufferEnded:d}).pipe(va(({allBuffersFull:c,someBufferEnded:p})=>c&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream(),this.bufferManagers.forEach(c=>c.warmUpMediaSource())}catch(c){this.error$.next({id:"EndOfStream",category:Vt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(ur(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(c=>this.source?.addEventListener("sourceopen",c))),!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,vl.default)((0,vl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let m=[];return p.duration&&m.push(p.duration),ce(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&cS(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=gl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Vt.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 Gs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=sr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){nr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ae(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(){nr(this.element),this.state$.setState("running"),this.subscription.add(ur(...sM.map(e=>or(this.element,e)),or(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Vt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(or(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(or(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Rt(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=rM(),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,d=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&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",Sa(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=gl(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Vt.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let a={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?a?.switchToWithPreviousAbort(t,r):a?.switchTo(t,r):a?.switchToOld(t,r)}async seek(e,t){nr(this.element),nr(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),Rt(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Sa({requestedPosition:e,forcePrecise:t,position:r}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.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=tM(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.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",Sa(t)))}}};var Js=class{constructor(e,t){this.fov=e,this.orientation=t}};var Zs=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 hS=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var al=D(Zt(),1);import{videoSizeToQuality as q$}from"@vkontakte/videoplayer-shared";var jv=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s,streamId:n})=>{let o=(s?wt(s):void 0)??q$({width:e,height:t});return o&&{id:i,quality:o,bitrate:r,size:{width:e,height:t},fps:a,streamId:n}},Qv=({id:i,bitrate:e})=>({id:i,bitrate:e}),Gv=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Wv=({language:i,label:e,id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),sl=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,al.default)(r.split("."),0),isDefault:a}),nl=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,al.default)(a.split("."),0)}),ol=i=>"url"in i,ce=i=>i.type==="template",da=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var zv=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},ft=(i,e)=>{let t=i;t=(0,ul.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,Kv.default)(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,ul.default)(t,n,(o,u)=>Yv(s)?o:Yv(u)?s:(0,Xv.default)(s,parseInt(u,10),"0"))}return t},Zv=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(y=>y.textContent?.trim()??""),o=(0,Jv.default)(n,0)??"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),d=l?new Date(l).getTime():void 0,c,p=s.getAttribute("mediaPresentationDuration"),f=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((y,I)=>({...y,[I.id]:I.children}),{}),v=b.reduce((y,I)=>({...y,[I.id]:I.getAttribute("duration")}),{});p?c=zv(p):(0,ll.default)(v).filter(y=>y).length&&!u?c=(0,ll.default)(v).reduce((y,I)=>y+(zv(I)??0),0):f&&(c=parseInt(f,10));let k=0,x=s.getAttribute("profiles")?.split(",")??[];for(let y of b.map(I=>I.id))for(let I of g[y]){let A=I.getAttribute("id")??"id"+(k++).toString(10),Q=I.getAttribute("mimeType")??"",N=I.getAttribute("codecs")??"",q=I.getAttribute("contentType")??Q?.split("/")[0],S=I.getAttribute("profiles")?.split(",")??[],P=Hv(I.getAttribute("lang")??"")??{},U=I.querySelector("Label")?.textContent?.trim()??void 0,Le=I.querySelectorAll("Representation"),Re=I.querySelector("SegmentTemplate"),w=I.querySelector("Role")?.getAttribute("value")??void 0,B=q,F={id:A,language:P.language,isDefault:w==="main",label:U,codecs:N,hdr:B==="video"&&rl(N),mime:Q,representations:[]};for(let L of Le){let G=L.getAttribute("lang")??void 0,$e=U??I.getAttribute("label")??L.getAttribute("label")??void 0,cr=L.querySelector("BaseURL")?.textContent?.trim()??"",ze=new URL(cr||o,e).toString(),C=L.getAttribute("mimeType")??Q,te=L.getAttribute("codecs")??N??"",oe;if(q==="text"){let X=L.getAttribute("id")||"",Ke=P.privateuse?.includes("x-auto")||X.includes("_auto"),Oe=L.querySelector("SegmentTemplate");if(Oe){let _e={representationId:L.getAttribute("id")??void 0,bandwidth:L.getAttribute("bandwidth")??void 0},st=parseInt(L.getAttribute("bandwidth")??"",10)/1e3,gt=parseInt(Oe.getAttribute("startNumber")??"",10)??1,nt=parseInt(Oe.getAttribute("timescale")??"",10),Sn=Oe.querySelectorAll("SegmentTimeline S")??[],dr=Oe.getAttribute("media");if(!dr)continue;let Va=[],Ba=0,Oa="",pr=0,Kr=gt,ue=0;for(let Ne of Sn){let Nt=parseInt(Ne.getAttribute("d")??"",10),Me=parseInt(Ne.getAttribute("r")??"",10)||0,vt=parseInt(Ne.getAttribute("t")??"",10);ue=Number.isFinite(vt)?vt:ue;let Ft=Nt/nt*1e3,hr=ue/nt*1e3;for(let Xe=0;Xe<Me+1;Xe++){let St=ft(dr,{..._e,segmentNumber:Kr.toString(10),segmentTime:(ue+Xe*Nt).toString(10)}),mr=(hr??0)+Xe*Ft,Jr=mr+Ft;Kr++,Va.push({time:{from:mr,to:Jr},url:St})}ue+=(Me+1)*Nt,Ba+=(Me+1)*Ft}pr=ue/nt*1e3,Oa=ft(dr,{..._e,segmentNumber:Kr.toString(10),segmentTime:ue.toString(10)});let Xr={time:{from:pr,to:1/0},url:Oa},ot={type:"template",baseUrl:ze,segmentTemplateUrl:dr,initUrl:"",totalSegmentsDurationMs:Ba,segments:Va,nextSegmentBeyondManifest:Xr,timescale:nt};oe={id:X,kind:"text",segmentReference:ot,profiles:[],duration:c,bitrate:st,mime:"",codecs:"",width:0,height:0,isAuto:Ke}}else oe={id:X,isAuto:Ke,kind:"text",url:ze}}else{let X=L.getAttribute("contentType")??C?.split("/")[0]??q,Ke=I.getAttribute("profiles")?.split(",")??[],Oe=parseInt(L.getAttribute("width")??"",10),_e=parseInt(L.getAttribute("height")??"",10),st=parseInt(L.getAttribute("bandwidth")??"",10)/1e3,gt=L.getAttribute("frameRate")??"",nt=L.getAttribute("quality")??void 0,Sn=gt?Uv(gt):void 0,dr=L.getAttribute("id")??"id"+(k++).toString(10),Va=X==="video"?`${_e}p`:X==="audio"?`${st}Kbps`:te,Ba=`${dr}@${Va}`,Oa=[...x,...S,...Ke],pr,Kr=L.querySelector("SegmentBase"),ue=L.querySelector("SegmentTemplate")??Re;if(Kr){let ot=L.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Ne,Nt]=ot.split("-").map(St=>parseInt(St,10)),Me={from:Ne,to:Nt},vt=L.querySelector("SegmentBase")?.getAttribute("indexRange"),[Ft,hr]=vt?vt.split("-").map(St=>parseInt(St,10)):[],Xe=vt?{from:Ft,to:hr}:void 0;pr={type:"byteRange",url:ze,initRange:Me,indexRange:Xe}}else if(ue){let ot={representationId:L.getAttribute("id")??void 0,bandwidth:L.getAttribute("bandwidth")??void 0},Ne=parseInt(ue.getAttribute("timescale")??"",10),Nt=ue.getAttribute("initialization")??"",Me=ue.getAttribute("media"),vt=parseInt(ue.getAttribute("startNumber")??"",10)??1,Ft=ft(Nt,ot);if(!Me)throw new ReferenceError("No media attribute in SegmentTemplate");let hr=ue.querySelectorAll("SegmentTimeline S")??[],Xe=[],St=0,mr="",Jr=0;if(hr.length){let _a=vt,Fe=0;for(let fr of hr){let Je=parseInt(fr.getAttribute("d")??"",10),qt=parseInt(fr.getAttribute("r")??"",10)||0,Na=parseInt(fr.getAttribute("t")??"",10);Fe=Number.isFinite(Na)?Na:Fe;let yn=Je/Ne*1e3,vy=Fe/Ne*1e3;for(let Fa=0;Fa<qt+1;Fa++){let Sy=ft(Me,{...ot,segmentNumber:_a.toString(10),segmentTime:(Fe+Fa*Je).toString(10)}),ql=(vy??0)+Fa*yn,yy=ql+yn;_a++,Xe.push({time:{from:ql,to:yy},url:Sy})}Fe+=(qt+1)*Je,St+=(qt+1)*yn}Jr=Fe/Ne*1e3,mr=ft(Me,{...ot,segmentNumber:_a.toString(10),segmentTime:Fe.toString(10)})}else if(U$(c)){let Fe=parseInt(ue.getAttribute("duration")??"",10)/Ne*1e3,fr=Math.ceil(c/Fe),Je=0;for(let qt=1;qt<fr;qt++){let Na=ft(Me,{...ot,segmentNumber:qt.toString(10),segmentTime:Je.toString(10)});Xe.push({time:{from:Je,to:Je+Fe},url:Na}),Je+=Fe}Jr=Je,mr=ft(Me,{...ot,segmentNumber:fr.toString(10),segmentTime:Je.toString(10)})}let gy={time:{from:Jr,to:1/0},url:mr};pr={type:"template",baseUrl:ze,segmentTemplateUrl:Me,initUrl:Ft,totalSegmentsDurationMs:St,segments:Xe,nextSegmentBeyondManifest:gy,timescale:Ne}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!X||!C)continue;let Xr={video:"video",audio:"audio",text:"text"}[X];if(!Xr)continue;B||=Xr,oe={id:Ba,kind:Xr,segmentReference:pr,profiles:Oa,duration:c,bitrate:st,mime:C,codecs:te,width:Oe,height:_e,fps:Sn,quality:nt}}F.language||=G,F.label||=$e,F.mime||=C,F.codecs||=te,F.hdr||=B==="video"&&rl(te),F.representations.push(oe)}if(B){let L=a[B].find(G=>G.id===F.id);if(L&&F.representations.every(G=>ce(G.segmentReference)))for(let G of L.representations){let cr=F.representations.find(C=>C.id===G.id)?.segmentReference,ze=G.segmentReference;ze.segments.push(...cr.segments),ze.nextSegmentBeyondManifest=cr.nextSegmentBeyondManifest}else a[B].push(F)}}return{dynamic:u,liveAvailabilityStartTime:d,duration:c,streams:a,baseUrls:n}};var tS=D(je(),1);import{isNonNullable as eS}from"@vkontakte/videoplayer-shared";var de=(i,e)=>eS(i)&&eS(e)&&i.readyState==="open"&&(0,tS.default)([...i.activeSourceBuffers],e);var pa=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ir(0);this.currentLowLatencySegmentLength$=new ir(0);this.currentSegmentLength$=new ir(0);this.onLastSegment$=new ir(!1);this.fullyBuffered$=new ir(!1);this.playingRepresentation$=new ir(void 0);this.playingRepresentationInit$=new ir(void 0);this.error$=new Q$;this.gaps=[];this.subscription=new G$;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new se;this.switchAbortController=new se;this.destroyAbortController=new se;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=Mt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Te(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Xg(this.sourceBuffer),this.subscription.add(dl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Dt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(dl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Dt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!de(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Yu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=it(this.sourceBuffer.buffered,o),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<d)})),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);Te(r,"No init buffer for starting representation"),Te(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.switchTo=Mt(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);Te(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Te(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();jr(n)&&!this.isLive&&(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}}.bind(this));this.switchToOld=Mt(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);Te(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(ne(s)||ne(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Te(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();jr(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=Mt(this.destroyAbortController.signal,async function*(e){let t=(0,Qs.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 d=this.representations.get(u);if(!d||!ce(d.segmentReference))return;let c=this.getActualLiveStartingSegments(d.segmentReference);this.segments.set(d.id,c)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);Te(a);let s=this.segments.get(r);Te(s,"No segments for starting representation");let n=this.initData.get(r);if(Te(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,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(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new se,Mt(this.switchAbortController.signal,async function*(r,a=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);Te(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(ne(o)||ne(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),Te(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(yield 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();jr(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))}warmUpMediaSource(){!ne(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}async abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new se,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ne(e)||ne(this.downloadingRepresentationId)||ne(this.playingRepresentationId)||ne(this.sourceBuffer)||!de(this.mediaSource,this.sourceBuffer)||jr(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Te(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);jr(a)&&isFinite(a.time.from)&&isFinite(a.time.to)&&this.currentSegmentLength$.next(a?.time.to-a.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let d=it(this.sourceBuffer.buffered,e),c=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(s=c)}if(isFinite(this.bufferLimit)&&Yu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=it(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<d);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,js.default)(o,a))l="high";else{let d=(0,Qr.default)(o,0);d&&d.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&&it(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Qr.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;jr(t.duration)&&t.duration-r>0&&!this.isLive&&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,Qs.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,Qs.default)(e?.streams[this.kind],r=>r.representations)??[];if(![...this.segments.values()].every(r=>!r.length))for(let r of t){if(!r||!ce(r.segmentReference))return;let a=r.segmentReference.segments.map(l=>({...l,status:"none",size:void 0})),s=100,n=this.segments.get(r.id)??[],o=(0,Qr.default)(n,-1)?.time.to??0,u=a?.findIndex(l=>o>=l.time.from+s&&o<=l.time.to+s);if(u===-1){this.liveUpdateSegmentIndex=0;let l=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,l)}else{let l=a.slice(u+1);this.segments.set(r.id,[...n,...l])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;Te(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){let t=0;for(let r of this.representations.values()){let a=r.segmentReference;if(!ce(a))return;let s=this.segments.get(r.id)??[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to,t=n.time.to-n.time.from),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*a.timescale/1e3).toString(10),l=ft(a.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let 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&&_i&&_i(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&_i&&_i(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,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:c,time:{from:p,to:m}},f)=>{let b=p<=r&&m>=r,g=p>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),k=this.preloadOnly&&p<=r+v||m<=r+v;return(c==="none"||c==="partially_ejected"&&g&&k&&this.sourceBuffer&&de(this.mediaSource,this.sourceBuffer)&&!(Rt(this.sourceBuffer.buffered,p)&&Rt(this.sourceBuffer.buffered,m)))&&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,d=this.preloadOnly?this.forwardBufferTarget:0;for(let c=a;c<s.length&&(n<=l||o<=d);c++){let p=s[c];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"){ce(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 Mt(o,async function*(){let d=pl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,d))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let d=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Hs(),!d)return;let c=new DataView(d),p=ca(t.mime);if(!isFinite(a.segment.time.to)){let b=t.segmentReference.timescale;a.segment.time.to=p.getChunkEndTime(c,b)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(c,o);let{serverDataReceivedTimestamp:m,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(c);m&&f&&this.currentLiveSegmentServerLatency$.next(f-m),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){this.abortActiveSegments([e]),da(d)||(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())ce(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 Mt(n,async function*(){let u=pl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),dl(window,"online").pipe(j$()).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=Hs(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),da(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(ce(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Qr.default)(e,0).byte.from,to:(0,Qr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Hs(),await 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:Dt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ce(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,d)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Hs();let c=this.onSomeTemplateDataLoaded({dataView:l,loaded:d,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Dt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,js.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),d=ca(n.mime).parseFeedableSegmentChunk(l,this.isLive);d?.byteLength&&(u.status="partially_fed",o.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),o.fedBytes+=d.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){await n();continue}let d=l.byte.from-r,c=l.byte.to-r,p=c-d+1,m=d<a,f=c<=a;if(!m)continue;let b=ca(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+d,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):await n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-d),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+d+u.feedingBytes,u.loadedBytes-u.feedingBytes),v=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);v?.byteLength&&(l.status="partially_fed",u.feedingBytes+=v.byteLength,await this.sourceBufferTaskQueue.append(v,s)&&!s.aborted?(u.fedBytes+=v.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(ne(this.sourceBuffer)||!de(this.mediaSource,this.sourceBuffer))){!this.isLive&&H$.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Rt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Rt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Dt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",ol(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())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");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[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 r=this.representations.get(e);r&&(this.initLoadIdleCallback=Qu(()=>(0,rS.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?Mt(this.destroyAbortController.signal,async function*(){let o=pl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ca(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:d}=o,c=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,c);let p=d;this.isLive&&ce(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:Dt.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,r=!1){if(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ne(e))return!1;let a=[],s=0,n=u=>{u.sort((d,c)=>d.from-c.from);let l=[u[0]];for(let d=1;d<u.length;d++){let{from:c,to:p}=u[d],m=l[l.length-1];m.to>=c?m.to=Math.max(m.to,p):l.push(u[d])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=ol(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 d=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(d||c)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let m of p)(0,js.default)(["none","partially_ejected"],m.status)&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.time.to)>=Math.round(d)&&c++;if(c===this.segments.size){let p={time:{from:l,to:d},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 this.segments.values())for(let d of l)d.time.from>=e+u&&d.status==="fed"&&o(d)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,d)=>l||d,!1):!1}async abortBuffer(){if(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ne(e)?0:it(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)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)));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||!this.sourceBuffer||!de(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)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=Qu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Dt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ne(this.sourceBuffer)||!de(this.mediaSource,this.sourceBuffer)||ne(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 this.segments.values())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(d=>d.from-t<=n&&d.to+t>=o),l=e.filter(d=>n>=d.from&&n<d.to-t||o>d.from+t&&o<=d.to);u||(l.length===1?a.status="partially_ejected":this.gaps.some(d=>d.from===a.time.from||d.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var ha=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var iS=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 ma,assertNever as sS,fromEvent as nS,merge as W$,now as fa,Subscription as Y$,ValueSubject as hl,flattenObject as Gr}from"@vkontakte/videoplayer-shared";var aS=i=>{let e=new URL(i);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Gs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new hl(void 0);this.lastConnectionReused$=new hl(void 0);this.lastRequestFirstBytes$=new hl(void 0);this.abortAllController=new se;this.subscription=new Y$;this.fetchManifest=ma(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ha(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=aS(r));let a=yield Ge(r,{signal:this.abortAllController.signal}).catch(ba);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=ma(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,d=new Headers,c=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let S=new URL(l,location.href);S.searchParams.append("bytes",`${r.from}-${r.to}`),l=S.toString();break}default:sS(t)}this.requestQuic&&(l=ha(l));let p=this.abortAllController.signal,m;if(n){let S=new se;if(m=W$(nS(this.abortAllController.signal,"abort"),nS(n,"abort")).subscribe(()=>{try{S.abort()}catch(P){ba(P)}}),this.abortAllController.signal.aborted||n.aborted)try{S.abort()}catch(P){ba(P)}p=S.signal}let f=fa();c.log("startRequest",Gr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield Ge(l,{priority:s,headers:d,signal:p}).catch(ba),g=fa();if(!b)return c.error("error",{message:"No response in request"}),c.end(),m?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){m?.unsubscribe();let S=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:S}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){m?.unsubscribe();let S=fa(),P={requestStartedAt:f,requestEndedAt:S,duration:S-f};return c.log("endRequest",Gr(P)),c.end(),b.arrayBuffer()}let[v,k]=b.body.tee(),x=v.getReader();o&&this.throughputEstimator?.trackStream(k,u);let R=0,y=new Uint8Array(0),I=!1,A=S=>{m?.unsubscribe(),I=!0,ba(S)},Q=ma(p,async function*({done:S,value:P}){if(R===0&&this.lastRequestFirstBytes$.next(fa()-f),p.aborted){m?.unsubscribe();return}if(!S&&P){let U=new Uint8Array(y.length+P.length);U.set(y),U.set(P,y.length),y=U,R+=P.byteLength,a?.(new DataView(y.buffer),R),yield x?.read().then(Q,A)}}.bind(this));yield x?.read().then(Q,A),m?.unsubscribe();let N=fa(),q={failed:I,requestStartedAt:f,requestEndedAt:N,duration:N-f};return I?(c.error("endRequest",Gr(q)),c.end(),null):(c.log("endRequest",Gr(q)),c.end(),y.buffer)}.bind(this));this.fetchByteRangeRepresentation=ma(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,d;e.indexRange&&(l=e.indexRange.from,d=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(d,s))),n=Math.min(n,0);let c=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!c)return null;let p=new DataView(c,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let m=t.parseInit(p),f=e.indexRange??t.getIndexRange(m);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(c,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,m,f);return{init:m,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=ma(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}=iS(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:sS(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ba=i=>{if(!da(i))throw i};var ar=(i,e,t)=>t*e+(1-t)*i,ml=(i,e)=>i.reduce((t,r)=>t+r,0)/e,oS=(i,e,t,r)=>{let a=0,s=t,n=ml(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 z$,ValueSubject as uS}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 uS(e.initial),this.debounced$=new uS(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new le(`raw_${t}`),this.smoothedSeries$=new le(`smoothed_${t}`),this.reportedSeries$=new le(`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)&&(z$(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 Ws=class extends Ct{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ar(this.slow,e,this.params.emaAlphaSlow),this.fast=ar(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Ys=class extends Ct{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ml(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ar(this.emaSmoothed,e,this.params.emaAlpha);let r=oS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var zs=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?ar(this.smoothed,t,this.params.emaAlpha):t}};var sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Ws({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Ys({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 zs({initial:e,label:"liveEdgeDelay",...t})}};var fl=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};import{isNullable as K$,ValueSubject as X$}from"@vkontakte/videoplayer-shared";var ga=class i{constructor(e,t){this.currentRepresentation$=new X$(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(!K$(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&&ce(t.segmentReference))}};var sM=["timeupdate","progress","play","seeked","stalled","waiting"],nM=["timeupdate","progress","loadeddata","playing","seeked"];var Xs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new pS;this.representationSubscription=new pS;this.state$=new $("none");this.currentVideoRepresentation$=new z(void 0);this.currentVideoRepresentationInit$=new z(void 0);this.currentAudioRepresentation$=new z(void 0);this.currentVideoSegmentLength$=new z(0);this.currentAudioSegmentLength$=new z(0);this.error$=new dS;this.lastConnectionType$=new z(void 0);this.lastConnectionReused$=new z(void 0);this.lastRequestFirstBytes$=new z(void 0);this.currentLiveTextRepresentation$=new z(null);this.isLive$=new z(!1);this.liveDuration$=new z(0);this.liveAvailabilityStartTime$=new z(void 0);this.bufferLength$=new z(0);this.liveLatency$=new z(void 0);this.liveLoadBufferLength$=new z(0);this.livePositionFromPlayer$=new z(0);this.isLowLatency$=new z(!1);this.isActiveLowLatency$=new z(!1);this.currentStallDuration$=new z(0);this.videoLastDataObtainedTimestamp$=new z(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new dS;this.gapWatchdogActive=!1;this.destroyController=new se;this.initManifest=bl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ae(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:Vt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=bl(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:Vt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Zv(e??"",this.manifestUrlString)}catch(n){let o=Qg(e)??{id:"ManifestParsing",category:Vt.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)&&ht()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let n=(t.duration??0)/1e3;this.liveDuration$.next(-1*n)}let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:c,codecs:p})=>r(n,c,p)),l=new Set(u.map(({codecs:c})=>c)),d=Eg(l);if(d&&(a[n]=u.filter(({codecs:c})=>c.startsWith(d))),n==="video"){let c=this.tuning.preferHDR,p=a.video.some(f=>f.hdr),m=a.video.some(f=>!f.hdr);eM.isHDR&&c&&p?a.video=a.video.filter(f=>f.hdr):m&&(a.video=a.video.filter(f=>!f.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",Sa(s)),s}.bind(this));this.initRepresentations=bl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",Sa({initialVideo:e,initialAudio:t,sourceHls:r})),nr(this.manifest),nr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=c=>{this.representationSubscription.add(or(c,"error").pipe(va(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Vt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?bg():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Os())if(r){let c=document.createElement("source");a(c),c.type="application/x-mpegurl",c.src=r.url,this.element.appendChild(c)}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((c,p)=>[...c,...p.representations],[]);if(this.videoBufferManager=new pa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],cS(t)){let c=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new pa("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}ga.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ga(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.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(gl(1e3).subscribe(c=>{if(this.element?.paused){let p=Es(this.manifestUrlString,2);this.manifestUrlString=ae(this.manifestUrlString,p+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ur(...nM.map(c=>or(this.element,c))).pipe(ya(c=>this.element?it(this.element.buffered,this.element.currentTime*1e3):0),Ks(),iM(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ur(or(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Ks()).subscribe(p=>{this.isManualDecreasePlaybackInLive()||fl(this.element,1)})),this.representationSubscription.add(Wr({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(va(({bufferLength:p,isActiveLowLatency:m})=>m&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(Wr({isActiveLowLatency:this.isActiveLowLatency$.pipe(Ks()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(va(({isActiveLowLatency:p,currentLowLatencySegmentLength:m})=>p&&!!m)).subscribe(({currentLowLatencySegmentLength:p})=>{let m=this.liveDuration$.getValue()-p/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(Wr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(va(({isLive:p})=>p),ya(p=>({...p})),Ks((p,m)=>m.bufferLength<p.bufferLength),ya(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=Es(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Wr({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:p,isActiveLowLatency:m})=>{if(!m)return;let f=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=p-f;if(this.isManualDecreasePlaybackInLive())return;let k=1;Math.abs(v)>b&&(k=1+Math.sign(v)*g),fl(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(p=>{let m=0;if(p){let f=(this.element?.currentTime??0)*1e3;m=Math.min(...this.bufferManagers.map(g=>g.getLiveSegmentsToLoadState(this.manifest)?.to??f))-f}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let c=0;this.representationSubscription.add(Wr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(aM(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(nr(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,b=Es(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),k=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,R=isFinite(p)?p:m,y=this.isActiveLowLatency$.getValue(),I=g<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(y&&I);let A="none";if(y?A="active_low_latency":this.isLowLatency$.getValue()&&I?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(Q=>Q.proceedLowLatencyLive()),A="active_low_latency"):b!==0&&R<v?A="live_forward_buffering":R<v+x&&(A="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),A==="live_forward_buffering"||A==="live_with_target_offset"){let Q=c-(v+k),N=this.normolizeLiveOffset(Math.trunc(b+Q/f)),q=Math.abs(N-b),S;!p||q<=this.tuning.dashCmafLive.offsetCalculationError?S=b:N>0&&q>this.tuning.dashCmafLive.offsetCalculationError?S=N:S=0,this.manifestUrlString=ae(this.manifestUrlString,S,2)}A!=="none"&&A!=="active_low_latency"&&(c=0,this.updateLive())}))}let l=ur(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(ya(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),d=ur(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(ya(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue())));if(this.representationSubscription.add(ur(this.forceEnded$,Wr({allBuffersFull:l,someBufferEnded:d}).pipe(va(({allBuffersFull:c,someBufferEnded:p})=>c&&p))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{this.source?.endOfStream(),this.bufferManagers.forEach(c=>c.warmUpMediaSource())}catch(c){this.error$.next({id:"EndOfStream",category:Vt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(ur(...this.bufferManagers.map(c=>c.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(c=>this.source?.addEventListener("sourceopen",c))),!this.isLive$.getValue()){let c=[this.manifest.duration??0,...(0,vl.default)((0,vl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let m=[];return p.duration&&m.push(p.duration),ce(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...c)/1e3}this.audioBufferManager&&cS(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=gl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Vt.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 Gs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=sr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){nr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=ae(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(){nr(this.element),this.state$.setState("running"),this.subscription.add(ur(...sM.map(e=>or(this.element,e)),or(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Vt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(or(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(or(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Rt(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=rM(),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,d=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,c=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||c)&&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",Sa(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=gl(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Vt.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){let a={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?a?.switchToWithPreviousAbort(t,r):a?.switchTo(t,r):a?.switchToOld(t,r)}async seek(e,t){nr(this.element),nr(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),Rt(this.element.buffered,r)||await Promise.all([this.videoBufferManager.abort(),this.audioBufferManager?.abort()]),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Sa({requestedPosition:e,forcePrecise:t,position:r}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>{URL.revokeObjectURL(e.src),e.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.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=tM(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.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",Sa(t)))}}};var Js=class{constructor(e,t){this.fov=e,this.orientation=t}};var Zs=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 hS=`attribute vec2 a_vertex;
|
|
71
71
|
attribute vec2 a_texel;
|
|
72
72
|
|
|
73
73
|
varying vec2 v_texel;
|
|
@@ -121,6 +121,6 @@ void main(void) {
|
|
|
121
121
|
// sample using new coordinates
|
|
122
122
|
gl_FragColor = texture2D(u_texture, tc);
|
|
123
123
|
}
|
|
124
|
-
`;var en=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 Js(this.params.fov,this.params.orientation),this.cameraRotationManager=new Zs(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(hS,this.gl.VERTEX_SHADER),r=this.createShader(mS,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,d=t+a,c=e-r,p=t+a;return[s,n,o,u,l,d,c,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 lM,now as fS,Subscription as cM,filter as dM,combine as bS,ValueSubject as Sl,isNonNullable as pM}from"@vkontakte/videoplayer-shared";var yl=class{constructor(){this.isSeeked$=new Sl(!1);this.isBuffering$=new Sl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new cM;this.severeStallOccurred$=new Sl(!1)}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(bS({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(dM(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(bS({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(lM(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:a,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=fS(),d=a&&this.currentStallsCount>=a,c=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(d||c)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,pM(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=fS(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},gS=yl;import{combine as hM,map as mM,observeElementSize as fM,Subscription as bM,ValueSubject as Tl,noop as gM}from"@vkontakte/videoplayer-shared";var tn=class{constructor(){this.subscription=new bM;this.pipSize$=new Tl(void 0);this.videoSize$=new Tl(void 0);this.elementSize$=new Tl(void 0);this.pictureInPictureWindowRemoveEventListener=gM}connect({observableVideo:e,video:t}){let r=a=>{let s=a.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(fM(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:a})=>{this.pipSize$.next({width:a.width,height:a.height}),a.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{a.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(hM({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(mM(({videoSize:a,inPip:s,pipSize:n})=>s?n:a)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var lr=class{constructor(e){this.subscription=new xM;this.videoState=new $("stopped");this.droppedFramesManager=new Ds;this.stallsManager=new gS;this.elementSizeManager=new tn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new wi;this.audioTrackSwitchHistory=new wi;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.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"),T(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"),T(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&T(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"&&T(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"&&T(this.params.desiredState.playbackState,"paused");return;default:return yM(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new en(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=me(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 Xs({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=ge(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Il.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(vS(d=>!!d.length),yS()).subscribe(d=>{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:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(El(d=>d.to.state!=="none"),Ia());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ia()),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(vS(SS),yS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(El(d=>d.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(tt(this.video,t.isLooped,a)),this.subscription.add(be(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,a)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(TM(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of c.audio){m.push(sl(f));let b=[];for(let g of f.representations){let v=Qv(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(m)}let p=[];for(let m of c.video){p.push(nl(m));let f=[];for(let b of m.representations){let g=jv({...b,streamId:m.id});g&&(f.push(g),this.videoTracksMap.set(g,{stream:m,representation:b}))}this.videoStreamsMap.set(m,f)}this.params.output.availableVideoStreams$.next(p);for(let m of c.text)for(let f of m.representations){let b=Gv(m,f);this.textTracksMap.set(b,{stream:m,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 d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let o=d=>e.error$.next({id:"RepresentationSwitch",category:Il.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(rn(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.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,EM(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,TS.default)(["manifest_ready","running"],d)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[m,f]=p,b=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===m.id);SS(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),d==="manifest_ready")this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",m.id).catch(o),f){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,v).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ia()).subscribe(d=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(nl(m))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ia()).subscribe(d=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(sl(m))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},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(El(({to:d})=>d==="ready"),Ia());this.subscription.add(rn(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,xl(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(rn(u,this.player.state$.stateChangeEnded$,xl(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=rn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xl(["init"])).pipe(IM(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:A})=>A===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:A})=>A===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=it(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(c/Math.min(p,m||1/0),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:A})=>A===b?.id)??this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let A=Ls(n,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,A?.bitrate??-1/0)}if(o){let A=Ls(o,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,A?.bitrate??-1/0)}}let w=Lt(d,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:f,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}),x=r?w??n:n??w,R=g&&Db(x,d,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),y=this.videoTracksMap.get(x)?.representation,I=R&&this.audioTracksMap.get(R)?.representation;if(y&&I)return[y,I];if(y&&!I&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Il.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.params.output.currentVideoStream$.next(void 0),fe(this.video),this.tracer.end()}};var Ea=class extends lr{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 IS,interval as PM,map as ES}from"@vkontakte/videoplayer-shared";var xa=class extends lr{constructor(e){super(e),this.liveOffset=new dt,this.textTracksManager.destroy()}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(ES(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(IS({interval:PM(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(IS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ES(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Wv(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 PS=D(Is(),1);import{assertNever as Pa,assertNonNullable as xS,debounce as wM,ErrorCategory as an,filter as kM,isNonNullable as AM,isNullable as LM,map as sn,merge as RM,Observable as $M,observableFrom as MM,Subscription as DM,videoSizeToQuality as CM}from"@vkontakte/videoplayer-shared";var Ye={};var Yr=(i,e)=>new $M(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),wa=class{constructor(e){this.subscription=new DM;this.videoState=new $("initializing");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:Pa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Pa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Pa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Pa(e)}break;default:Pa(t)}};this.textTracksManager=new Ce(e.source.url),this.video=me(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),fe(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:an.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,PS.default)(import("hls.js").then(a=>{e||(Ye.Hls=a.default,Ye.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){xS(Ye.Hls,"hls.js not loaded"),this.hls=new Ye.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){xS(Ye.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:an.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=ge(this.video),s=(l,d)=>this.subscription.add(l.subscribe(d,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(tt(this.video,e.isLooped,r)),this.subscription.add(be(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(De(this.video,e.playbackRate,a.playbackRateState$,r)),s(Be(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(sn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Yr(this.hls,Ye.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:an.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"),T(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(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(Yr(this.hls,Ye.Events.MANIFEST_PARSED).pipe(sn(({levels:l})=>l.reduce((d,c)=>{let p=c.name||c.height.toString(10),{width:m,height:f}=c,b=kt(c.attrs.QUALITY??"")??CM({width:m,height:f});if(!b)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:m,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:c}),d.push(v),d},[]))),t.availableVideoTracks$),s(Yr(this.hls,Ye.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,m=c.attrs.URI||"",f=c.lang;d.push({id:p,url:m,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Yr(this.hls,Ye.Events.LEVEL_LOADING).pipe(sn(({url:l})=>Z(l))),t.hostname$),s(Yr(this.hls,Ye.Events.FRAG_CHANGED),l=>{let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.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(this.trackLevels.values()).find(({level:d})=>d===l)?.track,o=Yr(this.hls,Ye.Events.LEVEL_SWITCHED).pipe(sn(({level:l})=>n(this.hls.levels[l])));o.pipe(kM(AM)).subscribe(t.currentVideoTrack$,r),this.subscription.add(xt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(LM(l))return;let d=this.trackLevels.get(l.id)?.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,m=this.hls.levels[p];!m||d.bitrate>m.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{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=RM(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,MM(["init"])).pipe(wM(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 ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:an.DOM,thrown:t}))||(this.videoState.setState("paused"),T(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"),T(this.params.desiredState.playbackState,"stopped",!0)}};var wS="X-Playback-Duration",Pl=async i=>{let e=await Ge(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(wS)?parseInt(e.headers.get(wS),10):void 0};import{assertNever as QM,combine as GM,debounce as WM,ErrorCategory as un,filter as YM,filterChanged as zM,isNonNullable as LS,isNullable as ln,map as RS,merge as KM,observableFrom as XM,Subscription as JM,ValueSubject as Al,VideoQuality as ZM}from"@vkontakte/videoplayer-shared";var kl=D(Lo(),1);import{videoSizeToQuality as VM,getExponentialDelay as BM}from"@vkontakte/videoplayer-shared";var OM=i=>{let e=null;if(i.QUALITY&&(e=kt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=VM({width:t,height:r})}return e??null},_M=(i,e)=>{let t=i.split(`
|
|
125
|
-
`),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,
|
|
126
|
-
`),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(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!r.segmentStartTime){let c=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.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);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(FM(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:a}=t[t.length-1].time;if(e<r||e>a)return;a-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new se;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:jM.WTF,thrown:t,message:e})}};var ka=class{constructor(e){this.subscription=new JM;this.videoState=new $("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Al([]);this.liveOffset=new dt;this.manifestStartTime$=new Al(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"),T(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),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&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?T(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),T(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"&&T(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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return QM(t)}};this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ZM.INVARIANT,url:this.params.source.url};let t=(r,a)=>nn(r,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 on(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ce(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:un.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:un.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),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 Al(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:un.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ge(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(be(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,r)),s(Be(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"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(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.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(zM(),RS(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&LS(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(m=>m.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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(GM({startTime:this.manifestStartTime$.pipe(YM(LS)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(RS(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r));let n=KM(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,XM(["init"])).pipe(WM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),fe(this.video)}prepare(){let e=this.selectManifest();if(ln(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,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&a.searchParams.set(d,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ae(a.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Pl(n).then(o=>{if(!ln(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(ln(u)||!isFinite(u))&&Ge(n).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let c=new URL(d,n).toString();Pl(c).then(p=>{ln(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:un.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()}generateLiveUrl(){let e=ae(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 eD,debounce as tD,ErrorCategory as Ll,fromEvent as Rl,isNonNullable as rD,isNullable as iD,map as $S,merge as MS,observableFrom as DS,Subscription as aD,ValueSubject as sD,VideoQuality as nD,clientChecker as oD}from"@vkontakte/videoplayer-shared";var Aa=class{constructor(e){this.subscription=new aD;this.videoState=new $("stopped");this.manifests$=new sD([]);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"),T(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?T(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),T(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"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return eD(t)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:nD.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),nn(ae(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:Ll.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||!a.from)&&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:Ll.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ge(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($S(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(be(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&rD(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===m);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Z(f.url)))}let c=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(c!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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($S(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r)),!oD.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(MS(Rl(o,"addtrack"),Rl(o,"removetrack"),Rl(o,"change"),DS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=MS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,DS(["init"])).pipe(tD(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),fe(this.video)}prepare(){let e=this.selectManifest();if(iD(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(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ll.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var BS=D(Pr(),1),$l=D(Br(),1),OS=D(Zt(),1);import{assertNever as uD,assertNonNullable as CS,debounce as lD,ErrorCategory as VS,isHigherOrEqual as cD,isLowerOrEqual as dD,isNonNullable as pD,merge as hD,observableFrom as mD,Subscription as fD,map as bD}from"@vkontakte/videoplayer-shared";var La=class{constructor(e){this.subscription=new fD;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Ce;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"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?T(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),T(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"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return uD(e)}};this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),(0,BS.default)(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,$l.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:VS.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ge(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(bD(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(be(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,r)),s(Be(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(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&&pD(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 d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=hD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,mD(["init"])).pipe(lD(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),fe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;CS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];CS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ha(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Z(t))}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:VS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=()=>{let d=Lt(n,{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(d)},a=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,$l.default)(this.trackUrls).map(d=>d.track);if(!a||!s||ks({limits:e,lowestAvailableQuality:(0,OS.default)(n,-1)?.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?dD(a,e.max):!0,u=e.min?cD(a,e.min):!0;if(o&&u)return;let l=n.find(d=>Ib({limits:e,track:d}));l?t(l):r()}};import{assertNever as NS,debounce as yD,merge as FS,observableFrom as TD,Subscription as ID,map as qS,ValueSubject as ED,ErrorCategory as Dl,VideoQuality as xD}from"@vkontakte/videoplayer-shared";import{ErrorCategory as gD}from"@vkontakte/videoplayer-shared";var _S=["stun:videostun.mycdn.me:80"],vD=1e3,SD=3,Ml=()=>null,cn=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=Ml;this.externalStopCallback=Ml;this.externalErrorCallback=Ml;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:_S}]};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:gD.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),vD)}normalizeOptions(e={}){let t={stunServerList:_S,maxRetryNumber:SD,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ra=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new ED(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"),T(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"),T(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"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return NS(e)}};this.subscription=new ID,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=me(e.container,e.tuning),this.liveStreamClient=new cn(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),fe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Dl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};FS(this.videoState.stateChangeStarted$.pipe(qS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(qS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ge(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(Be(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(be(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 NS(n.to)}},r)).add(FS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,TD(["init"])).pipe(yD(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:xD.INVARIANT}),this.video.srcObject=e,T(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:Dl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Dl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var $a=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 Bt,ErrorCategory as dn,filter as WS,isNonNullable as YS,isNullable as MD,map as DD,merge as CD,once as VD,Subject as Ie,Subscription as zS,ValueSubject as M,flattenObject as KS}from"@vkontakte/videoplayer-shared";import{Observable as PD,map as US,Subscription as wD,Subject as kD}from"@vkontakte/videoplayer-shared";var HS=i=>new PD(e=>{let t=new wD,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(US(({from:l,to:d})=>`${l}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(US(({type:l})=>l!==void 0)),n=new kD,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 AD,Subscription as LD,combine as RD,filter as QS,once as GS}from"@vkontakte/videoplayer-shared";function jS(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as $D}from"@vkontakte/videoplayer-shared";var zr=class i{constructor(e,t,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.destroyController=new se;this.subscriptions=new LD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(QS(s=>!!s.type),GS()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){$D.isSafari&&e!=="MPEG"||this.subscriptions.add(RD({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(QS(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),GS()).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=jS();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:AD.VIDEO_PIPELINE,message:e?.message??`${i.errorId} exception`,thrown:e})}};var BD={chunkDuration:5e3,maxParallelRequests:5},Da=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new Ie;this.noAvailableProvidersError$=new Ie;this.volumeMultiplierError$=new Ie;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 Ie,warning$:new Ie,willSeekEvent$:new Ie,soundProhibitedEvent$:new Ie,seekedEvent$:new Ie,loopedEvent$:new Ie,endedEvent$:new Ie,firstBytesEvent$:new Ie,loadedMetadataEvent$:new Ie,firstFrameEvent$:new Ie,canplay$:new Ie,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(""),getCurrentTime$:new M(null)};this.subscription=new zS;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=yg([...Ig(this.params.tuning),...Tg(this.params.tuning)],this.params.tuning).filter(l=>YS(e.sources[l])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(l=>!(0,Cl.default)(a,l)),...t.filter(l=>(0,Cl.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",KS(s)),this.screenFormatsIterator=new $a(s);let n=[...Fu(!0),...Fu(!1)];this.chromecastFormatsIterator=new $a(n.filter(l=>YS(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&zr.isSupported()&&(this.volumeMultiplierManager=new zr(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(MD(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:dn.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 Ma(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 Bt(o),new Ea({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Bt(o),new xa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Bt(o),qr||!this.params.tuning.useHlsJs?new Aa({...n,source:o}):new wa({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Bt(o),new ka({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Bt(o),new La({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Yb({...n,source:o,config:{...BD,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Ra({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 Ma(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 Bt(o),new Ii({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 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 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,JS.default)((0,XS.default)(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new zS,t=!1,r=0;return e.add(CD(this.providerOutput.error$.pipe(WS(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),HS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(DD(a=>({id:`ProviderHangup:${a}`,category:dn.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(WS(({to:s})=>s==="playing"),VD()).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===dn.NETWORK,u=a.category===dn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(r++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",KS(n))})),e}};import{fromEvent as pn,once as OD,combine as _D,Subscription as ZS,ValueSubject as Vl,map as ND,filter as FD,isNonNullable as hn,now as Ae,safeStorage as Bl}from"@vkontakte/videoplayer-shared";var qD=5e3,ey="one_video_throughput",ty="one_video_rtt",Ca=window.navigator.connection,ry=()=>{let i=Ca?.downlink;if(hn(i)&&i!==10)return i*1e3},iy=()=>{let i=Ca?.rtt;if(hn(i)&&i!==3e3)return i},ay=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Ol=class i{constructor(e){this.subscription=new ZS;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(ey)||(e.useBrowserEstimation?ry():void 0)||qD,r=i.load(ty)??(e.useBrowserEstimation?iy():void 0)??0;if(this.throughput$=new Vl(t),this.rtt$=new Vl(r),this.rttAdjustedThroughput$=new Vl(ay(t,r,e.rttPenaltyRequestSize)),this.throughput=sr.getSmoothedValue(t,-1,e),this.rtt=sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=ry();n&&this.throughput.next(n);let o=iy();hn(o)&&this.rtt.next(o)};Ca&&"onchange"in Ca&&this.subscription.add(pn(Ca,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Bl.set(ey,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Bl.set(ty,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(_D({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(ND(({throughput:a,rtt:s})=>ay(a,s,e.rttPenaltyRequestSize)),FD(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=Ae(),a=new ZS;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(pn(e,"progress").pipe(OD()).subscribe(s=>{t=s.loaded,r=Ae()}));break;case 1:case 0:a.add(pn(e,"loadstart").subscribe(()=>{t=0,r=Ae()}));break}a.add(pn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ae(),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=Ae(),n=0,o=Ae(),u=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(a,Ae()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=Ae();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=c.byteLength,s=Ae()}else n+=c.byteLength;o=Ae()}else a+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ae()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ae()-o,this.concurrentDownloads.size),n=0,o=Ae());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=Bl.get(e);if(hn(t))return parseInt(t,10)??void 0}},sy=Ol;import{fillWithDefault as UD,VideoQuality as mn}from"@vkontakte/videoplayer-shared";var ny={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:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:mn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:mn.Q_720P,trafficSavingLimit:mn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:mn.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:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},oy=i=>({...UD(i,ny),configName:[...i.configName??[],...ny.configName]});import{assertNonNullable as fn,combine as bt,ErrorCategory as bn,filter as pe,filterChanged as _,fromEvent as Nl,isNonNullable as zD,isNullable as KD,Logger as XD,map as O,mapTo as dy,merge as Ot,now as gn,once as at,Subject as H,Subscription as py,tap as hy,ValueSubject as E,isHigher as JD,isInvariantQuality as my,flattenObject as _t,throttle as Fl,getTraceSubscriptionMethod as fy,Tracer as ZD,InternalsExposure as e0}from"@vkontakte/videoplayer-shared";import{merge as HD,map as jD,filter as uy,isNonNullable as QD}from"@vkontakte/videoplayer-shared";var _l=({seekState:i,position$:e})=>HD(i.stateChangeEnded$.pipe(jD(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),uy(QD)),e.pipe(uy(()=>i.getState().state==="none")));import{assertNonNullable as GD}from"@vkontakte/videoplayer-shared";var ly=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return GD(e,`Wrong container or containerId {${i.container}}`),e};import{filter as WD,once as YD}from"@vkontakte/videoplayer-shared";var cy=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(WD(a=>a.length>0),YD()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var vn=class{constructor(e={configName:[]},t=ZD.createRootTracer(!1)){this.subscription=new py;this.logger=new XD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!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 E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),predefinedQualityLimitType$:new E("unknown"),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),liveLatency$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(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 E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:yb,getCurrentTime$:new E(null)};if(this.initLogs(),this.tuning=oy(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ya({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new sy(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new e0("CORE"),this.internalsExposure.expose({player:this})),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,(m,f)=>{let b=typeof f;return(0,by.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),d=`Player.${String(a)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:bn.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",_t(r)),this.domContainer=ly(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Da({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.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),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(),this.internalsExposure?.destroy()}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&&!$i()?(this.tracer.log("request play from hidden tab"),Nl(document,"visibilitychange").pipe(at()).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-.2),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){fn(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(pe(r=>r.length>0),at()).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",_t(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,a;switch(e){case"high_quality":a={min:t,max:void 0};break;case"traffic_saving":a={max:r,min:void 0};break;default:a={max:void 0,min:void 0}}return this.setAutoQualityLimits(a),this}setPlaybackRate(e){fn(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 cy(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(KD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return zD(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(Ot(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(O(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Pu({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pe(({from:e})=>e==="stopped"),at()).subscribe(()=>{this.initedAt=gn(),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:bn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(at()).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(O(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(O(n=>n.destination),_()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(bt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(O(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>my(u)?1:my(l)?-1:JD(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(_()).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(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(_()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(_()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(_()).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(O(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(bt({hasLiveOffsetByPaused:Ot(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(O(n=>n.to),_(),O(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(bt({atLiveEdge:bt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:_l({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(O(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),_(),hy(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(O(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(bt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(O(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),_(),hy(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(O(n=>n.muted),_()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(O(n=>n.volume),_()).subscribe(this.info.volume$)).add(_l({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ot(e.providerOutput.endedEvent$.pipe(dy(!0)),e.providerOutput.seekedEvent$.pipe(dy(!1))).pipe(_()).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(O(n=>({id:n?`No${n}`:"NoProviders",category:bn.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(at(),O(n=>n??gn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(at(),O(()=>gn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(at(),O(()=>gn()-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 E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new E(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(pe(({to:n})=>n==="playing"),at()).subscribe(()=>r.next(!1)));let a=0,s=Ot(e.providerOutput.isBuffering$,t,r).pipe(O(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),_());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(Ot(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(Ot(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(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(O(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new py;this.subscription.add(t),this.subscription.add(e.current$.pipe(_((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(pe(r=>r.length>0),at()).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=Lt(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(Ot(this.desiredState.videoTrack.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(O(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;fn(this.providerContainer),fn(e),Sb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>vb(t)),this.providerContainer.current$.subscribe(({type:t})=>Pi("provider",t)),e.duration$.subscribe(t=>Pi("duration",t)),e.availableVideoTracks$.pipe(pe(t=>!!t.length),at()).subscribe(t=>Pi("tracks",t)),this.events.fatalError$.subscribe(new le("fatalError")),this.events.managedError$.subscribe(new le("managedError")),e.position$.subscribe(new le("position")),e.currentVideoTrack$.pipe(O(t=>t?.quality)).subscribe(new le("quality")),this.info.currentBuffer$.subscribe(new le("buffer")),e.isBuffering$.subscribe(new le("isBuffering"))].forEach(t=>this.subscription.add(t)),Pi("codecs",Sg())}initTracerSubscription(){let e=fy(this.tracer.log.bind(this.tracer)),t=fy(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(_()).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(bt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(pe(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),_((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(pe(r=>r>0),_()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(pe(r=>r>0),_()).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(bt({currentBuffer:this.info.currentBuffer$.pipe(pe(r=>r.end>0),_((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe(_())}).pipe(Fl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(_()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(_()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(_()).subscribe(e("canChangePlaybackSpeed"))).add(bt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(pe(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),Fl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(_(),pe(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(_(),pe(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(_()).subscribe(e("muted"))).add(this.info.volume$.pipe(_()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(_(),pe(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(bt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(pe(({throughputEstimation:r,rtt:a})=>!!r&&!!a),Fl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(_(),pe(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:bn.DOM,message:String(a)})})};this.subscription.add(Ot(Nl(document,"visibilitychange"),Nl(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",_t({quality:t,availableTracks:_t(e),track:_t(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 ez,Observable as tz,Subject as rz,ValueSubject as iz,VideoQuality as az}from"@vkontakte/videoplayer-shared";var sz=`@vkontakte/videoplayer-core@${Hl}`;export{qa as ChromecastState,Tn as HttpConnectionType,tz as Observable,he as PlaybackState,vn as Player,Ua as PredefinedQualityLimits,sz as SDK_VERSION,rz as Subject,ez as Subscription,In as Surface,Hl as VERSION,iz as ValueSubject,yt as VideoFormat,az as VideoQuality};
|
|
124
|
+
`;var en=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 Js(this.params.fov,this.params.orientation),this.cameraRotationManager=new Zs(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(hS,this.gl.VERTEX_SHADER),r=this.createShader(mS,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,d=t+a,c=e-r,p=t+a;return[s,n,o,u,l,d,c,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 lM,now as fS,Subscription as cM,filter as dM,combine as bS,ValueSubject as Sl,isNonNullable as pM}from"@vkontakte/videoplayer-shared";var yl=class{constructor(){this.isSeeked$=new Sl(!1);this.isBuffering$=new Sl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new cM;this.severeStallOccurred$=new Sl(!1)}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(bS({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(dM(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(bS({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(lM(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:a,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=fS(),d=a&&this.currentStallsCount>=a,c=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(d||c)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,pM(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=fS(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},gS=yl;import{combine as hM,map as mM,observeElementSize as fM,Subscription as bM,ValueSubject as Tl,noop as gM}from"@vkontakte/videoplayer-shared";var tn=class{constructor(){this.subscription=new bM;this.pipSize$=new Tl(void 0);this.videoSize$=new Tl(void 0);this.elementSize$=new Tl(void 0);this.pictureInPictureWindowRemoveEventListener=gM}connect({observableVideo:e,video:t}){let r=a=>{let s=a.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(fM(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:a})=>{this.pipSize$.next({width:a.width,height:a.height}),a.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{a.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(hM({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(mM(({videoSize:a,inPip:s,pipSize:n})=>s?n:a)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var lr=class{constructor(e){this.subscription=new xM;this.videoState=new $("stopped");this.droppedFramesManager=new Ds;this.stallsManager=new gS;this.elementSizeManager=new tn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new ki;this.audioTrackSwitchHistory=new ki;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.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"),T(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"),T(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&T(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"&&T(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"&&T(this.params.desiredState.playbackState,"paused");return;default:return yM(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new en(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:e.projectionData?.pose.yaw||0,y:e.projectionData?.pose.pitch||0,z:e.projectionData?.pose.roll||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=me(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 Xs({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=ge(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Il.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(vS(d=>!!d.length),yS()).subscribe(d=>{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:d})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(El(d=>d.to.state!=="none"),Ia());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ia()),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(vS(SS),yS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(El(d=>d.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(tt(this.video,t.isLooped,a)),this.subscription.add(be(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(De(this.video,t.playbackRate,r.playbackRateState$,a)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Be(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(TM(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of c.audio){m.push(sl(f));let b=[];for(let g of f.representations){let v=Qv(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(m)}let p=[];for(let m of c.video){p.push(nl(m));let f=[];for(let b of m.representations){let g=jv({...b,streamId:m.id});g&&(f.push(g),this.videoTracksMap.set(g,{stream:m,representation:b}))}this.videoStreamsMap.set(m,f)}this.params.output.availableVideoStreams$.next(p);for(let m of c.text)for(let f of m.representations){let b=Gv(m,f);this.textTracksMap.set(b,{stream:m,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 d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let o=d=>e.error$.next({id:"RepresentationSwitch",category:Il.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(rn(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.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,EM(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,TS.default)(["manifest_ready","running"],d)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[m,f]=p,b=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===m.id);SS(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),d==="manifest_ready")this.player.initRepresentations(m.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",m.id).catch(o),f){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,v).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSizeManager.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ia()).subscribe(d=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(nl(m))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ia()).subscribe(d=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===d);if(!c){e.currentAudioStream$.next(void 0);return}let[p,{stream:m}]=c,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===m.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(sl(m))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{if(d?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(c){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${c}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},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(El(({to:d})=>d==="ready"),Ia());this.subscription.add(rn(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,xl(["init"])).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(rn(u,this.player.state$.stateChangeEnded$,xl(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=rn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,xl(["init"])).pipe(IM(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:A})=>A===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:A})=>A===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=it(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(c/Math.min(p,m||1/0),1),b=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),g=[...this.audioStreamsMap.keys()].find(({id:A})=>A===b?.id)??this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let A=Ls(n,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,A?.bitrate??-1/0)}if(o){let A=Ls(o,d,this.audioStreamsMap.get(g)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,A?.bitrate??-1/0)}}let k=Lt(d,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:f,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}),x=r?k??n:n??k,R=g&&Db(x,d,this.audioStreamsMap.get(g)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),y=this.videoTracksMap.get(x)?.representation,I=R&&this.audioTracksMap.get(R)?.representation;if(y&&I)return[y,I];if(y&&!I&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Il.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),fe(this.video),this.tracer.end()}};var Ea=class extends lr{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 IS,interval as PM,map as ES}from"@vkontakte/videoplayer-shared";var xa=class extends lr{constructor(e){super(e),this.liveOffset=new dt,this.textTracksManager.destroy()}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(ES(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(IS({interval:PM(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(IS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(ES(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Wv(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 PS=D(Is(),1);import{assertNever as Pa,assertNonNullable as xS,debounce as kM,ErrorCategory as an,filter as wM,isNonNullable as AM,isNullable as LM,map as sn,merge as RM,Observable as $M,observableFrom as MM,Subscription as DM,videoSizeToQuality as CM}from"@vkontakte/videoplayer-shared";var Ye={};var Yr=(i,e)=>new $M(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),ka=class{constructor(e){this.subscription=new DM;this.videoState=new $("initializing");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:Pa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Pa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Pa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Pa(e)}break;default:Pa(t)}};this.textTracksManager=new Ce(e.source.url),this.video=me(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),fe(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:an.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,PS.default)(import("hls.js").then(a=>{e||(Ye.Hls=a.default,Ye.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){xS(Ye.Hls,"hls.js not loaded"),this.hls=new Ye.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){xS(Ye.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:an.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=ge(this.video),s=(l,d)=>this.subscription.add(l.subscribe(d,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(tt(this.video,e.isLooped,r)),this.subscription.add(be(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(De(this.video,e.playbackRate,a.playbackRateState$,r)),s(Be(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(sn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Yr(this.hls,Ye.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:an.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"),T(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(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(Yr(this.hls,Ye.Events.MANIFEST_PARSED).pipe(sn(({levels:l})=>l.reduce((d,c)=>{let p=c.name||c.height.toString(10),{width:m,height:f}=c,b=wt(c.attrs.QUALITY??"")??CM({width:m,height:f});if(!b)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:m,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:c}),d.push(v),d},[]))),t.availableVideoTracks$),s(Yr(this.hls,Ye.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let d=[];for(let c of l.subtitleTracks){let p=c.name,m=c.attrs.URI||"",f=c.lang;d.push({id:p,url:m,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(d)}}),s(Yr(this.hls,Ye.Events.LEVEL_LOADING).pipe(sn(({url:l})=>Z(l))),t.hostname$),s(Yr(this.hls,Ye.Events.FRAG_CHANGED),l=>{let{video:d,audio:c}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((c?.endPTS??0)-(c?.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(this.trackLevels.values()).find(({level:d})=>d===l)?.track,o=Yr(this.hls,Ye.Events.LEVEL_SWITCHED).pipe(sn(({level:l})=>n(this.hls.levels[l])));o.pipe(wM(AM)).subscribe(t.currentVideoTrack$,r),this.subscription.add(xt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(LM(l))return;let d=this.trackLevels.get(l.id)?.level;if(!d)return;let c=this.hls.levels.indexOf(d),p=this.hls.currentLevel,m=this.hls.levels[p];!m||d.bitrate>m.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{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=RM(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,MM(["init"])).pipe(kM(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 ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:an.DOM,thrown:t}))||(this.videoState.setState("paused"),T(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"),T(this.params.desiredState.playbackState,"stopped",!0)}};var kS="X-Playback-Duration",Pl=async i=>{let e=await Ge(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(kS)?parseInt(e.headers.get(kS),10):void 0};import{assertNever as QM,combine as GM,debounce as WM,ErrorCategory as un,filter as YM,filterChanged as zM,isNonNullable as LS,isNullable as ln,map as RS,merge as KM,observableFrom as XM,Subscription as JM,ValueSubject as Al,VideoQuality as ZM}from"@vkontakte/videoplayer-shared";var wl=D(Lo(),1);import{videoSizeToQuality as VM,getExponentialDelay as BM}from"@vkontakte/videoplayer-shared";var OM=i=>{let e=null;if(i.QUALITY&&(e=wt(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=VM({width:t,height:r})}return e??null},_M=(i,e)=>{let t=i.split(`
|
|
125
|
+
`),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,wl.default)(o[1].split(",").map(g=>g.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,c=OM(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 m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,v]=l.RESOLUTION.split("x").map(k=>parseInt(k,10));g&&v&&(f={width:g,height:v})}let b=new URL(t[++s],e).toString();c&&r.push({id:d,quality:c,url:b,bandwidth:p,size:f,fps:m})}if(u){let l=(0,wl.default)(u[1].split(",").map(m=>{let f=m.indexOf("=");return[m.substring(0,f),m.substring(f+1)]}).map(([m,f])=>[m,f.replace(/^"|"$/g,"")])),d=l.URI?.replace(/playlist$/,"subtitles.vtt"),c=l.LANGUAGE,p=l.NAME;d&&c&&a.push({type:"internal",id:c,label:p,language:c,url:d,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},NM=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),kl=0,wS=async(i,e=i,t,r)=>{let s=await(await Ge(i,r)).text();kl+=1;try{let{qualityManifests:n,textTracks:o}=_M(s,e);return{qualityManifests:n,textTracks:o}}catch{if(kl<=t.manifestRetryMaxCount)return await NM(BM(kl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),wS(i,e,t)}return{qualityManifests:[],textTracks:[]}},nn=wS;import{isNonNullable as FM,Subscription as qM,throttle as UM,ValueSubject as AS,Subject as HM,ErrorCategory as jM}from"@vkontakte/videoplayer-shared";var on=class{constructor(e,t,r,a,s){this.subscription=new qM;this.abortControllers={destroy:new se,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new AS(null);this.getCurrentTime$=new AS(null);this.error$=new HM;this.params={fetchManifestData:r,sourceUrl:a,downloadThreshold:s},this.subscription.add(e.pipe(UM(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}async prepare(e){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=await this.fetchManifestData();await this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}}async processTextTracks(e,t){try{let r=await this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}}async parseTextTracks(e,t){for(let r of e){let a=new URL(r.url,t).toString(),n=await(await Ge(a,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,a);return{textTrack:r,playlist:o}}}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},a=e.split(`
|
|
126
|
+
`),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(),d=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+d},url:l}),s=s+d,!r.segmentStartTime){let c=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-c}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.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);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(FM(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:a}=t[t.length-1].time;if(e<r||e>a)return;a-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([{...this.currentTextTrackData.textTrack,url:n.url,isAuto:!0}]);break}}}async fetchNextManifestData(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new se;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:jM.WTF,thrown:t,message:e})}};var wa=class{constructor(e){this.subscription=new JM;this.videoState=new $("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Al([]);this.liveOffset=new dt;this.manifestStartTime$=new Al(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"),T(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d),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&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?T(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),T(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"&&T(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 d=this.liveOffset.getTotalOffset();d>=this.maxSeekBackTime$.getValue()&&(d=0,this.liveOffset.resetTo(d)),this.liveOffset.resume(),this.params.output.position$.next(-d/1e3),this.prepare()}else a?.to==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return QM(t)}};this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ZM.INVARIANT,url:this.params.source.url};let t=(r,a)=>nn(r,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 on(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Ce(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:un.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.liveTextManager?.processTextTracks(a,this.params.source.url),this.manifests$.next([this.masterManifest,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:un.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),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 Al(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:un.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ge(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(be(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,r)),s(Be(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"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(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.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(zM(),RS(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&LS(l.to)){let c=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(m=>m.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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(GM({startTime:this.manifestStartTime$.pipe(YM(LS)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(RS(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r));let n=KM(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,XM(["init"])).pipe(WM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager?.destroy(),this.liveTextManager?.destroy(),this.params.output.element$.next(void 0),fe(this.video)}prepare(){let e=this.selectManifest();if(ln(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,d]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(l||""));d&&l&&a.searchParams.set(d,c)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ae(a.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Pl(n).then(o=>{if(!ln(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(ln(u)||!isFinite(u))&&Ge(n).then(l=>l.text()).then(l=>{let d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(d){let c=new URL(d,n).toString();Pl(c).then(p=>{ln(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:un.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()}generateLiveUrl(){let e=ae(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 eD,debounce as tD,ErrorCategory as Ll,fromEvent as Rl,isNonNullable as rD,isNullable as iD,map as $S,merge as MS,observableFrom as DS,Subscription as aD,ValueSubject as sD,VideoQuality as nD,clientChecker as oD}from"@vkontakte/videoplayer-shared";var Aa=class{constructor(e){this.subscription=new aD;this.videoState=new $("stopped");this.manifests$=new sD([]);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"),T(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 d=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(d);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?T(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),T(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"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return eD(t)}};this.textTracksManager=new Ce(e.source.url),this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:nD.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),nn(ae(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:Ll.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||!a.from)&&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:Ll.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ge(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($S(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(be(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(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(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&rD(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===m);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Z(f.url)))}let c=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(c!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(c),m.playbackRate=c)}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.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($S(o=>o.map(({id:u,quality:l,size:d,bandwidth:c,fps:p})=>({id:u,quality:l,size:d,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,r)),!oD.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(MS(Rl(o,"addtrack"),Rl(o,"removetrack"),Rl(o,"change"),DS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=MS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,DS(["init"])).pipe(tD(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),fe(this.video)}prepare(){let e=this.selectManifest();if(iD(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(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ll.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var BS=D(Pr(),1),$l=D(Br(),1),OS=D(Zt(),1);import{assertNever as uD,assertNonNullable as CS,debounce as lD,ErrorCategory as VS,isHigherOrEqual as cD,isLowerOrEqual as dD,isNonNullable as pD,merge as hD,observableFrom as mD,Subscription as fD,map as bD}from"@vkontakte/videoplayer-shared";var La=class{constructor(e){this.subscription=new fD;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Ce;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"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0}),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"?T(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),T(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"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return uD(e)}};this.params=e,this.video=me(e.container,e.tuning),this.params.output.element$.next(this.video),(0,BS.default)(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,$l.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:VS.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ge(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(bD(o=>o.to)),this.params.output.playbackState$),this.subscription.add(tt(this.video,t.isLooped,r)),this.subscription.add(be(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(De(this.video,t.playbackRate,a.playbackRateState$,r)),s(Be(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),T(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&&pD(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 d=this.params.output.element$.getValue();d&&(this.params.desiredState.playbackRate.setState(u),d.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=hD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,mD(["init"])).pipe(lD(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),fe(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;CS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];CS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ha(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Z(t))}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:VS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){this.test(e)}test(e){this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},r=()=>{let d=Lt(n,{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(d)},a=this.params.output.currentVideoTrack$.getValue()?.quality,s=!!(e.max||e.min),n=(0,$l.default)(this.trackUrls).map(d=>d.track);if(!a||!s||ws({limits:e,lowestAvailableQuality:(0,OS.default)(n,-1)?.quality,highestAvailableQuality:n[0].quality})){r();return}let o=e.max?dD(a,e.max):!0,u=e.min?cD(a,e.min):!0;if(o&&u)return;let l=n.find(d=>Ib({limits:e,track:d}));if(l){t(l);return}r()}};import{assertNever as NS,debounce as yD,merge as FS,observableFrom as TD,Subscription as ID,map as qS,ValueSubject as ED,ErrorCategory as Dl,VideoQuality as xD}from"@vkontakte/videoplayer-shared";import{ErrorCategory as gD}from"@vkontakte/videoplayer-shared";var _S=["stun:videostun.mycdn.me:80"],vD=1e3,SD=3,Ml=()=>null,cn=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=Ml;this.externalStopCallback=Ml;this.externalErrorCallback=Ml;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:_S}]};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:gD.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),vD)}normalizeOptions(e={}){let t={stunServerList:_S,maxRetryNumber:SD,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ra=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new ED(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"),T(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"),T(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"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return NS(e)}};this.subscription=new ID,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=me(e.container,e.tuning),this.liveStreamClient=new cn(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),fe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Dl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};FS(this.videoState.stateChangeStarted$.pipe(qS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(qS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ge(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(Be(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(be(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 NS(n.to)}},r)).add(FS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,TD(["init"])).pipe(yD(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:xD.INVARIANT}),this.video.srcObject=e,T(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:Dl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ve(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Dl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var $a=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 Bt,ErrorCategory as dn,filter as WS,isNonNullable as YS,isNullable as MD,map as DD,merge as CD,once as VD,Subject as Ie,Subscription as zS,ValueSubject as M,flattenObject as KS}from"@vkontakte/videoplayer-shared";import{Observable as PD,map as US,Subscription as kD,Subject as wD}from"@vkontakte/videoplayer-shared";var HS=i=>new PD(e=>{let t=new kD,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(US(({from:l,to:d})=>`${l}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(US(({type:l})=>l!==void 0)),n=new wD,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 AD,Subscription as LD,combine as RD,filter as QS,once as GS}from"@vkontakte/videoplayer-shared";function jS(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as $D}from"@vkontakte/videoplayer-shared";var zr=class i{constructor(e,t,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.destroyController=new se;this.subscriptions=new LD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(QS(s=>!!s.type),GS()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){$D.isSafari&&e!=="MPEG"||this.subscriptions.add(RD({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(QS(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),GS()).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=jS();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:AD.VIDEO_PIPELINE,message:e?.message??`${i.errorId} exception`,thrown:e})}};var BD={chunkDuration:5e3,maxParallelRequests:5},Da=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new Ie;this.noAvailableProvidersError$=new Ie;this.volumeMultiplierError$=new Ie;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 Ie,warning$:new Ie,willSeekEvent$:new Ie,soundProhibitedEvent$:new Ie,seekedEvent$:new Ie,loopedEvent$:new Ie,endedEvent$:new Ie,firstBytesEvent$:new Ie,loadedMetadataEvent$:new Ie,firstFrameEvent$:new Ie,canplay$:new Ie,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(""),getCurrentTime$:new M(null)};this.subscription=new zS;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=yg([...Ig(this.params.tuning),...Tg(this.params.tuning)],this.params.tuning).filter(l=>YS(e.sources[l])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(l=>!(0,Cl.default)(a,l)),...t.filter(l=>(0,Cl.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",KS(s)),this.screenFormatsIterator=new $a(s);let n=[...Fu(!0),...Fu(!1)];this.chromecastFormatsIterator=new $a(n.filter(l=>YS(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&zr.isSupported()&&(this.volumeMultiplierManager=new zr(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(MD(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:dn.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 Ma(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 Bt(o),new Ea({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Bt(o),new xa({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Bt(o),qr||!this.params.tuning.useHlsJs?new Aa({...n,source:o}):new ka({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Bt(o),new wa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Bt(o),new La({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Yb({...n,source:o,config:{...BD,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Bt(o),new Ra({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 Ma(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 Bt(o),new Ii({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 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 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,JS.default)((0,XS.default)(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new zS,t=!1,r=0;return e.add(CD(this.providerOutput.error$.pipe(WS(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),HS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(DD(a=>({id:`ProviderHangup:${a}`,category:dn.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(WS(({to:s})=>s==="playing"),VD()).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===dn.NETWORK,u=a.category===dn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit&&!u,c=l&&!u&&(o&&t||!d);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:c,canReinitProvider:d},d?(r++,this.reinitProvider()):c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",KS(n))})),e}};import{fromEvent as pn,once as OD,combine as _D,Subscription as ZS,ValueSubject as Vl,map as ND,filter as FD,isNonNullable as hn,now as Ae,safeStorage as Bl}from"@vkontakte/videoplayer-shared";var qD=5e3,ey="one_video_throughput",ty="one_video_rtt",Ca=window.navigator.connection,ry=()=>{let i=Ca?.downlink;if(hn(i)&&i!==10)return i*1e3},iy=()=>{let i=Ca?.rtt;if(hn(i)&&i!==3e3)return i},ay=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Ol=class i{constructor(e){this.subscription=new ZS;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(ey)||(e.useBrowserEstimation?ry():void 0)||qD,r=i.load(ty)??(e.useBrowserEstimation?iy():void 0)??0;if(this.throughput$=new Vl(t),this.rtt$=new Vl(r),this.rttAdjustedThroughput$=new Vl(ay(t,r,e.rttPenaltyRequestSize)),this.throughput=sr.getSmoothedValue(t,-1,e),this.rtt=sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=ry();n&&this.throughput.next(n);let o=iy();hn(o)&&this.rtt.next(o)};Ca&&"onchange"in Ca&&this.subscription.add(pn(Ca,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Bl.set(ey,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Bl.set(ty,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(_D({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(ND(({throughput:a,rtt:s})=>ay(a,s,e.rttPenaltyRequestSize)),FD(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=Ae(),a=new ZS;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(pn(e,"progress").pipe(OD()).subscribe(s=>{t=s.loaded,r=Ae()}));break;case 1:case 0:a.add(pn(e,"loadstart").subscribe(()=>{t=0,r=Ae()}));break}a.add(pn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ae(),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=Ae(),n=0,o=Ae(),u=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},l=async({done:d,value:c})=>{if(d)!t&&this.addRawSpeed(a,Ae()-s,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=Ae();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=c.byteLength,s=Ae()}else n+=c.byteLength;o=Ae()}else a+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ae()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ae()-o,this.concurrentDownloads.size),n=0,o=Ae());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=Bl.get(e);if(hn(t))return parseInt(t,10)??void 0}},sy=Ol;import{fillWithDefault as UD,VideoQuality as mn}from"@vkontakte/videoplayer-shared";var ny={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:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:mn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:mn.Q_720P,trafficSavingLimit:mn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:mn.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:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},oy=i=>({...UD(i,ny),configName:[...i.configName??[],...ny.configName]});import{assertNonNullable as fn,combine as bt,ErrorCategory as bn,filter as pe,filterChanged as _,fromEvent as Nl,isNonNullable as zD,isNullable as KD,Logger as XD,map as O,mapTo as dy,merge as Ot,now as gn,once as at,Subject as H,Subscription as py,tap as hy,ValueSubject as E,isHigher as JD,isInvariantQuality as my,flattenObject as _t,throttle as Fl,getTraceSubscriptionMethod as fy,Tracer as ZD,InternalsExposure as e0}from"@vkontakte/videoplayer-shared";import{merge as HD,map as jD,filter as uy,isNonNullable as QD}from"@vkontakte/videoplayer-shared";var _l=({seekState:i,position$:e})=>HD(i.stateChangeEnded$.pipe(jD(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),uy(QD)),e.pipe(uy(()=>i.getState().state==="none")));import{assertNonNullable as GD}from"@vkontakte/videoplayer-shared";var ly=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return GD(e,`Wrong container or containerId {${i.container}}`),e};import{filter as WD,once as YD}from"@vkontakte/videoplayer-shared";var cy=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(WD(a=>a.length>0),YD()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var vn=class{constructor(e={configName:[]},t=ZD.createRootTracer(!1)){this.subscription=new py;this.logger=new XD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!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 E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableVideoStreams$:new E([]),currentVideoStream$:new E(void 0),availableQualities$:new E([]),availableQualitiesFps$:new E({}),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),predefinedQualityLimitType$:new E("unknown"),availableAudioStreams$:new E([]),currentAudioStream$:new E(void 0),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentPlaybackRate$:new E(1),currentBuffer$:new E({start:0,end:0}),isBuffering$:new E(!0),isStalled$:new E(!1),isEnded$:new E(!1),isLooped$:new E(!1),isLive$:new E(void 0),canChangePlaybackSpeed$:new E(void 0),atLiveEdge$:new E(void 0),atLiveDurationEdge$:new E(void 0),liveTime$:new E(void 0),liveBufferTime$:new E(void 0),liveLatency$:new E(void 0),currentFormat$:new E(void 0),availableTextTracks$:new E([]),currentTextTrack$:new E(void 0),throughputEstimation$:new E(void 0),rttEstimation$:new E(void 0),videoBitrate$:new E(void 0),hostname$:new E(void 0),httpConnectionType$:new E(void 0),httpConnectionReused$:new E(void 0),surface$:new E("none"),chromecastState$:new E("NOT_AVAILABLE"),chromecastDeviceName$:new E(void 0),intrinsicVideoSize$:new E(void 0),availableSources$:new E(void 0),is3DVideo$:new E(!1),currentVideoSegmentLength$:new E(0),currentAudioSegmentLength$:new E(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 E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:yb,getCurrentTime$:new E(null)};if(this.initLogs(),this.tuning=oy(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ya({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new sy(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new e0("CORE"),this.internalsExposure.expose({player:this})),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,(m,f)=>{let b=typeof f;return(0,by.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),d=`Player.${String(a)}`,c=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:bn.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",_t(r)),this.domContainer=ly(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new Da({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.internalsExposure?.expose({config:e,logger:this.logger,tuning:this.tuning}),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(),this.internalsExposure?.destroy()}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&&!$i()?(this.tracer.log("request play from hidden tab"),Nl(document,"visibilitychange").pipe(at()).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-.2),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){fn(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(pe(r=>r.length>0),at()).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",_t(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,a;switch(e){case"high_quality":a={min:t,max:void 0};break;case"traffic_saving":a={max:r,min:void 0};break;default:a={max:void 0,min:void 0}}return this.setAutoQualityLimits(a),this}setPlaybackRate(e){fn(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 cy(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(KD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return zD(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(Ot(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(O(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(O(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Pu({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(pe(({from:e})=>e==="stopped"),at()).subscribe(()=>{this.initedAt=gn(),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:bn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(at()).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(O(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(O(n=>n.destination),_()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(bt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(O(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>my(u)?1:my(l)?-1:JD(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(_()).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(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(_((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(_()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(_()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(_()).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(O(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(bt({hasLiveOffsetByPaused:Ot(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(O(n=>n.to),_(),O(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(bt({atLiveEdge:bt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:_l({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(O(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),_(),hy(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(O(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(bt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(O(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),_(),hy(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(O(n=>n.muted),_()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(O(n=>n.volume),_()).subscribe(this.info.volume$)).add(_l({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ot(e.providerOutput.endedEvent$.pipe(dy(!0)),e.providerOutput.seekedEvent$.pipe(dy(!1))).pipe(_()).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(O(n=>({id:n?`No${n}`:"NoProviders",category:bn.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(at(),O(n=>n??gn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(at(),O(()=>gn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(at(),O(()=>gn()-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 E(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new E(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(pe(({to:n})=>n==="playing"),at()).subscribe(()=>r.next(!1)));let a=0,s=Ot(e.providerOutput.isBuffering$,t,r).pipe(O(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),_());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(Ot(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(Ot(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(),d=this.chromecastInitializer.castState$.getValue(),c;d==="CONNECTED"?c="second_screen":u?l?n?c="pip":o?c="fullscreen":c="inline":c="invisible":c="none",this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(O(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new py;this.subscription.add(t),this.subscription.add(e.current$.pipe(_((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(pe(r=>r.length>0),at()).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=Lt(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(Ot(this.desiredState.videoTrack.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(O(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(O(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(O(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;fn(this.providerContainer),fn(e),Sb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>vb(t)),this.providerContainer.current$.subscribe(({type:t})=>Pi("provider",t)),e.duration$.subscribe(t=>Pi("duration",t)),e.availableVideoTracks$.pipe(pe(t=>!!t.length),at()).subscribe(t=>Pi("tracks",t)),this.events.fatalError$.subscribe(new le("fatalError")),this.events.managedError$.subscribe(new le("managedError")),e.position$.subscribe(new le("position")),e.currentVideoTrack$.pipe(O(t=>t?.quality)).subscribe(new le("quality")),this.info.currentBuffer$.subscribe(new le("buffer")),e.isBuffering$.subscribe(new le("isBuffering"))].forEach(t=>this.subscription.add(t)),Pi("codecs",Sg())}initTracerSubscription(){let e=fy(this.tracer.log.bind(this.tracer)),t=fy(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(_()).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(bt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(pe(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),_((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(pe(r=>r>0),_()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(pe(r=>r>0),_()).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(bt({currentBuffer:this.info.currentBuffer$.pipe(pe(r=>r.end>0),_((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe(_())}).pipe(Fl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(_()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(_()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(_()).subscribe(e("canChangePlaybackSpeed"))).add(bt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(pe(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),Fl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(_(),pe(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(_(),pe(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(_()).subscribe(e("muted"))).add(this.info.volume$.pipe(_()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(_(),pe(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(bt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(pe(({throughputEstimation:r,rtt:a})=>!!r&&!!a),Fl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(_(),pe(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:bn.DOM,message:String(a)})})};this.subscription.add(Ot(Nl(document,"visibilitychange"),Nl(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",_t({quality:t,availableTracks:_t(e),track:_t(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 ez,Observable as tz,Subject as rz,ValueSubject as iz,VideoQuality as az}from"@vkontakte/videoplayer-shared";var sz=`@vkontakte/videoplayer-core@${Hl}`;export{qa as ChromecastState,Tn as HttpConnectionType,tz as Observable,he as PlaybackState,vn as Player,Ua as PredefinedQualityLimits,sz as SDK_VERSION,rz as Subject,ez as Subscription,In as Surface,Hl as VERSION,iz as ValueSubject,yt as VideoFormat,az as VideoQuality};
|