@vkontakte/videoplayer-core 2.0.123-dev.c995f51b.0 → 2.0.123-dev.d53feee8.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 +29 -27
- package/es2015.esm.js +29 -27
- package/es2018.cjs.js +27 -25
- package/es2018.esm.js +25 -23
- package/esnext.cjs.js +27 -25
- package/esnext.esm.js +27 -25
- package/evergreen.esm.js +23 -21
- package/package.json +2 -2
- package/types/player/Player.d.ts +1 -2
- package/types/player/types.d.ts +2 -4
- package/types/providers/ChromecastProvider/ChromecastInitializer/index.d.ts +8 -7
- package/types/providers/DashProvider/lib/buffer.d.ts +3 -1
- package/types/providers/DashProvider/lib/fetcher.d.ts +1 -4
- package/types/providers/DashProvider/lib/player.d.ts +2 -4
- package/types/providers/DashProvider/lib/sourceBufferTaskQueue.d.ts +1 -0
- package/types/providers/HlsLiveProvider/LiveTextManager.d.ts +39 -0
- package/types/providers/HlsLiveProvider/index.d.ts +2 -0
- package/types/providers/HlsProvider/manifestDataExtractor.d.ts +1 -1
- package/types/providers/types.d.ts +1 -2
- package/types/providers/utils/HTMLVideoElement/TextTrackManager.d.ts +2 -0
- package/types/providers/utils/StallsManager.d.ts +1 -0
- package/types/utils/buffer/isSourceBufferValid.d.ts +3 -0
- package/types/utils/tuningConfig.d.ts +8 -2
package/esnext.esm.js
CHANGED
|
@@ -1,51 +1,52 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.123-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.123-dev.d53feee8.0
|
|
3
|
+
* Tue, 14 Jan 2025 08:45:35 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-123/doc/
|
|
5
5
|
*/
|
|
6
|
-
var ny=Object.create;var $l=Object.defineProperty;var oy=Object.getOwnPropertyDescriptor;var uy=Object.getOwnPropertyNames;var ly=Object.getPrototypeOf,cy=Object.prototype.hasOwnProperty;var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var dy=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of uy(e))!cy.call(i,a)&&a!==t&&$l(i,a,{get:()=>e[a],enumerable:!(r=oy(e,a))||r.enumerable});return i};var C=(i,e,t)=>(t=i!=null?ny(ly(i)):{},dy(e||!i||!i.__esModule?$l(t,"default",{value:i,enumerable:!0}):t,i));var Q=m((fn,Ml)=>{"use strict";var Kr=function(i){return i&&i.Math===Math&&i};Ml.exports=Kr(typeof globalThis=="object"&&globalThis)||Kr(typeof window=="object"&&window)||Kr(typeof self=="object"&&self)||Kr(typeof global=="object"&&global)||Kr(typeof fn=="object"&&fn)||function(){return this}()||Function("return this")()});var ie=m((D0,Cl)=>{"use strict";Cl.exports=function(i){try{return!!i()}catch{return!0}}});var Jr=m((V0,Dl)=>{"use strict";var py=ie();Dl.exports=!py(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var bn=m((O0,_l)=>{"use strict";var hy=Jr(),Bl=Function.prototype,Vl=Bl.apply,Ol=Bl.call;_l.exports=typeof Reflect=="object"&&Reflect.apply||(hy?Ol.bind(Vl):function(){return Ol.apply(Vl,arguments)})});var J=m((B0,ql)=>{"use strict";var Nl=Jr(),Fl=Function.prototype,gn=Fl.call,my=Nl&&Fl.bind.bind(gn,gn);ql.exports=Nl?my:function(i){return function(){return gn.apply(i,arguments)}}});var Nt=m((_0,Hl)=>{"use strict";var Ul=J(),fy=Ul({}.toString),by=Ul("".slice);Hl.exports=function(i){return by(fy(i),8,-1)}});var vn=m((N0,jl)=>{"use strict";var gy=Nt(),vy=J();jl.exports=function(i){if(gy(i)==="Function")return vy(i)}});var G=m((F0,Gl)=>{"use strict";var Sn=typeof document=="object"&&document.all;Gl.exports=typeof Sn>"u"&&Sn!==void 0?function(i){return typeof i=="function"||i===Sn}:function(i){return typeof i=="function"}});var Ie=m((q0,Ql)=>{"use strict";var Sy=ie();Ql.exports=!Sy(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ee=m((U0,Wl)=>{"use strict";var yy=Jr(),Ba=Function.prototype.call;Wl.exports=yy?Ba.bind(Ba):function(){return Ba.apply(Ba,arguments)}});var yn=m(Kl=>{"use strict";var Yl={}.propertyIsEnumerable,zl=Object.getOwnPropertyDescriptor,Ty=zl&&!Yl.call({1:2},1);Kl.f=Ty?function(e){var t=zl(this,e);return!!t&&t.enumerable}:Yl});var Xr=m((j0,Jl)=>{"use strict";Jl.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var Zl=m((G0,Xl)=>{"use strict";var Iy=J(),Ey=ie(),xy=Nt(),Tn=Object,Py=Iy("".split);Xl.exports=Ey(function(){return!Tn("z").propertyIsEnumerable(0)})?function(i){return xy(i)==="String"?Py(i,""):Tn(i)}:Tn});var hr=m((Q0,ec)=>{"use strict";ec.exports=function(i){return i==null}});var gt=m((W0,tc)=>{"use strict";var ky=hr(),Ay=TypeError;tc.exports=function(i){if(ky(i))throw new Ay("Can't call method on "+i);return i}});var Ft=m((Y0,rc)=>{"use strict";var wy=Zl(),Ry=gt();rc.exports=function(i){return wy(Ry(i))}});var xe=m((z0,ic)=>{"use strict";var $y=G();ic.exports=function(i){return typeof i=="object"?i!==null:$y(i)}});var mr=m((K0,ac)=>{"use strict";ac.exports={}});var at=m((J0,nc)=>{"use strict";var In=mr(),En=Q(),Ly=G(),sc=function(i){return Ly(i)?i:void 0};nc.exports=function(i,e){return arguments.length<2?sc(In[i])||sc(En[i]):In[i]&&In[i][e]||En[i]&&En[i][e]}});var Zr=m((X0,oc)=>{"use strict";var My=J();oc.exports=My({}.isPrototypeOf)});var qt=m((Z0,cc)=>{"use strict";var Cy=Q(),uc=Cy.navigator,lc=uc&&uc.userAgent;cc.exports=lc?String(lc):""});var Pn=m((eC,bc)=>{"use strict";var fc=Q(),xn=qt(),dc=fc.process,pc=fc.Deno,hc=dc&&dc.versions||pc&&pc.version,mc=hc&&hc.v8,_e,_a;mc&&(_e=mc.split("."),_a=_e[0]>0&&_e[0]<4?1:+(_e[0]+_e[1]));!_a&&xn&&(_e=xn.match(/Edge\/(\d+)/),(!_e||_e[1]>=74)&&(_e=xn.match(/Chrome\/(\d+)/),_e&&(_a=+_e[1])));bc.exports=_a});var kn=m((tC,vc)=>{"use strict";var gc=Pn(),Dy=ie(),Vy=Q(),Oy=Vy.String;vc.exports=!!Object.getOwnPropertySymbols&&!Dy(function(){var i=Symbol("symbol detection");return!Oy(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&gc&&gc<41})});var An=m((rC,Sc)=>{"use strict";var By=kn();Sc.exports=By&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var wn=m((iC,yc)=>{"use strict";var _y=at(),Ny=G(),Fy=Zr(),qy=An(),Uy=Object;yc.exports=qy?function(i){return typeof i=="symbol"}:function(i){var e=_y("Symbol");return Ny(e)&&Fy(e.prototype,Uy(i))}});var ei=m((aC,Tc)=>{"use strict";var Hy=String;Tc.exports=function(i){try{return Hy(i)}catch{return"Object"}}});var Ye=m((sC,Ic)=>{"use strict";var jy=G(),Gy=ei(),Qy=TypeError;Ic.exports=function(i){if(jy(i))return i;throw new Qy(Gy(i)+" is not a function")}});var ti=m((nC,Ec)=>{"use strict";var Wy=Ye(),Yy=hr();Ec.exports=function(i,e){var t=i[e];return Yy(t)?void 0:Wy(t)}});var Pc=m((oC,xc)=>{"use strict";var Rn=Ee(),$n=G(),Ln=xe(),zy=TypeError;xc.exports=function(i,e){var t,r;if(e==="string"&&$n(t=i.toString)&&!Ln(r=Rn(t,i))||$n(t=i.valueOf)&&!Ln(r=Rn(t,i))||e!=="string"&&$n(t=i.toString)&&!Ln(r=Rn(t,i)))return r;throw new zy("Can't convert object to primitive value")}});var Ne=m((uC,kc)=>{"use strict";kc.exports=!0});var Rc=m((lC,wc)=>{"use strict";var Ac=Q(),Ky=Object.defineProperty;wc.exports=function(i,e){try{Ky(Ac,i,{value:e,configurable:!0,writable:!0})}catch{Ac[i]=e}return e}});var ri=m((cC,Mc)=>{"use strict";var Jy=Ne(),Xy=Q(),Zy=Rc(),$c="__core-js_shared__",Lc=Mc.exports=Xy[$c]||Zy($c,{});(Lc.versions||(Lc.versions=[])).push({version:"3.38.0",mode:Jy?"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 Mn=m((dC,Dc)=>{"use strict";var Cc=ri();Dc.exports=function(i,e){return Cc[i]||(Cc[i]=e||{})}});var fr=m((pC,Vc)=>{"use strict";var eT=gt(),tT=Object;Vc.exports=function(i){return tT(eT(i))}});var Fe=m((hC,Oc)=>{"use strict";var rT=J(),iT=fr(),aT=rT({}.hasOwnProperty);Oc.exports=Object.hasOwn||function(e,t){return aT(iT(e),t)}});var Cn=m((mC,Bc)=>{"use strict";var sT=J(),nT=0,oT=Math.random(),uT=sT(1 .toString);Bc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+uT(++nT+oT,36)}});var ae=m((fC,Nc)=>{"use strict";var lT=Q(),cT=Mn(),_c=Fe(),dT=Cn(),pT=kn(),hT=An(),br=lT.Symbol,Dn=cT("wks"),mT=hT?br.for||br:br&&br.withoutSetter||dT;Nc.exports=function(i){return _c(Dn,i)||(Dn[i]=pT&&_c(br,i)?br[i]:mT("Symbol."+i)),Dn[i]}});var Hc=m((bC,Uc)=>{"use strict";var fT=Ee(),Fc=xe(),qc=wn(),bT=ti(),gT=Pc(),vT=ae(),ST=TypeError,yT=vT("toPrimitive");Uc.exports=function(i,e){if(!Fc(i)||qc(i))return i;var t=bT(i,yT),r;if(t){if(e===void 0&&(e="default"),r=fT(t,i,e),!Fc(r)||qc(r))return r;throw new ST("Can't convert object to primitive value")}return e===void 0&&(e="number"),gT(i,e)}});var Vn=m((gC,jc)=>{"use strict";var TT=Hc(),IT=wn();jc.exports=function(i){var e=TT(i,"string");return IT(e)?e:e+""}});var Na=m((vC,Qc)=>{"use strict";var ET=Q(),Gc=xe(),On=ET.document,xT=Gc(On)&&Gc(On.createElement);Qc.exports=function(i){return xT?On.createElement(i):{}}});var Bn=m((SC,Wc)=>{"use strict";var PT=Ie(),kT=ie(),AT=Na();Wc.exports=!PT&&!kT(function(){return Object.defineProperty(AT("div"),"a",{get:function(){return 7}}).a!==7})});var Kc=m(zc=>{"use strict";var wT=Ie(),RT=Ee(),$T=yn(),LT=Xr(),MT=Ft(),CT=Vn(),DT=Fe(),VT=Bn(),Yc=Object.getOwnPropertyDescriptor;zc.f=wT?Yc:function(e,t){if(e=MT(e),t=CT(t),VT)try{return Yc(e,t)}catch{}if(DT(e,t))return LT(!RT($T.f,e,t),e[t])}});var _n=m((TC,Jc)=>{"use strict";var OT=ie(),BT=G(),_T=/#|\.prototype\./,ii=function(i,e){var t=FT[NT(i)];return t===UT?!0:t===qT?!1:BT(e)?OT(e):!!e},NT=ii.normalize=function(i){return String(i).replace(_T,".").toLowerCase()},FT=ii.data={},qT=ii.NATIVE="N",UT=ii.POLYFILL="P";Jc.exports=ii});var gr=m((IC,Zc)=>{"use strict";var Xc=vn(),HT=Ye(),jT=Jr(),GT=Xc(Xc.bind);Zc.exports=function(i,e){return HT(i),e===void 0?i:jT?GT(i,e):function(){return i.apply(e,arguments)}}});var Nn=m((EC,ed)=>{"use strict";var QT=Ie(),WT=ie();ed.exports=QT&&WT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var ze=m((xC,td)=>{"use strict";var YT=xe(),zT=String,KT=TypeError;td.exports=function(i){if(YT(i))return i;throw new KT(zT(i)+" is not an object")}});var Ut=m(id=>{"use strict";var JT=Ie(),XT=Bn(),ZT=Nn(),Fa=ze(),rd=Vn(),eI=TypeError,Fn=Object.defineProperty,tI=Object.getOwnPropertyDescriptor,qn="enumerable",Un="configurable",Hn="writable";id.f=JT?ZT?function(e,t,r){if(Fa(e),t=rd(t),Fa(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Hn in r&&!r[Hn]){var a=tI(e,t);a&&a[Hn]&&(e[t]=r.value,r={configurable:Un in r?r[Un]:a[Un],enumerable:qn in r?r[qn]:a[qn],writable:!1})}return Fn(e,t,r)}:Fn:function(e,t,r){if(Fa(e),t=rd(t),Fa(r),XT)try{return Fn(e,t,r)}catch{}if("get"in r||"set"in r)throw new eI("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var vr=m((kC,ad)=>{"use strict";var rI=Ie(),iI=Ut(),aI=Xr();ad.exports=rI?function(i,e,t){return iI.f(i,e,aI(1,t))}:function(i,e,t){return i[e]=t,i}});var z=m((AC,nd)=>{"use strict";var ai=Q(),sI=bn(),nI=vn(),oI=G(),uI=Kc().f,lI=_n(),Sr=mr(),cI=gr(),yr=vr(),sd=Fe();ri();var dI=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 sI(i,this,arguments)};return e.prototype=i.prototype,e};nd.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?ai:a?ai[t]:ai[t]&&ai[t].prototype,o=r?Sr:Sr[t]||yr(Sr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,v;for(p in e)l=lI(r?p:t+(a?".":"#")+p,i.forced),c=!l&&n&&sd(n,p),f=o[p],c&&(i.dontCallGetSet?(v=uI(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(i.bind&&c?g=cI(h,ai):i.wrap&&c?g=dI(h):s&&oI(h)?g=nI(h):g=h,(i.sham||h&&h.sham||f&&f.sham)&&yr(g,"sham",!0),yr(o,p,g),s&&(d=t+"Prototype",sd(Sr,d)||yr(Sr,d,{}),yr(Sr[d],p,h),i.real&&u&&(l||!u[p])&&yr(u,p,h)))}});var ud=m((wC,od)=>{"use strict";var pI=Math.ceil,hI=Math.floor;od.exports=Math.trunc||function(e){var t=+e;return(t>0?hI:pI)(t)}});var si=m((RC,ld)=>{"use strict";var mI=ud();ld.exports=function(i){var e=+i;return e!==e||e===0?0:mI(e)}});var dd=m(($C,cd)=>{"use strict";var fI=si(),bI=Math.max,gI=Math.min;cd.exports=function(i,e){var t=fI(i);return t<0?bI(t+e,0):gI(t,e)}});var jn=m((LC,pd)=>{"use strict";var vI=si(),SI=Math.min;pd.exports=function(i){var e=vI(i);return e>0?SI(e,9007199254740991):0}});var Tr=m((MC,hd)=>{"use strict";var yI=jn();hd.exports=function(i){return yI(i.length)}});var Gn=m((CC,fd)=>{"use strict";var TI=Ft(),II=dd(),EI=Tr(),md=function(i){return function(e,t,r){var a=TI(e),s=EI(a);if(s===0)return!i&&-1;var n=II(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}};fd.exports={includes:md(!0),indexOf:md(!1)}});var ni=m((DC,bd)=>{"use strict";bd.exports=function(){}});var gd=m(()=>{"use strict";var xI=z(),PI=Gn().includes,kI=ie(),AI=ni(),wI=kI(function(){return!Array(1).includes()});xI({target:"Array",proto:!0,forced:wI},{includes:function(e){return PI(this,e,arguments.length>1?arguments[1]:void 0)}});AI("includes")});var vt=m((BC,vd)=>{"use strict";var RI=at();vd.exports=RI});var yd=m((_C,Sd)=>{"use strict";gd();var $I=vt();Sd.exports=$I("Array","includes")});var Id=m((NC,Td)=>{"use strict";var LI=yd();Td.exports=LI});var Ke=m((FC,Ed)=>{"use strict";var MI=Id();Ed.exports=MI});var Ha=m((XC,Ld)=>{"use strict";var FI=Mn(),qI=Cn(),$d=FI("keys");Ld.exports=function(i){return $d[i]||($d[i]=qI(i))}});var Cd=m((ZC,Md)=>{"use strict";var UI=ie();Md.exports=!UI(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var ja=m((eD,Vd)=>{"use strict";var HI=Fe(),jI=G(),GI=fr(),QI=Ha(),WI=Cd(),Dd=QI("IE_PROTO"),Yn=Object,YI=Yn.prototype;Vd.exports=WI?Yn.getPrototypeOf:function(i){var e=GI(i);if(HI(e,Dd))return e[Dd];var t=e.constructor;return jI(t)&&e instanceof t?t.prototype:e instanceof Yn?YI:null}});var Ga=m((tD,Od)=>{"use strict";Od.exports={}});var Nd=m((rD,_d)=>{"use strict";var zI=J(),zn=Fe(),KI=Ft(),JI=Gn().indexOf,XI=Ga(),Bd=zI([].push);_d.exports=function(i,e){var t=KI(i),r=0,a=[],s;for(s in t)!zn(XI,s)&&zn(t,s)&&Bd(a,s);for(;e.length>r;)zn(t,s=e[r++])&&(~JI(a,s)||Bd(a,s));return a}});var Kn=m((iD,Fd)=>{"use strict";Fd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Jn=m((aD,qd)=>{"use strict";var ZI=Nd(),eE=Kn();qd.exports=Object.keys||function(e){return ZI(e,eE)}});var Xn=m((sD,Qd)=>{"use strict";var Hd=Ie(),tE=ie(),jd=J(),rE=ja(),iE=Jn(),aE=Ft(),sE=yn().f,Gd=jd(sE),nE=jd([].push),oE=Hd&&tE(function(){var i=Object.create(null);return i[2]=2,!Gd(i,2)}),Ud=function(i){return function(e){for(var t=aE(e),r=iE(t),a=oE&&rE(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Hd||(a?u in t:Gd(t,u)))&&nE(o,i?[u,t[u]]:t[u]);return o}};Qd.exports={entries:Ud(!0),values:Ud(!1)}});var Wd=m(()=>{"use strict";var uE=z(),lE=Xn().entries;uE({target:"Object",stat:!0},{entries:function(e){return lE(e)}})});var zd=m((uD,Yd)=>{"use strict";Wd();var cE=mr();Yd.exports=cE.Object.entries});var Jd=m((lD,Kd)=>{"use strict";var dE=zd();Kd.exports=dE});var Ir=m((cD,Xd)=>{"use strict";var pE=Jd();Xd.exports=pE});var Ht=m((dD,Zd)=>{"use strict";Zd.exports={}});var rp=m((pD,tp)=>{"use strict";var hE=Q(),mE=G(),ep=hE.WeakMap;tp.exports=mE(ep)&&/native code/.test(String(ep))});var ro=m((hD,sp)=>{"use strict";var fE=rp(),ap=Q(),bE=xe(),gE=vr(),Zn=Fe(),eo=ri(),vE=Ha(),SE=Ga(),ip="Object already initialized",to=ap.TypeError,yE=ap.WeakMap,Qa,oi,Wa,TE=function(i){return Wa(i)?oi(i):Qa(i,{})},IE=function(i){return function(e){var t;if(!bE(e)||(t=oi(e)).type!==i)throw new to("Incompatible receiver, "+i+" required");return t}};fE||eo.state?(qe=eo.state||(eo.state=new yE),qe.get=qe.get,qe.has=qe.has,qe.set=qe.set,Qa=function(i,e){if(qe.has(i))throw new to(ip);return e.facade=i,qe.set(i,e),e},oi=function(i){return qe.get(i)||{}},Wa=function(i){return qe.has(i)}):(jt=vE("state"),SE[jt]=!0,Qa=function(i,e){if(Zn(i,jt))throw new to(ip);return e.facade=i,gE(i,jt,e),e},oi=function(i){return Zn(i,jt)?i[jt]:{}},Wa=function(i){return Zn(i,jt)});var qe,jt;sp.exports={set:Qa,get:oi,has:Wa,enforce:TE,getterFor:IE}});var so=m((mD,op)=>{"use strict";var io=Ie(),EE=Fe(),np=Function.prototype,xE=io&&Object.getOwnPropertyDescriptor,ao=EE(np,"name"),PE=ao&&function(){}.name==="something",kE=ao&&(!io||io&&xE(np,"name").configurable);op.exports={EXISTS:ao,PROPER:PE,CONFIGURABLE:kE}});var lp=m(up=>{"use strict";var AE=Ie(),wE=Nn(),RE=Ut(),$E=ze(),LE=Ft(),ME=Jn();up.f=AE&&!wE?Object.defineProperties:function(e,t){$E(e);for(var r=LE(t),a=ME(t),s=a.length,n=0,o;s>n;)RE.f(e,o=a[n++],r[o]);return e}});var no=m((bD,cp)=>{"use strict";var CE=at();cp.exports=CE("document","documentElement")});var co=m((gD,gp)=>{"use strict";var DE=ze(),VE=lp(),dp=Kn(),OE=Ga(),BE=no(),_E=Na(),NE=Ha(),pp=">",hp="<",uo="prototype",lo="script",fp=NE("IE_PROTO"),oo=function(){},bp=function(i){return hp+lo+pp+i+hp+"/"+lo+pp},mp=function(i){i.write(bp("")),i.close();var e=i.parentWindow.Object;return i=null,e},FE=function(){var i=_E("iframe"),e="java"+lo+":",t;return i.style.display="none",BE.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(bp("document.F=Object")),t.close(),t.F},Ya,za=function(){try{Ya=new ActiveXObject("htmlfile")}catch{}za=typeof document<"u"?document.domain&&Ya?mp(Ya):FE():mp(Ya);for(var i=dp.length;i--;)delete za[uo][dp[i]];return za()};OE[fp]=!0;gp.exports=Object.create||function(e,t){var r;return e!==null?(oo[uo]=DE(e),r=new oo,oo[uo]=null,r[fp]=e):r=za(),t===void 0?r:VE.f(r,t)}});var Er=m((vD,vp)=>{"use strict";var qE=vr();vp.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:qE(i,e,t),i}});var fo=m((SD,Tp)=>{"use strict";var UE=ie(),HE=G(),jE=xe(),GE=co(),Sp=ja(),QE=Er(),WE=ae(),YE=Ne(),mo=WE("iterator"),yp=!1,st,po,ho;[].keys&&(ho=[].keys(),"next"in ho?(po=Sp(Sp(ho)),po!==Object.prototype&&(st=po)):yp=!0);var zE=!jE(st)||UE(function(){var i={};return st[mo].call(i)!==i});zE?st={}:YE&&(st=GE(st));HE(st[mo])||QE(st,mo,function(){return this});Tp.exports={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:yp}});var Ka=m((yD,Ep)=>{"use strict";var KE=ae(),JE=KE("toStringTag"),Ip={};Ip[JE]="z";Ep.exports=String(Ip)==="[object z]"});var ui=m((TD,xp)=>{"use strict";var XE=Ka(),ZE=G(),Ja=Nt(),ex=ae(),tx=ex("toStringTag"),rx=Object,ix=Ja(function(){return arguments}())==="Arguments",ax=function(i,e){try{return i[e]}catch{}};xp.exports=XE?Ja:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=ax(e=rx(i),tx))=="string"?t:ix?Ja(e):(r=Ja(e))==="Object"&&ZE(e.callee)?"Arguments":r}});var kp=m((ID,Pp)=>{"use strict";var sx=Ka(),nx=ui();Pp.exports=sx?{}.toString:function(){return"[object "+nx(this)+"]"}});var li=m((ED,wp)=>{"use strict";var ox=Ka(),ux=Ut().f,lx=vr(),cx=Fe(),dx=kp(),px=ae(),Ap=px("toStringTag");wp.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(cx(a,Ap)||ux(a,Ap,{configurable:!0,value:e}),r&&!ox&&lx(a,"toString",dx))}});var $p=m((xD,Rp)=>{"use strict";var hx=fo().IteratorPrototype,mx=co(),fx=Xr(),bx=li(),gx=Ht(),vx=function(){return this};Rp.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=mx(hx,{next:fx(+!r,t)}),bx(i,a,!1,!0),gx[a]=vx,i}});var Mp=m((PD,Lp)=>{"use strict";var Sx=J(),yx=Ye();Lp.exports=function(i,e,t){try{return Sx(yx(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var Dp=m((kD,Cp)=>{"use strict";var Tx=xe();Cp.exports=function(i){return Tx(i)||i===null}});var Op=m((AD,Vp)=>{"use strict";var Ix=Dp(),Ex=String,xx=TypeError;Vp.exports=function(i){if(Ix(i))return i;throw new xx("Can't set "+Ex(i)+" as a prototype")}});var bo=m((wD,Bp)=>{"use strict";var Px=Mp(),kx=xe(),Ax=gt(),wx=Op();Bp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=Px(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return Ax(a),wx(s),kx(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Yp=m((RD,Wp)=>{"use strict";var Rx=z(),$x=Ee(),Xa=Ne(),Gp=so(),Lx=G(),Mx=$p(),_p=ja(),Np=bo(),Cx=li(),Dx=vr(),go=Er(),Vx=ae(),Fp=Ht(),Qp=fo(),Ox=Gp.PROPER,Bx=Gp.CONFIGURABLE,qp=Qp.IteratorPrototype,Za=Qp.BUGGY_SAFARI_ITERATORS,ci=Vx("iterator"),Up="keys",di="values",Hp="entries",jp=function(){return this};Wp.exports=function(i,e,t,r,a,s,n){Mx(t,e,r);var o=function(v){if(v===a&&p)return p;if(!Za&&v&&v in c)return c[v];switch(v){case Up:return function(){return new t(this,v)};case di:return function(){return new t(this,v)};case Hp:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[ci]||c["@@iterator"]||a&&c[a],p=!Za&&d||o(a),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=_p(h.call(new i)),f!==Object.prototype&&f.next&&(!Xa&&_p(f)!==qp&&(Np?Np(f,qp):Lx(f[ci])||go(f,ci,jp)),Cx(f,u,!0,!0),Xa&&(Fp[u]=jp))),Ox&&a===di&&d&&d.name!==di&&(!Xa&&Bx?Dx(c,"name",di):(l=!0,p=function(){return $x(d,this)})),a)if(b={values:o(di),keys:s?p:o(Up),entries:o(Hp)},n)for(g in b)(Za||l||!(g in c))&&go(c,g,b[g]);else Rx({target:e,proto:!0,forced:Za||l},b);return(!Xa||n)&&c[ci]!==p&&go(c,ci,p,{name:a}),Fp[e]=p,b}});var Kp=m(($D,zp)=>{"use strict";zp.exports=function(i,e){return{value:i,done:e}}});var So=m((LD,th)=>{"use strict";var _x=Ft(),vo=ni(),Jp=Ht(),Zp=ro(),Nx=Ut().f,Fx=Yp(),es=Kp(),qx=Ne(),Ux=Ie(),eh="Array Iterator",Hx=Zp.set,jx=Zp.getterFor(eh);th.exports=Fx(Array,"Array",function(i,e){Hx(this,{type:eh,target:_x(i),index:0,kind:e})},function(){var i=jx(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,es(void 0,!0);switch(i.kind){case"keys":return es(t,!1);case"values":return es(e[t],!1)}return es([t,e[t]],!1)},"values");var Xp=Jp.Arguments=Jp.Array;vo("keys");vo("values");vo("entries");if(!qx&&Ux&&Xp.name!=="values")try{Nx(Xp,"name",{value:"values"})}catch{}});var ih=m((MD,rh)=>{"use strict";var Gx=ae(),Qx=Ht(),Wx=Gx("iterator"),Yx=Array.prototype;rh.exports=function(i){return i!==void 0&&(Qx.Array===i||Yx[Wx]===i)}});var yo=m((CD,sh)=>{"use strict";var zx=ui(),ah=ti(),Kx=hr(),Jx=Ht(),Xx=ae(),Zx=Xx("iterator");sh.exports=function(i){if(!Kx(i))return ah(i,Zx)||ah(i,"@@iterator")||Jx[zx(i)]}});var oh=m((DD,nh)=>{"use strict";var eP=Ee(),tP=Ye(),rP=ze(),iP=ei(),aP=yo(),sP=TypeError;nh.exports=function(i,e){var t=arguments.length<2?aP(i):e;if(tP(t))return rP(eP(t,i));throw new sP(iP(i)+" is not iterable")}});var ch=m((VD,lh)=>{"use strict";var nP=Ee(),uh=ze(),oP=ti();lh.exports=function(i,e,t){var r,a;uh(i);try{if(r=oP(i,"return"),!r){if(e==="throw")throw t;return t}r=nP(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return uh(r),t}});var rs=m((OD,mh)=>{"use strict";var uP=gr(),lP=Ee(),cP=ze(),dP=ei(),pP=ih(),hP=Tr(),dh=Zr(),mP=oh(),fP=yo(),ph=ch(),bP=TypeError,ts=function(i,e){this.stopped=i,this.result=e},hh=ts.prototype;mh.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=uP(e,r),l,c,d,p,h,f,b,g=function(k){return l&&ph(l,"normal",k),new ts(!0,k)},v=function(k){return a?(cP(k),o?u(k[0],k[1],g):u(k[0],k[1])):o?u(k,g):u(k)};if(s)l=i.iterator;else if(n)l=i;else{if(c=fP(i),!c)throw new bP(dP(i)+" is not iterable");if(pP(c)){for(d=0,p=hP(i);p>d;d++)if(h=v(i[d]),h&&dh(hh,h))return h;return new ts(!1)}l=mP(i,c)}for(f=s?i.next:l.next;!(b=lP(f,l)).done;){try{h=v(b.value)}catch(k){ph(l,"throw",k)}if(typeof h=="object"&&h&&dh(hh,h))return h}return new ts(!1)}});var bh=m((BD,fh)=>{"use strict";var gP=Ie(),vP=Ut(),SP=Xr();fh.exports=function(i,e,t){gP?vP.f(i,e,SP(0,t)):i[e]=t}});var gh=m(()=>{"use strict";var yP=z(),TP=rs(),IP=bh();yP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return TP(e,function(r,a){IP(t,r,a)},{AS_ENTRIES:!0}),t}})});var Sh=m((FD,vh)=>{"use strict";So();gh();var EP=mr();vh.exports=EP.Object.fromEntries});var Th=m((qD,yh)=>{"use strict";yh.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 Eh=m(()=>{"use strict";So();var xP=Th(),PP=Q(),kP=li(),Ih=Ht();for(is in xP)kP(PP[is],is),Ih[is]=Ih.Array;var is});var Ph=m((jD,xh)=>{"use strict";var AP=Sh();Eh();xh.exports=AP});var To=m((GD,kh)=>{"use strict";var wP=Ph();kh.exports=wP});var Ah=m(()=>{"use strict"});var Io=m((YD,wh)=>{"use strict";var pi=Q(),RP=qt(),$P=Nt(),as=function(i){return RP.slice(0,i.length)===i};wh.exports=function(){return as("Bun/")?"BUN":as("Cloudflare-Workers")?"CLOUDFLARE":as("Deno/")?"DENO":as("Node.js/")?"NODE":pi.Bun&&typeof Bun.version=="string"?"BUN":pi.Deno&&typeof Deno.version=="object"?"DENO":$P(pi.process)==="process"?"NODE":pi.window&&pi.document?"BROWSER":"REST"}()});var ss=m((zD,Rh)=>{"use strict";var LP=Io();Rh.exports=LP==="NODE"});var Lh=m((KD,$h)=>{"use strict";var MP=Ut();$h.exports=function(i,e,t){return MP.f(i,e,t)}});var Dh=m((JD,Ch)=>{"use strict";var CP=at(),DP=Lh(),VP=ae(),OP=Ie(),Mh=VP("species");Ch.exports=function(i){var e=CP(i);OP&&e&&!e[Mh]&&DP(e,Mh,{configurable:!0,get:function(){return this}})}});var Oh=m((XD,Vh)=>{"use strict";var BP=Zr(),_P=TypeError;Vh.exports=function(i,e){if(BP(e,i))return i;throw new _P("Incorrect invocation")}});var xo=m((ZD,Bh)=>{"use strict";var NP=J(),FP=G(),Eo=ri(),qP=NP(Function.toString);FP(Eo.inspectSource)||(Eo.inspectSource=function(i){return qP(i)});Bh.exports=Eo.inspectSource});var ko=m((eV,Uh)=>{"use strict";var UP=J(),HP=ie(),_h=G(),jP=ui(),GP=at(),QP=xo(),Nh=function(){},Fh=GP("Reflect","construct"),Po=/^\s*(?:class|function)\b/,WP=UP(Po.exec),YP=!Po.test(Nh),hi=function(e){if(!_h(e))return!1;try{return Fh(Nh,[],e),!0}catch{return!1}},qh=function(e){if(!_h(e))return!1;switch(jP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return YP||!!WP(Po,QP(e))}catch{return!0}};qh.sham=!0;Uh.exports=!Fh||HP(function(){var i;return hi(hi.call)||!hi(Object)||!hi(function(){i=!0})||i})?qh:hi});var jh=m((tV,Hh)=>{"use strict";var zP=ko(),KP=ei(),JP=TypeError;Hh.exports=function(i){if(zP(i))return i;throw new JP(KP(i)+" is not a constructor")}});var Ao=m((rV,Qh)=>{"use strict";var Gh=ze(),XP=jh(),ZP=hr(),ek=ae(),tk=ek("species");Qh.exports=function(i,e){var t=Gh(i).constructor,r;return t===void 0||ZP(r=Gh(t)[tk])?e:XP(r)}});var Yh=m((iV,Wh)=>{"use strict";var rk=J();Wh.exports=rk([].slice)});var Kh=m((aV,zh)=>{"use strict";var ik=TypeError;zh.exports=function(i,e){if(i<e)throw new ik("Not enough arguments");return i}});var wo=m((sV,Jh)=>{"use strict";var ak=qt();Jh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(ak)});var Bo=m((nV,nm)=>{"use strict";var Pe=Q(),sk=bn(),nk=gr(),Xh=G(),ok=Fe(),sm=ie(),Zh=no(),uk=Yh(),em=Na(),lk=Kh(),ck=wo(),dk=ss(),Do=Pe.setImmediate,Vo=Pe.clearImmediate,pk=Pe.process,Ro=Pe.Dispatch,hk=Pe.Function,tm=Pe.MessageChannel,mk=Pe.String,$o=0,mi={},rm="onreadystatechange",fi,Gt,Lo,Mo;sm(function(){fi=Pe.location});var Oo=function(i){if(ok(mi,i)){var e=mi[i];delete mi[i],e()}},Co=function(i){return function(){Oo(i)}},im=function(i){Oo(i.data)},am=function(i){Pe.postMessage(mk(i),fi.protocol+"//"+fi.host)};(!Do||!Vo)&&(Do=function(e){lk(arguments.length,1);var t=Xh(e)?e:hk(e),r=uk(arguments,1);return mi[++$o]=function(){sk(t,void 0,r)},Gt($o),$o},Vo=function(e){delete mi[e]},dk?Gt=function(i){pk.nextTick(Co(i))}:Ro&&Ro.now?Gt=function(i){Ro.now(Co(i))}:tm&&!ck?(Lo=new tm,Mo=Lo.port2,Lo.port1.onmessage=im,Gt=nk(Mo.postMessage,Mo)):Pe.addEventListener&&Xh(Pe.postMessage)&&!Pe.importScripts&&fi&&fi.protocol!=="file:"&&!sm(am)?(Gt=am,Pe.addEventListener("message",im,!1)):rm in em("script")?Gt=function(i){Zh.appendChild(em("script"))[rm]=function(){Zh.removeChild(this),Oo(i)}}:Gt=function(i){setTimeout(Co(i),0)});nm.exports={set:Do,clear:Vo}});var lm=m((oV,um)=>{"use strict";var om=Q(),fk=Ie(),bk=Object.getOwnPropertyDescriptor;um.exports=function(i){if(!fk)return om[i];var e=bk(om,i);return e&&e.value}});var _o=m((uV,dm)=>{"use strict";var cm=function(){this.head=null,this.tail=null};cm.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}}};dm.exports=cm});var hm=m((lV,pm)=>{"use strict";var gk=qt();pm.exports=/ipad|iphone|ipod/i.test(gk)&&typeof Pebble<"u"});var fm=m((cV,mm)=>{"use strict";var vk=qt();mm.exports=/web0s(?!.*chrome)/i.test(vk)});var Im=m((dV,Tm)=>{"use strict";var Pr=Q(),Sk=lm(),bm=gr(),No=Bo().set,yk=_o(),Tk=wo(),Ik=hm(),Ek=fm(),Fo=ss(),gm=Pr.MutationObserver||Pr.WebKitMutationObserver,vm=Pr.document,Sm=Pr.process,ns=Pr.Promise,Ho=Sk("queueMicrotask"),xr,qo,Uo,os,ym;Ho||(bi=new yk,gi=function(){var i,e;for(Fo&&(i=Sm.domain)&&i.exit();e=bi.get();)try{e()}catch(t){throw bi.head&&xr(),t}i&&i.enter()},!Tk&&!Fo&&!Ek&&gm&&vm?(qo=!0,Uo=vm.createTextNode(""),new gm(gi).observe(Uo,{characterData:!0}),xr=function(){Uo.data=qo=!qo}):!Ik&&ns&&ns.resolve?(os=ns.resolve(void 0),os.constructor=ns,ym=bm(os.then,os),xr=function(){ym(gi)}):Fo?xr=function(){Sm.nextTick(gi)}:(No=bm(No,Pr),xr=function(){No(gi)}),Ho=function(i){bi.head||xr(),bi.add(i)});var bi,gi;Tm.exports=Ho});var xm=m((pV,Em)=>{"use strict";Em.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var us=m((hV,Pm)=>{"use strict";Pm.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Qt=m((mV,km)=>{"use strict";var xk=Q();km.exports=xk.Promise});var kr=m((fV,$m)=>{"use strict";var Pk=Q(),vi=Qt(),kk=G(),Ak=_n(),wk=xo(),Rk=ae(),Am=Io(),$k=Ne(),jo=Pn(),wm=vi&&vi.prototype,Lk=Rk("species"),Go=!1,Rm=kk(Pk.PromiseRejectionEvent),Mk=Ak("Promise",function(){var i=wk(vi),e=i!==String(vi);if(!e&&jo===66||$k&&!(wm.catch&&wm.finally))return!0;if(!jo||jo<51||!/native code/.test(i)){var t=new vi(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Lk]=r,Go=t.then(function(){})instanceof r,!Go)return!0}return!e&&(Am==="BROWSER"||Am==="DENO")&&!Rm});$m.exports={CONSTRUCTOR:Mk,REJECTION_EVENT:Rm,SUBCLASSING:Go}});var Ar=m((bV,Mm)=>{"use strict";var Lm=Ye(),Ck=TypeError,Dk=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new Ck("Bad Promise constructor");e=r,t=a}),this.resolve=Lm(e),this.reject=Lm(t)};Mm.exports.f=function(i){return new Dk(i)}});var Jm=m(()=>{"use strict";var Vk=z(),Ok=Ne(),ps=ss(),St=Q(),Lr=Ee(),Cm=Er(),Dm=bo(),Bk=li(),_k=Dh(),Nk=Ye(),ds=G(),Fk=xe(),qk=Oh(),Uk=Ao(),Nm=Bo().set,Ko=Im(),Hk=xm(),jk=us(),Gk=_o(),Fm=ro(),hs=Qt(),Jo=kr(),qm=Ar(),ms="Promise",Um=Jo.CONSTRUCTOR,Qk=Jo.REJECTION_EVENT,Wk=Jo.SUBCLASSING,Qo=Fm.getterFor(ms),Yk=Fm.set,wr=hs&&hs.prototype,Wt=hs,ls=wr,Hm=St.TypeError,Wo=St.document,Xo=St.process,Yo=qm.f,zk=Yo,Kk=!!(Wo&&Wo.createEvent&&St.dispatchEvent),jm="unhandledrejection",Jk="rejectionhandled",Vm=0,Gm=1,Xk=2,Zo=1,Qm=2,cs,Om,Zk,Bm,Wm=function(i){var e;return Fk(i)&&ds(e=i.then)?e:!1},Ym=function(i,e){var t=e.value,r=e.state===Gm,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===Qm&&tA(e),e.rejection=Zo),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(new Hm("Promise-chain cycle")):(l=Wm(u))?Lr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},zm=function(i,e){i.notified||(i.notified=!0,Ko(function(){for(var t=i.reactions,r;r=t.get();)Ym(r,i);i.notified=!1,e&&!i.rejection&&eA(i)}))},Km=function(i,e,t){var r,a;Kk?(r=Wo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),St.dispatchEvent(r)):r={promise:e,reason:t},!Qk&&(a=St["on"+i])?a(r):i===jm&&Hk("Unhandled promise rejection",t)},eA=function(i){Lr(Nm,St,function(){var e=i.facade,t=i.value,r=_m(i),a;if(r&&(a=jk(function(){ps?Xo.emit("unhandledRejection",t,e):Km(jm,e,t)}),i.rejection=ps||_m(i)?Qm:Zo,a.error))throw a.value})},_m=function(i){return i.rejection!==Zo&&!i.parent},tA=function(i){Lr(Nm,St,function(){var e=i.facade;ps?Xo.emit("rejectionHandled",e):Km(Jk,e,i.value)})},Rr=function(i,e,t){return function(r){i(e,r,t)}},$r=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Xk,zm(i,!0))},zo=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new Hm("Promise can't be resolved itself");var r=Wm(e);r?Ko(function(){var a={done:!1};try{Lr(r,e,Rr(zo,a,i),Rr($r,a,i))}catch(s){$r(a,s,i)}}):(i.value=e,i.state=Gm,zm(i,!1))}catch(a){$r({done:!1},a,i)}}};if(Um&&(Wt=function(e){qk(this,ls),Nk(e),Lr(cs,this);var t=Qo(this);try{e(Rr(zo,t),Rr($r,t))}catch(r){$r(t,r)}},ls=Wt.prototype,cs=function(e){Yk(this,{type:ms,done:!1,notified:!1,parent:!1,reactions:new Gk,rejection:!1,state:Vm,value:void 0})},cs.prototype=Cm(ls,"then",function(e,t){var r=Qo(this),a=Yo(Uk(this,Wt));return r.parent=!0,a.ok=ds(e)?e:!0,a.fail=ds(t)&&t,a.domain=ps?Xo.domain:void 0,r.state===Vm?r.reactions.add(a):Ko(function(){Ym(a,r)}),a.promise}),Om=function(){var i=new cs,e=Qo(i);this.promise=i,this.resolve=Rr(zo,e),this.reject=Rr($r,e)},qm.f=Yo=function(i){return i===Wt||i===Zk?new Om(i):zk(i)},!Ok&&ds(hs)&&wr!==Object.prototype)){Bm=wr.then,Wk||Cm(wr,"then",function(e,t){var r=this;return new Wt(function(a,s){Lr(Bm,r,a,s)}).then(e,t)},{unsafe:!0});try{delete wr.constructor}catch{}Dm&&Dm(wr,ls)}Vk({global:!0,constructor:!0,wrap:!0,forced:Um},{Promise:Wt});Bk(Wt,ms,!1,!0);_k(ms)});var rf=m((SV,tf)=>{"use strict";var rA=ae(),Zm=rA("iterator"),ef=!1;try{Xm=0,eu={next:function(){return{done:!!Xm++}},return:function(){ef=!0}},eu[Zm]=function(){return this},Array.from(eu,function(){throw 2})}catch{}var Xm,eu;tf.exports=function(i,e){try{if(!e&&!ef)return!1}catch{return!1}var t=!1;try{var r={};r[Zm]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var tu=m((yV,af)=>{"use strict";var iA=Qt(),aA=rf(),sA=kr().CONSTRUCTOR;af.exports=sA||!aA(function(i){iA.all(i).then(void 0,function(){})})});var sf=m(()=>{"use strict";var nA=z(),oA=Ee(),uA=Ye(),lA=Ar(),cA=us(),dA=rs(),pA=tu();nA({target:"Promise",stat:!0,forced:pA},{all:function(e){var t=this,r=lA.f(t),a=r.resolve,s=r.reject,n=cA(function(){var o=uA(t.resolve),u=[],l=0,c=1;dA(e,function(d){var p=l++,h=!1;c++,oA(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var of=m(()=>{"use strict";var hA=z(),mA=Ne(),fA=kr().CONSTRUCTOR,iu=Qt(),bA=at(),gA=G(),vA=Er(),nf=iu&&iu.prototype;hA({target:"Promise",proto:!0,forced:fA,real:!0},{catch:function(i){return this.then(void 0,i)}});!mA&&gA(iu)&&(ru=bA("Promise").prototype.catch,nf.catch!==ru&&vA(nf,"catch",ru,{unsafe:!0}));var ru});var uf=m(()=>{"use strict";var SA=z(),yA=Ee(),TA=Ye(),IA=Ar(),EA=us(),xA=rs(),PA=tu();SA({target:"Promise",stat:!0,forced:PA},{race:function(e){var t=this,r=IA.f(t),a=r.reject,s=EA(function(){var n=TA(t.resolve);xA(e,function(o){yA(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var lf=m(()=>{"use strict";var kA=z(),AA=Ar(),wA=kr().CONSTRUCTOR;kA({target:"Promise",stat:!0,forced:wA},{reject:function(e){var t=AA.f(this),r=t.reject;return r(e),t.promise}})});var au=m((RV,cf)=>{"use strict";var RA=ze(),$A=xe(),LA=Ar();cf.exports=function(i,e){if(RA(i),$A(e)&&e.constructor===i)return e;var t=LA.f(i),r=t.resolve;return r(e),t.promise}});var hf=m(()=>{"use strict";var MA=z(),CA=at(),df=Ne(),DA=Qt(),pf=kr().CONSTRUCTOR,VA=au(),OA=CA("Promise"),BA=df&&!pf;MA({target:"Promise",stat:!0,forced:df||pf},{resolve:function(e){return VA(BA&&this===OA?DA:this,e)}})});var mf=m(()=>{"use strict";Jm();sf();of();uf();lf();hf()});var vf=m(()=>{"use strict";var _A=z(),NA=Ne(),fs=Qt(),FA=ie(),bf=at(),gf=G(),qA=Ao(),ff=au(),UA=Er(),nu=fs&&fs.prototype,HA=!!fs&&FA(function(){nu.finally.call({then:function(){}},function(){})});_A({target:"Promise",proto:!0,real:!0,forced:HA},{finally:function(i){var e=qA(this,bf("Promise")),t=gf(i);return this.then(t?function(r){return ff(e,i()).then(function(){return r})}:i,t?function(r){return ff(e,i()).then(function(){throw r})}:i)}});!NA&&gf(fs)&&(su=bf("Promise").prototype.finally,nu.finally!==su&&UA(nu,"finally",su,{unsafe:!0}));var su});var yf=m((OV,Sf)=>{"use strict";Ah();mf();vf();var jA=vt();Sf.exports=jA("Promise","finally")});var If=m((BV,Tf)=>{"use strict";var GA=yf();Tf.exports=GA});var bs=m((_V,Ef)=>{"use strict";var QA=If();Ef.exports=QA});var Of=m(()=>{"use strict";var nw=z(),ow=Xn().values;nw({target:"Object",stat:!0},{values:function(e){return ow(e)}})});var _f=m((IO,Bf)=>{"use strict";Of();var uw=mr();Bf.exports=uw.Object.values});var Ff=m((EO,Nf)=>{"use strict";var lw=_f();Nf.exports=lw});var yi=m((xO,qf)=>{"use strict";var cw=Ff();qf.exports=cw});var eb=m(()=>{"use strict";var kw=z(),Aw=fr(),ww=Tr(),Rw=si(),$w=ni();kw({target:"Array",proto:!0},{at:function(e){var t=Aw(this),r=ww(t),a=Rw(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});$w("at")});var rb=m((XO,tb)=>{"use strict";eb();var Lw=vt();tb.exports=Lw("Array","at")});var ab=m((ZO,ib)=>{"use strict";var Mw=rb();ib.exports=Mw});var Dr=m((eB,sb)=>{"use strict";var Cw=ab();sb.exports=Cw});var Ru=m((k_,Vb)=>{"use strict";var mR=Nt();Vb.exports=Array.isArray||function(e){return mR(e)==="Array"}});var Bb=m((A_,Ob)=>{"use strict";var fR=TypeError,bR=9007199254740991;Ob.exports=function(i){if(i>bR)throw fR("Maximum allowed index exceeded");return i}});var Fb=m((w_,Nb)=>{"use strict";var gR=Ru(),vR=Tr(),SR=Bb(),yR=gr(),_b=function(i,e,t,r,a,s,n,o){for(var u=a,l=0,c=n?yR(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&gR(d)?(p=vR(d),u=_b(i,e,d,p,u,s-1)-1):(SR(u+1),i[u]=d),u++),l++;return u};Nb.exports=_b});var jb=m((R_,Hb)=>{"use strict";var qb=Ru(),TR=ko(),IR=xe(),ER=ae(),xR=ER("species"),Ub=Array;Hb.exports=function(i){var e;return qb(i)&&(e=i.constructor,TR(e)&&(e===Ub||qb(e.prototype))?e=void 0:IR(e)&&(e=e[xR],e===null&&(e=void 0))),e===void 0?Ub:e}});var Qb=m(($_,Gb)=>{"use strict";var PR=jb();Gb.exports=function(i,e){return new(PR(i))(e===0?0:e)}});var Wb=m(()=>{"use strict";var kR=z(),AR=Fb(),wR=Ye(),RR=fr(),$R=Tr(),LR=Qb();kR({target:"Array",proto:!0},{flatMap:function(e){var t=RR(this),r=$R(t),a;return wR(e),a=LR(t,0),a.length=AR(a,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var Yb=m(()=>{"use strict";var MR=ni();MR("flatMap")});var Kb=m((V_,zb)=>{"use strict";Wb();Yb();var CR=vt();zb.exports=CR("Array","flatMap")});var Xb=m((O_,Jb)=>{"use strict";var DR=Kb();Jb.exports=DR});var $u=m((B_,Zb)=>{"use strict";var VR=Xb();Zb.exports=VR});var Di=m((W_,lg)=>{"use strict";var HR=ui(),jR=String;lg.exports=function(i){if(HR(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return jR(i)}});var Mu=m((Y_,cg)=>{"use strict";cg.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 hg=m((z_,pg)=>{"use strict";var GR=J(),QR=gt(),WR=Di(),Du=Mu(),dg=GR("".replace),YR=RegExp("^["+Du+"]+"),zR=RegExp("(^|[^"+Du+"])["+Du+"]+$"),Cu=function(i){return function(e){var t=WR(QR(e));return i&1&&(t=dg(t,YR,"")),i&2&&(t=dg(t,zR,"$1")),t}};pg.exports={start:Cu(1),end:Cu(2),trim:Cu(3)}});var gg=m((K_,bg)=>{"use strict";var KR=so().PROPER,JR=ie(),mg=Mu(),fg="\u200B\x85\u180E";bg.exports=function(i){return JR(function(){return!!mg[i]()||fg[i]()!==fg||KR&&mg[i].name!==i})}});var Vu=m((J_,vg)=>{"use strict";var XR=hg().start,ZR=gg();vg.exports=ZR("trimStart")?function(){return XR(this)}:"".trimStart});var yg=m(()=>{"use strict";var e$=z(),Sg=Vu();e$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Sg},{trimLeft:Sg})});var Ig=m(()=>{"use strict";yg();var t$=z(),Tg=Vu();t$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Tg},{trimStart:Tg})});var xg=m((rN,Eg)=>{"use strict";Ig();var r$=vt();Eg.exports=r$("String","trimLeft")});var kg=m((iN,Pg)=>{"use strict";var i$=xg();Pg.exports=i$});var wg=m((aN,Ag)=>{"use strict";var a$=kg();Ag.exports=a$});var jg=m(()=>{"use strict"});var Gg=m(()=>{"use strict"});var Wg=m((wq,Qg)=>{"use strict";var A$=xe(),w$=Nt(),R$=ae(),$$=R$("match");Qg.exports=function(i){var e;return A$(i)&&((e=i[$$])!==void 0?!!e:w$(i)==="RegExp")}});var zg=m((Rq,Yg)=>{"use strict";var L$=ze();Yg.exports=function(){var i=L$(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 Xg=m(($q,Jg)=>{"use strict";var M$=Ee(),C$=Fe(),D$=Zr(),V$=zg(),Kg=RegExp.prototype;Jg.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Kg)&&!C$(i,"flags")&&D$(Kg,i)?M$(V$,i):e}});var ev=m((Lq,Zg)=>{"use strict";var ju=J(),O$=fr(),B$=Math.floor,Uu=ju("".charAt),_$=ju("".replace),Hu=ju("".slice),N$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,F$=/\$([$&'`]|\d{1,2})/g;Zg.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=F$;return a!==void 0&&(a=O$(a),u=N$),_$(s,u,function(l,c){var d;switch(Uu(c,0)){case"$":return"$";case"&":return i;case"`":return Hu(e,0,t);case"'":return Hu(e,n);case"<":d=a[Hu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=B$(p/10);return h===0?l:h<=o?r[h-1]===void 0?Uu(c,1):r[h-1]+Uu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var iv=m(()=>{"use strict";var q$=z(),U$=Ee(),Qu=J(),tv=gt(),H$=G(),j$=hr(),G$=Wg(),Fr=Di(),Q$=ti(),W$=Xg(),Y$=ev(),z$=ae(),K$=Ne(),J$=z$("replace"),X$=TypeError,Gu=Qu("".indexOf),Z$=Qu("".replace),rv=Qu("".slice),eL=Math.max;q$({target:"String",proto:!0},{replaceAll:function(e,t){var r=tv(this),a,s,n,o,u,l,c,d,p,h,f=0,b="";if(!j$(e)){if(a=G$(e),a&&(s=Fr(tv(W$(e))),!~Gu(s,"g")))throw new X$("`.replaceAll` does not allow non-global regexes");if(n=Q$(e,J$),n)return U$(n,e,r,t);if(K$&&a)return Z$(Fr(r),e,t)}for(o=Fr(r),u=Fr(e),l=H$(t),l||(t=Fr(t)),c=u.length,d=eL(1,c),p=Gu(o,u);p!==-1;)h=l?Fr(t(u,p,o)):Y$(u,o,p,[],void 0,t),b+=rv(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Gu(o,u,p+d);return f<o.length&&(b+=rv(o,f)),b}})});var sv=m((Dq,av)=>{"use strict";jg();Gg();iv();var tL=vt();av.exports=tL("String","replaceAll")});var ov=m((Vq,nv)=>{"use strict";var rL=sv();nv.exports=rL});var lv=m((Oq,uv)=>{"use strict";var iL=ov();uv.exports=iL});var dv=m((Bq,cv)=>{"use strict";var aL=si(),sL=Di(),nL=gt(),oL=RangeError;cv.exports=function(e){var t=sL(nL(this)),r="",a=aL(e);if(a<0||a===1/0)throw new oL("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(r+=t);return r}});var bv=m((_q,fv)=>{"use strict";var mv=J(),uL=jn(),pv=Di(),lL=dv(),cL=gt(),dL=mv(lL),pL=mv("".slice),hL=Math.ceil,hv=function(i){return function(e,t,r){var a=pv(cL(e)),s=uL(t),n=a.length,o=r===void 0?" ":pv(r),u,l;return s<=n||o===""?a:(u=s-n,l=dL(o,hL(u/o.length)),l.length>u&&(l=pL(l,0,u)),i?a+l:l+a)}};fv.exports={start:hv(!1),end:hv(!0)}});var vv=m((Nq,gv)=>{"use strict";var mL=qt();gv.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(mL)});var Sv=m(()=>{"use strict";var fL=z(),bL=bv().start,gL=vv();fL({target:"String",proto:!0,forced:gL},{padStart:function(e){return bL(this,e,arguments.length>1?arguments[1]:void 0)}})});var Tv=m((Uq,yv)=>{"use strict";Sv();var vL=vt();yv.exports=vL("String","padStart")});var Ev=m((Hq,Iv)=>{"use strict";var SL=Tv();Iv.exports=SL});var Pv=m((jq,xv)=>{"use strict";var yL=Ev();xv.exports=yL});var Ll="2.0.123-dev.c995f51b.0";var pe=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(pe||{}),bt=(E=>(E.MPEG="MPEG",E.DASH="DASH",E.DASH_SEP="DASH_SEP",E.DASH_SEP_VK="DASH_SEP",E.DASH_WEBM="DASH_WEBM",E.DASH_WEBM_AV1="DASH_WEBM_AV1",E.DASH_STREAMS="DASH_STREAMS",E.DASH_WEBM_VK="DASH_WEBM",E.DASH_ONDEMAND="DASH_ONDEMAND",E.DASH_ONDEMAND_VK="DASH_ONDEMAND",E.DASH_LIVE="DASH_LIVE",E.DASH_LIVE_CMAF="DASH_LIVE_CMAF",E.DASH_LIVE_WEBM="DASH_LIVE_WEBM",E.HLS="HLS",E.HLS_ONDEMAND="HLS_ONDEMAND",E.HLS_JS="HLS",E.HLS_LIVE="HLS_LIVE",E.HLS_LIVE_CMAF="HLS_LIVE_CMAF",E.WEB_RTC_LIVE="WEB_RTC_LIVE",E))(bt||{});var Oa=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Oa||{}),hn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(hn||{});var mn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(mn||{});var ty=C(Ke(),1);import{assertNever as Rd,assertNonNullable as CI,isNonNullable as qa,ValueSubject as Qn,Subject as DI,Subscription as VI,merge as OI,observableFrom as BI,fromEvent as Pd,map as kd,tap as Ad,filterChanged as _I,isNullable as Wn,ErrorCategory as wd}from"@vkontakte/videoplayer-shared";var xd=i=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var Ua=class{constructor(e){this.connection$=new Qn(void 0);this.castState$=new Qn("NOT_AVAILABLE");this.errorEvent$=new DI;this.realCastState$=new Qn("NOT_AVAILABLE");this.subscription=new VI;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=qa(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},a||xd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:wd.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(){qa(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Wn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Wn(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Pd(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 Rd(a.sessionState)}})).add(OI(Pd(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ad(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),kd(a=>a.castState)),BI([r.getCastState()])).pipe(_I(),kd(NI),Ad(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=qa(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();CI(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(Wn(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"?qa(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:wd.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},NI=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 Rd(i)}};var Il=C(Ke(),1),VS=C(Ir(),1),OS=C(To(),1);var Cf=C(bs(),1);import{assertNever as xf}from"@vkontakte/videoplayer-shared";var se=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:xf(t)}return i},gs=(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:xf(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as WA,Subject as vs,merge as Pf}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new vs;this.transitionEnded$=new vs;this.transitionUpdated$=new vs;this.forceChanged$=new vs;this.stateChangeStarted$=Pf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Pf(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||WA(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 YA}from"@vkontakte/videoplayer-shared";var kf=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 YA(i)}};import{assertNever as Mr,assertNonNullable as Yt,debounce as Af,ErrorCategory as wf,fromEvent as zt,isNonNullable as Rf,map as $f,merge as Lf,observableFrom as zA,Subject as KA,Subscription as ou,timeout as JA,getHighestQuality as XA}from"@vkontakte/videoplayer-shared";var ZA=5,ew=5,tw=500,Mf=7e3,Si=class{constructor(e){this.subscription=new ou;this.loadMediaTimeoutSubscription=new ou;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:Mr(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:Mr(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:Mr(e)}break}default:Mr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(kf(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 ou;this.subscription.add(e),this.subscription.add(Lf(this.videoState.stateChangeStarted$.pipe($f(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe($f(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 KA;e.add(a.pipe(Af(tw)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(zt(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)>ZA)&&a.next(o),s=o})),e.add(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(zt(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<ew&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Mr(n)}}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(zt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Lf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,zA(["init"])).pipe(Af(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&I(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let l=t[e];Yt(l);let c=XA(Object.keys(l));Yt(c);let d=l[c];Yt(d),r=d,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Yt(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];Yt(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Yt(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];Yt(l),r=se(l.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:wf.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Mr(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 Rf(o)&&(n.metadata.title=o),Rf(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(JA(Mf).subscribe(()=>s(`timeout(${Mf})`)))});(0,Cf.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:wf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Au=C(Ke(),1);import{clearVideoElement as Vf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as rw}from"@vkontakte/videoplayer-shared";var Df=i=>{try{i.pause(),i.playbackRate=0,rw(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as iw,Subscription as aw}from"@vkontakte/videoplayer-shared";var uu=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)}},lu=window.WeakMap?new WeakMap:new uu,cu=window.WeakMap?new WeakMap:new Map,sw=(i,e=20)=>{let t=0;return iw(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},he=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Vf(t):(t=document.createElement("video"),i.appendChild(t)),lu.set(t,r);let a=new aw;return a.add(sw(t,e)),cu.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},me=i=>{cu.get(i)?.unsubscribe(),cu.delete(i);let t=lu.get(i);lu.delete(i),t?Vf(i):Df(i)};var pu=C(yi(),1);import{assertNonNullable as Ti,isNonNullable as Xe,isNullable as hw,fromEvent as Cr,merge as Uf,observableFrom as Hf,filterChanged as jf,map as Ii,Subject as Gf,Subscription as mw,ValueSubject as fw,ErrorCategory as bw}from"@vkontakte/videoplayer-shared";import{isNonNullable as du,isNullable as dw,Subscription as pw}from"@vkontakte/videoplayer-shared";var Ss=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=dw(a),l=new pw;return a&&l.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},s)),l},Je=(i,e,t)=>Ss(e,()=>i.loop,r=>{du(r)&&(i.loop=r)},{onError:t}),fe=(i,e,t,r)=>Ss(e,()=>({muted:i.muted,volume:i.volume}),a=>{du(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),$e=(i,e,t,r)=>Ss(e,()=>i.playbackRate,a=>{du(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),yt=Ss;var gw=i=>["__",i.language,i.label].join("|"),vw=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},hu=class i{constructor(){this.available$=new Gf;this.current$=new fw(void 0);this.error$=new Gf;this.subscription=new mw;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let a=s=>{this.error$.next({id:"TextTracksManager",category:bw.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(yt(t.internalTextTracks,()=>(0,pu.default)(this.internalTracks),s=>{Xe(s)&&this.setInternal(s)},{equal:(s,n)=>Xe(s)&&Xe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ii(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(yt(t.externalTextTracks,()=>(0,pu.default)(this.externalTracks),s=>{Xe(s)&&this.setExternal(s)},{equal:(s,n)=>Xe(s)&&Xe(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ii(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(yt(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(yt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Ti(this.video);let{textTracks:e}=this.video;this.subscription.add(Cr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Uf(Cr(e,"addtrack"),Cr(e,"removetrack"),Hf(["init"])).pipe(Ii(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),jf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Uf(Cr(e,"change"),Hf(["init"])).pipe(Ii(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ii(r=>r&&this.htmlTextTrackToITextTrack(r).id),jf()).subscribe(this.current$));let t=r=>this.applyCueSettings(r.target?.activeCues??null);this.subscription.add(Cr(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(Cr(e,"removetrack").subscribe(r=>{r.track?.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let a=r;Xe(t.align)&&(a.align=t.align),Xe(t.position)&&(a.position=t.position),Xe(t.size)&&(a.size=t.size),Xe(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){Ti(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){let{language:t,label:r}=e,a=e.id?e.id:gw(e),s=this.externalTracks.has(a),n=(s?this.externalTracks.get(a)?.isAuto:this.internalTracks.get(a)?.isAuto)??a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:this.externalTracks.get(a)?.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:this.internalTracks.get(a)?.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){Ti(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(hw(e)||!vw(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){Ti(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Ti(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Le=hu;var ot=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Qf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},mu=i=>{let e=Qf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Wf=i=>{let e=Qf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Me,map as Tt,merge as zf,filterChanged as yw,isNonNullable as Kf,Subject as Tw,filter as Jf,mapTo as Xf,combine as Iw,once as Ew,ErrorCategory as xw,ValueSubject as Zf,clientChecker as Pw}from"@vkontakte/videoplayer-shared";var Sw=3,Yf=(i,e,t=Sw)=>{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 be=i=>{let e=E=>Me(i,E).pipe(Xf(void 0)),r=zf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>Me(i,E))).pipe(Tt(E=>E.type==="ended"?i.readyState<2:i.readyState<3),yw()),a=zf(Me(i,"progress"),Me(i,"timeupdate")).pipe(Tt(()=>Yf(i.buffered,i.currentTime))),s=Pw.isSafari?Iw({play:e("play").pipe(Ew()),playing:e("playing")}).pipe(Xf(void 0)):e("playing"),n=Me(i,"volumechange").pipe(Tt(()=>({muted:i.muted,volume:i.volume}))),o=Me(i,"ratechange").pipe(Tt(()=>i.playbackRate)),u=Me(i,"error").pipe(Jf(()=>!!(i.error||i.played.length)),Tt(()=>{let E=i.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:xw.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:i.error??void 0}})),l=Me(i,"timeupdate").pipe(Tt(()=>i.currentTime)),c=new Tw,d=.3,p;l.subscribe(E=>{i.loop&&Kf(p)&&Kf(E)&&p>=i.duration-d&&E<=d&&c.next(p),p=E});let h=e("pause").pipe(Jf(()=>!i.error&&p!==i.duration)),f=Me(i,"enterpictureinpicture"),b=Me(i,"leavepictureinpicture"),g=new Zf(Wf(i));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Zf(mu(i));return Me(i,"fullscreenchange").pipe(Tt(()=>mu(i))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Me(i,"durationchange").pipe(Tt(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:f,leavePip$:b}};import{VideoQuality as It}from"@vkontakte/videoplayer-shared";var Et=i=>{switch(i){case"mobile":return It.Q_144P;case"lowest":return It.Q_240P;case"low":return It.Q_360P;case"sd":case"medium":return It.Q_480P;case"hd":case"high":return It.Q_720P;case"fullhd":case"full":return It.Q_1080P;case"quadhd":case"quad":return It.Q_1440P;case"ultrahd":case"ultra":return It.Q_2160P}};var xt=C(Dr(),1),pb=C(Ke(),1),ys=C(Ir(),1);import{isNonNullable as X,isNullable as bu,now as hb,isHigher as gu,isHigherOrEqual as vu,isInvariantQuality as lb,isLower as cb,isLowerOrEqual as Su,videoSizeToQuality as Dw,assertNotEmptyArray as mb,assertNonNullable as Vw}from"@vkontakte/videoplayer-shared";var fu=!1,ut={},nb=i=>{fu=i},ob=()=>{ut={}},ub=i=>{i(ut)},Ei=(i,e)=>{fu&&(ut.meta=ut.meta??{},ut.meta[i]=e)},ue=class{constructor(e){this.name=e}next(e){if(!fu)return;ut.series=ut.series??{};let t=ut.series[this.name]??[];t.push([Date.now(),e]),ut.series[this.name]=t}};var Ow=new ue("best_bitrate"),fb=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var yu=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),xi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=hb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},bb='Assertion "ABR Tracks is empty array" failed',Ts=(i,e,t,r)=>{let a=[...e].sort(yu(1)),s=[...t].sort(yu(1)),n=s.filter(u=>X(u.bitrate)&&X(i.bitrate)?i.bitrate/u.bitrate>r:!0),o=(0,xt.default)(s,Math.round(s.length*a.indexOf(i)/(a.length+1)))??(0,xt.default)(s,-1);return o&&(0,pb.default)(n,o)?o:n.length?(0,xt.default)(n,-1):(0,xt.default)(s,0)},db=i=>"quality"in i,gb=(i,e,t,r)=>{let a=X(r?.last?.bitrate)&&X(t?.bitrate)&&r.last.bitrate<t.bitrate?i.trackCooldownIncreaseQuality:i.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&hb()-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=db(n)?"video":"audio",u=db(n)?n.quality:n.bitrate;return e({message:`
|
|
6
|
+
var dy=Object.create;var Cl=Object.defineProperty;var py=Object.getOwnPropertyDescriptor;var hy=Object.getOwnPropertyNames;var my=Object.getPrototypeOf,fy=Object.prototype.hasOwnProperty;var h=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var by=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of hy(e))!fy.call(i,a)&&a!==t&&Cl(i,a,{get:()=>e[a],enumerable:!(r=py(e,a))||r.enumerable});return i};var M=(i,e,t)=>(t=i!=null?dy(my(i)):{},by(e||!i||!i.__esModule?Cl(t,"default",{value:i,enumerable:!0}):t,i));var Y=h((gn,Ol)=>{"use strict";var Jr=function(i){return i&&i.Math===Math&&i};Ol.exports=Jr(typeof globalThis=="object"&&globalThis)||Jr(typeof window=="object"&&window)||Jr(typeof self=="object"&&self)||Jr(typeof global=="object"&&global)||Jr(typeof gn=="object"&&gn)||function(){return this}()||Function("return this")()});var ie=h((GD,Bl)=>{"use strict";Bl.exports=function(i){try{return!!i()}catch{return!0}}});var Zr=h((QD,_l)=>{"use strict";var gy=ie();_l.exports=!gy(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var Sn=h((WD,Ul)=>{"use strict";var Sy=Zr(),ql=Function.prototype,Nl=ql.apply,Fl=ql.call;Ul.exports=typeof Reflect=="object"&&Reflect.apply||(Sy?Fl.bind(Nl):function(){return Fl.apply(Nl,arguments)})});var J=h((YD,Gl)=>{"use strict";var Hl=Zr(),jl=Function.prototype,vn=jl.call,vy=Hl&&jl.bind.bind(vn,vn);Gl.exports=Hl?vy:function(i){return function(){return vn.apply(i,arguments)}}});var qt=h((zD,Wl)=>{"use strict";var Ql=J(),yy=Ql({}.toString),Ty=Ql("".slice);Wl.exports=function(i){return Ty(yy(i),8,-1)}});var yn=h((KD,Yl)=>{"use strict";var Iy=qt(),Ey=J();Yl.exports=function(i){if(Iy(i)==="Function")return Ey(i)}});var W=h((XD,zl)=>{"use strict";var Tn=typeof document=="object"&&document.all;zl.exports=typeof Tn>"u"&&Tn!==void 0?function(i){return typeof i=="function"||i===Tn}:function(i){return typeof i=="function"}});var xe=h((JD,Kl)=>{"use strict";var xy=ie();Kl.exports=!xy(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Pe=h((ZD,Xl)=>{"use strict";var Py=Zr(),Fa=Function.prototype.call;Xl.exports=Py?Fa.bind(Fa):function(){return Fa.apply(Fa,arguments)}});var In=h(ec=>{"use strict";var Jl={}.propertyIsEnumerable,Zl=Object.getOwnPropertyDescriptor,ky=Zl&&!Jl.call({1:2},1);ec.f=ky?function(e){var t=Zl(this,e);return!!t&&t.enumerable}:Jl});var ei=h((tC,tc)=>{"use strict";tc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var ic=h((rC,rc)=>{"use strict";var wy=J(),Ay=ie(),Ry=qt(),En=Object,$y=wy("".split);rc.exports=Ay(function(){return!En("z").propertyIsEnumerable(0)})?function(i){return Ry(i)==="String"?$y(i,""):En(i)}:En});var fr=h((iC,ac)=>{"use strict";ac.exports=function(i){return i==null}});var Tt=h((aC,sc)=>{"use strict";var Ly=fr(),My=TypeError;sc.exports=function(i){if(Ly(i))throw new My("Can't call method on "+i);return i}});var Ut=h((sC,nc)=>{"use strict";var Dy=ic(),Cy=Tt();nc.exports=function(i){return Dy(Cy(i))}});var ke=h((nC,oc)=>{"use strict";var Vy=W();oc.exports=function(i){return typeof i=="object"?i!==null:Vy(i)}});var br=h((oC,uc)=>{"use strict";uc.exports={}});var ut=h((uC,cc)=>{"use strict";var xn=br(),Pn=Y(),Oy=W(),lc=function(i){return Oy(i)?i:void 0};cc.exports=function(i,e){return arguments.length<2?lc(xn[i])||lc(Pn[i]):xn[i]&&xn[i][e]||Pn[i]&&Pn[i][e]}});var ti=h((lC,dc)=>{"use strict";var By=J();dc.exports=By({}.isPrototypeOf)});var Ht=h((cC,mc)=>{"use strict";var _y=Y(),pc=_y.navigator,hc=pc&&pc.userAgent;mc.exports=hc?String(hc):""});var wn=h((dC,yc)=>{"use strict";var vc=Y(),kn=Ht(),fc=vc.process,bc=vc.Deno,gc=fc&&fc.versions||bc&&bc.version,Sc=gc&&gc.v8,Fe,qa;Sc&&(Fe=Sc.split("."),qa=Fe[0]>0&&Fe[0]<4?1:+(Fe[0]+Fe[1]));!qa&&kn&&(Fe=kn.match(/Edge\/(\d+)/),(!Fe||Fe[1]>=74)&&(Fe=kn.match(/Chrome\/(\d+)/),Fe&&(qa=+Fe[1])));yc.exports=qa});var An=h((pC,Ic)=>{"use strict";var Tc=wn(),Ny=ie(),Fy=Y(),qy=Fy.String;Ic.exports=!!Object.getOwnPropertySymbols&&!Ny(function(){var i=Symbol("symbol detection");return!qy(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Tc&&Tc<41})});var Rn=h((hC,Ec)=>{"use strict";var Uy=An();Ec.exports=Uy&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var $n=h((mC,xc)=>{"use strict";var Hy=ut(),jy=W(),Gy=ti(),Qy=Rn(),Wy=Object;xc.exports=Qy?function(i){return typeof i=="symbol"}:function(i){var e=Hy("Symbol");return jy(e)&&Gy(e.prototype,Wy(i))}});var ri=h((fC,Pc)=>{"use strict";var Yy=String;Pc.exports=function(i){try{return Yy(i)}catch{return"Object"}}});var Je=h((bC,kc)=>{"use strict";var zy=W(),Ky=ri(),Xy=TypeError;kc.exports=function(i){if(zy(i))return i;throw new Xy(Ky(i)+" is not a function")}});var ii=h((gC,wc)=>{"use strict";var Jy=Je(),Zy=fr();wc.exports=function(i,e){var t=i[e];return Zy(t)?void 0:Jy(t)}});var Rc=h((SC,Ac)=>{"use strict";var Ln=Pe(),Mn=W(),Dn=ke(),eT=TypeError;Ac.exports=function(i,e){var t,r;if(e==="string"&&Mn(t=i.toString)&&!Dn(r=Ln(t,i))||Mn(t=i.valueOf)&&!Dn(r=Ln(t,i))||e!=="string"&&Mn(t=i.toString)&&!Dn(r=Ln(t,i)))return r;throw new eT("Can't convert object to primitive value")}});var qe=h((vC,$c)=>{"use strict";$c.exports=!0});var Dc=h((yC,Mc)=>{"use strict";var Lc=Y(),tT=Object.defineProperty;Mc.exports=function(i,e){try{tT(Lc,i,{value:e,configurable:!0,writable:!0})}catch{Lc[i]=e}return e}});var ai=h((TC,Oc)=>{"use strict";var rT=qe(),iT=Y(),aT=Dc(),Cc="__core-js_shared__",Vc=Oc.exports=iT[Cc]||aT(Cc,{});(Vc.versions||(Vc.versions=[])).push({version:"3.38.0",mode:rT?"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 Cn=h((IC,_c)=>{"use strict";var Bc=ai();_c.exports=function(i,e){return Bc[i]||(Bc[i]=e||{})}});var gr=h((EC,Nc)=>{"use strict";var sT=Tt(),nT=Object;Nc.exports=function(i){return nT(sT(i))}});var Ue=h((xC,Fc)=>{"use strict";var oT=J(),uT=gr(),lT=oT({}.hasOwnProperty);Fc.exports=Object.hasOwn||function(e,t){return lT(uT(e),t)}});var Vn=h((PC,qc)=>{"use strict";var cT=J(),dT=0,pT=Math.random(),hT=cT(1 .toString);qc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+hT(++dT+pT,36)}});var ae=h((kC,Hc)=>{"use strict";var mT=Y(),fT=Cn(),Uc=Ue(),bT=Vn(),gT=An(),ST=Rn(),Sr=mT.Symbol,On=fT("wks"),vT=ST?Sr.for||Sr:Sr&&Sr.withoutSetter||bT;Hc.exports=function(i){return Uc(On,i)||(On[i]=gT&&Uc(Sr,i)?Sr[i]:vT("Symbol."+i)),On[i]}});var Wc=h((wC,Qc)=>{"use strict";var yT=Pe(),jc=ke(),Gc=$n(),TT=ii(),IT=Rc(),ET=ae(),xT=TypeError,PT=ET("toPrimitive");Qc.exports=function(i,e){if(!jc(i)||Gc(i))return i;var t=TT(i,PT),r;if(t){if(e===void 0&&(e="default"),r=yT(t,i,e),!jc(r)||Gc(r))return r;throw new xT("Can't convert object to primitive value")}return e===void 0&&(e="number"),IT(i,e)}});var Bn=h((AC,Yc)=>{"use strict";var kT=Wc(),wT=$n();Yc.exports=function(i){var e=kT(i,"string");return wT(e)?e:e+""}});var Ua=h((RC,Kc)=>{"use strict";var AT=Y(),zc=ke(),_n=AT.document,RT=zc(_n)&&zc(_n.createElement);Kc.exports=function(i){return RT?_n.createElement(i):{}}});var Nn=h(($C,Xc)=>{"use strict";var $T=xe(),LT=ie(),MT=Ua();Xc.exports=!$T&&!LT(function(){return Object.defineProperty(MT("div"),"a",{get:function(){return 7}}).a!==7})});var ed=h(Zc=>{"use strict";var DT=xe(),CT=Pe(),VT=In(),OT=ei(),BT=Ut(),_T=Bn(),NT=Ue(),FT=Nn(),Jc=Object.getOwnPropertyDescriptor;Zc.f=DT?Jc:function(e,t){if(e=BT(e),t=_T(t),FT)try{return Jc(e,t)}catch{}if(NT(e,t))return OT(!CT(VT.f,e,t),e[t])}});var Fn=h((MC,td)=>{"use strict";var qT=ie(),UT=W(),HT=/#|\.prototype\./,si=function(i,e){var t=GT[jT(i)];return t===WT?!0:t===QT?!1:UT(e)?qT(e):!!e},jT=si.normalize=function(i){return String(i).replace(HT,".").toLowerCase()},GT=si.data={},QT=si.NATIVE="N",WT=si.POLYFILL="P";td.exports=si});var vr=h((DC,id)=>{"use strict";var rd=yn(),YT=Je(),zT=Zr(),KT=rd(rd.bind);id.exports=function(i,e){return YT(i),e===void 0?i:zT?KT(i,e):function(){return i.apply(e,arguments)}}});var qn=h((CC,ad)=>{"use strict";var XT=xe(),JT=ie();ad.exports=XT&&JT(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var Ze=h((VC,sd)=>{"use strict";var ZT=ke(),eI=String,tI=TypeError;sd.exports=function(i){if(ZT(i))return i;throw new tI(eI(i)+" is not an object")}});var jt=h(od=>{"use strict";var rI=xe(),iI=Nn(),aI=qn(),Ha=Ze(),nd=Bn(),sI=TypeError,Un=Object.defineProperty,nI=Object.getOwnPropertyDescriptor,Hn="enumerable",jn="configurable",Gn="writable";od.f=rI?aI?function(e,t,r){if(Ha(e),t=nd(t),Ha(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Gn in r&&!r[Gn]){var a=nI(e,t);a&&a[Gn]&&(e[t]=r.value,r={configurable:jn in r?r[jn]:a[jn],enumerable:Hn in r?r[Hn]:a[Hn],writable:!1})}return Un(e,t,r)}:Un:function(e,t,r){if(Ha(e),t=nd(t),Ha(r),iI)try{return Un(e,t,r)}catch{}if("get"in r||"set"in r)throw new sI("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var yr=h((BC,ud)=>{"use strict";var oI=xe(),uI=jt(),lI=ei();ud.exports=oI?function(i,e,t){return uI.f(i,e,lI(1,t))}:function(i,e,t){return i[e]=t,i}});var K=h((_C,cd)=>{"use strict";var ni=Y(),cI=Sn(),dI=yn(),pI=W(),hI=ed().f,mI=Fn(),Tr=br(),fI=vr(),Ir=yr(),ld=Ue();ai();var bI=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 cI(i,this,arguments)};return e.prototype=i.prototype,e};cd.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?ni:a?ni[t]:ni[t]&&ni[t].prototype,o=r?Tr:Tr[t]||Ir(Tr,t,{})[t],u=o.prototype,l,d,c,p,m,f,b,g,S;for(p in e)l=mI(r?p:t+(a?".":"#")+p,i.forced),d=!l&&n&&ld(n,p),f=o[p],d&&(i.dontCallGetSet?(S=hI(n,p),b=S&&S.value):b=n[p]),m=d&&b?b:e[p],!(!l&&!s&&typeof f==typeof m)&&(i.bind&&d?g=fI(m,ni):i.wrap&&d?g=bI(m):s&&pI(m)?g=dI(m):g=m,(i.sham||m&&m.sham||f&&f.sham)&&Ir(g,"sham",!0),Ir(o,p,g),s&&(c=t+"Prototype",ld(Tr,c)||Ir(Tr,c,{}),Ir(Tr[c],p,m),i.real&&u&&(l||!u[p])&&Ir(u,p,m)))}});var pd=h((NC,dd)=>{"use strict";var gI=Math.ceil,SI=Math.floor;dd.exports=Math.trunc||function(e){var t=+e;return(t>0?SI:gI)(t)}});var oi=h((FC,hd)=>{"use strict";var vI=pd();hd.exports=function(i){var e=+i;return e!==e||e===0?0:vI(e)}});var fd=h((qC,md)=>{"use strict";var yI=oi(),TI=Math.max,II=Math.min;md.exports=function(i,e){var t=yI(i);return t<0?TI(t+e,0):II(t,e)}});var Qn=h((UC,bd)=>{"use strict";var EI=oi(),xI=Math.min;bd.exports=function(i){var e=EI(i);return e>0?xI(e,9007199254740991):0}});var Er=h((HC,gd)=>{"use strict";var PI=Qn();gd.exports=function(i){return PI(i.length)}});var Wn=h((jC,vd)=>{"use strict";var kI=Ut(),wI=fd(),AI=Er(),Sd=function(i){return function(e,t,r){var a=kI(e),s=AI(a);if(s===0)return!i&&-1;var n=wI(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}};vd.exports={includes:Sd(!0),indexOf:Sd(!1)}});var ui=h((GC,yd)=>{"use strict";yd.exports=function(){}});var Td=h(()=>{"use strict";var RI=K(),$I=Wn().includes,LI=ie(),MI=ui(),DI=LI(function(){return!Array(1).includes()});RI({target:"Array",proto:!0,forced:DI},{includes:function(e){return $I(this,e,arguments.length>1?arguments[1]:void 0)}});MI("includes")});var It=h((YC,Id)=>{"use strict";var CI=ut();Id.exports=CI});var xd=h((zC,Ed)=>{"use strict";Td();var VI=It();Ed.exports=VI("Array","includes")});var kd=h((KC,Pd)=>{"use strict";var OI=xd();Pd.exports=OI});var He=h((XC,wd)=>{"use strict";var BI=kd();wd.exports=BI});var Qa=h((l0,Vd)=>{"use strict";var GI=Cn(),QI=Vn(),Cd=GI("keys");Vd.exports=function(i){return Cd[i]||(Cd[i]=QI(i))}});var Bd=h((c0,Od)=>{"use strict";var WI=ie();Od.exports=!WI(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Wa=h((d0,Nd)=>{"use strict";var YI=Ue(),zI=W(),KI=gr(),XI=Qa(),JI=Bd(),_d=XI("IE_PROTO"),Kn=Object,ZI=Kn.prototype;Nd.exports=JI?Kn.getPrototypeOf:function(i){var e=KI(i);if(YI(e,_d))return e[_d];var t=e.constructor;return zI(t)&&e instanceof t?t.prototype:e instanceof Kn?ZI:null}});var Ya=h((p0,Fd)=>{"use strict";Fd.exports={}});var Hd=h((h0,Ud)=>{"use strict";var eE=J(),Xn=Ue(),tE=Ut(),rE=Wn().indexOf,iE=Ya(),qd=eE([].push);Ud.exports=function(i,e){var t=tE(i),r=0,a=[],s;for(s in t)!Xn(iE,s)&&Xn(t,s)&&qd(a,s);for(;e.length>r;)Xn(t,s=e[r++])&&(~rE(a,s)||qd(a,s));return a}});var Jn=h((m0,jd)=>{"use strict";jd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Zn=h((f0,Gd)=>{"use strict";var aE=Hd(),sE=Jn();Gd.exports=Object.keys||function(e){return aE(e,sE)}});var eo=h((b0,Kd)=>{"use strict";var Wd=xe(),nE=ie(),Yd=J(),oE=Wa(),uE=Zn(),lE=Ut(),cE=In().f,zd=Yd(cE),dE=Yd([].push),pE=Wd&&nE(function(){var i=Object.create(null);return i[2]=2,!zd(i,2)}),Qd=function(i){return function(e){for(var t=lE(e),r=uE(t),a=pE&&oE(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Wd||(a?u in t:zd(t,u)))&&dE(o,i?[u,t[u]]:t[u]);return o}};Kd.exports={entries:Qd(!0),values:Qd(!1)}});var Xd=h(()=>{"use strict";var hE=K(),mE=eo().entries;hE({target:"Object",stat:!0},{entries:function(e){return mE(e)}})});var Zd=h((v0,Jd)=>{"use strict";Xd();var fE=br();Jd.exports=fE.Object.entries});var tp=h((y0,ep)=>{"use strict";var bE=Zd();ep.exports=bE});var xr=h((T0,rp)=>{"use strict";var gE=tp();rp.exports=gE});var Gt=h((I0,ip)=>{"use strict";ip.exports={}});var np=h((E0,sp)=>{"use strict";var SE=Y(),vE=W(),ap=SE.WeakMap;sp.exports=vE(ap)&&/native code/.test(String(ap))});var ao=h((x0,lp)=>{"use strict";var yE=np(),up=Y(),TE=ke(),IE=yr(),to=Ue(),ro=ai(),EE=Qa(),xE=Ya(),op="Object already initialized",io=up.TypeError,PE=up.WeakMap,za,li,Ka,kE=function(i){return Ka(i)?li(i):za(i,{})},wE=function(i){return function(e){var t;if(!TE(e)||(t=li(e)).type!==i)throw new io("Incompatible receiver, "+i+" required");return t}};yE||ro.state?(je=ro.state||(ro.state=new PE),je.get=je.get,je.has=je.has,je.set=je.set,za=function(i,e){if(je.has(i))throw new io(op);return e.facade=i,je.set(i,e),e},li=function(i){return je.get(i)||{}},Ka=function(i){return je.has(i)}):(Qt=EE("state"),xE[Qt]=!0,za=function(i,e){if(to(i,Qt))throw new io(op);return e.facade=i,IE(i,Qt,e),e},li=function(i){return to(i,Qt)?i[Qt]:{}},Ka=function(i){return to(i,Qt)});var je,Qt;lp.exports={set:za,get:li,has:Ka,enforce:kE,getterFor:wE}});var oo=h((P0,dp)=>{"use strict";var so=xe(),AE=Ue(),cp=Function.prototype,RE=so&&Object.getOwnPropertyDescriptor,no=AE(cp,"name"),$E=no&&function(){}.name==="something",LE=no&&(!so||so&&RE(cp,"name").configurable);dp.exports={EXISTS:no,PROPER:$E,CONFIGURABLE:LE}});var hp=h(pp=>{"use strict";var ME=xe(),DE=qn(),CE=jt(),VE=Ze(),OE=Ut(),BE=Zn();pp.f=ME&&!DE?Object.defineProperties:function(e,t){VE(e);for(var r=OE(t),a=BE(t),s=a.length,n=0,o;s>n;)CE.f(e,o=a[n++],r[o]);return e}});var uo=h((w0,mp)=>{"use strict";var _E=ut();mp.exports=_E("document","documentElement")});var ho=h((A0,Tp)=>{"use strict";var NE=Ze(),FE=hp(),fp=Jn(),qE=Ya(),UE=uo(),HE=Ua(),jE=Qa(),bp=">",gp="<",co="prototype",po="script",vp=jE("IE_PROTO"),lo=function(){},yp=function(i){return gp+po+bp+i+gp+"/"+po+bp},Sp=function(i){i.write(yp("")),i.close();var e=i.parentWindow.Object;return i=null,e},GE=function(){var i=HE("iframe"),e="java"+po+":",t;return i.style.display="none",UE.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(yp("document.F=Object")),t.close(),t.F},Xa,Ja=function(){try{Xa=new ActiveXObject("htmlfile")}catch{}Ja=typeof document<"u"?document.domain&&Xa?Sp(Xa):GE():Sp(Xa);for(var i=fp.length;i--;)delete Ja[co][fp[i]];return Ja()};qE[vp]=!0;Tp.exports=Object.create||function(e,t){var r;return e!==null?(lo[co]=NE(e),r=new lo,lo[co]=null,r[vp]=e):r=Ja(),t===void 0?r:FE.f(r,t)}});var Pr=h((R0,Ip)=>{"use strict";var QE=yr();Ip.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:QE(i,e,t),i}});var go=h(($0,Pp)=>{"use strict";var WE=ie(),YE=W(),zE=ke(),KE=ho(),Ep=Wa(),XE=Pr(),JE=ae(),ZE=qe(),bo=JE("iterator"),xp=!1,lt,mo,fo;[].keys&&(fo=[].keys(),"next"in fo?(mo=Ep(Ep(fo)),mo!==Object.prototype&&(lt=mo)):xp=!0);var ex=!zE(lt)||WE(function(){var i={};return lt[bo].call(i)!==i});ex?lt={}:ZE&&(lt=KE(lt));YE(lt[bo])||XE(lt,bo,function(){return this});Pp.exports={IteratorPrototype:lt,BUGGY_SAFARI_ITERATORS:xp}});var Za=h((L0,wp)=>{"use strict";var tx=ae(),rx=tx("toStringTag"),kp={};kp[rx]="z";wp.exports=String(kp)==="[object z]"});var ci=h((M0,Ap)=>{"use strict";var ix=Za(),ax=W(),es=qt(),sx=ae(),nx=sx("toStringTag"),ox=Object,ux=es(function(){return arguments}())==="Arguments",lx=function(i,e){try{return i[e]}catch{}};Ap.exports=ix?es:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=lx(e=ox(i),nx))=="string"?t:ux?es(e):(r=es(e))==="Object"&&ax(e.callee)?"Arguments":r}});var $p=h((D0,Rp)=>{"use strict";var cx=Za(),dx=ci();Rp.exports=cx?{}.toString:function(){return"[object "+dx(this)+"]"}});var di=h((C0,Mp)=>{"use strict";var px=Za(),hx=jt().f,mx=yr(),fx=Ue(),bx=$p(),gx=ae(),Lp=gx("toStringTag");Mp.exports=function(i,e,t,r){var a=t?i:i&&i.prototype;a&&(fx(a,Lp)||hx(a,Lp,{configurable:!0,value:e}),r&&!px&&mx(a,"toString",bx))}});var Cp=h((V0,Dp)=>{"use strict";var Sx=go().IteratorPrototype,vx=ho(),yx=ei(),Tx=di(),Ix=Gt(),Ex=function(){return this};Dp.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=vx(Sx,{next:yx(+!r,t)}),Tx(i,a,!1,!0),Ix[a]=Ex,i}});var Op=h((O0,Vp)=>{"use strict";var xx=J(),Px=Je();Vp.exports=function(i,e,t){try{return xx(Px(Object.getOwnPropertyDescriptor(i,e)[t]))}catch{}}});var _p=h((B0,Bp)=>{"use strict";var kx=ke();Bp.exports=function(i){return kx(i)||i===null}});var Fp=h((_0,Np)=>{"use strict";var wx=_p(),Ax=String,Rx=TypeError;Np.exports=function(i){if(wx(i))return i;throw new Rx("Can't set "+Ax(i)+" as a prototype")}});var So=h((N0,qp)=>{"use strict";var $x=Op(),Lx=ke(),Mx=Tt(),Dx=Fp();qp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=$x(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch{}return function(a,s){return Mx(a),Dx(s),Lx(a)&&(i?t(a,s):a.__proto__=s),a}}():void 0)});var Jp=h((F0,Xp)=>{"use strict";var Cx=K(),Vx=Pe(),ts=qe(),zp=oo(),Ox=W(),Bx=Cp(),Up=Wa(),Hp=So(),_x=di(),Nx=yr(),vo=Pr(),Fx=ae(),jp=Gt(),Kp=go(),qx=zp.PROPER,Ux=zp.CONFIGURABLE,Gp=Kp.IteratorPrototype,rs=Kp.BUGGY_SAFARI_ITERATORS,pi=Fx("iterator"),Qp="keys",hi="values",Wp="entries",Yp=function(){return this};Xp.exports=function(i,e,t,r,a,s,n){Bx(t,e,r);var o=function(S){if(S===a&&p)return p;if(!rs&&S&&S in d)return d[S];switch(S){case Qp:return function(){return new t(this,S)};case hi:return function(){return new t(this,S)};case Wp:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,d=i.prototype,c=d[pi]||d["@@iterator"]||a&&d[a],p=!rs&&c||o(a),m=e==="Array"&&d.entries||c,f,b,g;if(m&&(f=Up(m.call(new i)),f!==Object.prototype&&f.next&&(!ts&&Up(f)!==Gp&&(Hp?Hp(f,Gp):Ox(f[pi])||vo(f,pi,Yp)),_x(f,u,!0,!0),ts&&(jp[u]=Yp))),qx&&a===hi&&c&&c.name!==hi&&(!ts&&Ux?Nx(d,"name",hi):(l=!0,p=function(){return Vx(c,this)})),a)if(b={values:o(hi),keys:s?p:o(Qp),entries:o(Wp)},n)for(g in b)(rs||l||!(g in d))&&vo(d,g,b[g]);else Cx({target:e,proto:!0,forced:rs||l},b);return(!ts||n)&&d[pi]!==p&&vo(d,pi,p,{name:a}),jp[e]=p,b}});var eh=h((q0,Zp)=>{"use strict";Zp.exports=function(i,e){return{value:i,done:e}}});var To=h((U0,sh)=>{"use strict";var Hx=Ut(),yo=ui(),th=Gt(),ih=ao(),jx=jt().f,Gx=Jp(),is=eh(),Qx=qe(),Wx=xe(),ah="Array Iterator",Yx=ih.set,zx=ih.getterFor(ah);sh.exports=Gx(Array,"Array",function(i,e){Yx(this,{type:ah,target:Hx(i),index:0,kind:e})},function(){var i=zx(this),e=i.target,t=i.index++;if(!e||t>=e.length)return i.target=void 0,is(void 0,!0);switch(i.kind){case"keys":return is(t,!1);case"values":return is(e[t],!1)}return is([t,e[t]],!1)},"values");var rh=th.Arguments=th.Array;yo("keys");yo("values");yo("entries");if(!Qx&&Wx&&rh.name!=="values")try{jx(rh,"name",{value:"values"})}catch{}});var oh=h((H0,nh)=>{"use strict";var Kx=ae(),Xx=Gt(),Jx=Kx("iterator"),Zx=Array.prototype;nh.exports=function(i){return i!==void 0&&(Xx.Array===i||Zx[Jx]===i)}});var Io=h((j0,lh)=>{"use strict";var eP=ci(),uh=ii(),tP=fr(),rP=Gt(),iP=ae(),aP=iP("iterator");lh.exports=function(i){if(!tP(i))return uh(i,aP)||uh(i,"@@iterator")||rP[eP(i)]}});var dh=h((G0,ch)=>{"use strict";var sP=Pe(),nP=Je(),oP=Ze(),uP=ri(),lP=Io(),cP=TypeError;ch.exports=function(i,e){var t=arguments.length<2?lP(i):e;if(nP(t))return oP(sP(t,i));throw new cP(uP(i)+" is not iterable")}});var mh=h((Q0,hh)=>{"use strict";var dP=Pe(),ph=Ze(),pP=ii();hh.exports=function(i,e,t){var r,a;ph(i);try{if(r=pP(i,"return"),!r){if(e==="throw")throw t;return t}r=dP(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return ph(r),t}});var ss=h((W0,Sh)=>{"use strict";var hP=vr(),mP=Pe(),fP=Ze(),bP=ri(),gP=oh(),SP=Er(),fh=ti(),vP=dh(),yP=Io(),bh=mh(),TP=TypeError,as=function(i,e){this.stopped=i,this.result=e},gh=as.prototype;Sh.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=hP(e,r),l,d,c,p,m,f,b,g=function(k){return l&&bh(l,"normal",k),new as(!0,k)},S=function(k){return a?(fP(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=yP(i),!d)throw new TP(bP(i)+" is not iterable");if(gP(d)){for(c=0,p=SP(i);p>c;c++)if(m=S(i[c]),m&&fh(gh,m))return m;return new as(!1)}l=vP(i,d)}for(f=s?i.next:l.next;!(b=mP(f,l)).done;){try{m=S(b.value)}catch(k){bh(l,"throw",k)}if(typeof m=="object"&&m&&fh(gh,m))return m}return new as(!1)}});var yh=h((Y0,vh)=>{"use strict";var IP=xe(),EP=jt(),xP=ei();vh.exports=function(i,e,t){IP?EP.f(i,e,xP(0,t)):i[e]=t}});var Th=h(()=>{"use strict";var PP=K(),kP=ss(),wP=yh();PP({target:"Object",stat:!0},{fromEntries:function(e){var t={};return kP(e,function(r,a){wP(t,r,a)},{AS_ENTRIES:!0}),t}})});var Eh=h((X0,Ih)=>{"use strict";To();Th();var AP=br();Ih.exports=AP.Object.fromEntries});var Ph=h((J0,xh)=>{"use strict";xh.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 wh=h(()=>{"use strict";To();var RP=Ph(),$P=Y(),LP=di(),kh=Gt();for(ns in RP)LP($P[ns],ns),kh[ns]=kh.Array;var ns});var Rh=h((tV,Ah)=>{"use strict";var MP=Eh();wh();Ah.exports=MP});var Eo=h((rV,$h)=>{"use strict";var DP=Rh();$h.exports=DP});var Lh=h(()=>{"use strict"});var xo=h((sV,Mh)=>{"use strict";var mi=Y(),CP=Ht(),VP=qt(),os=function(i){return CP.slice(0,i.length)===i};Mh.exports=function(){return os("Bun/")?"BUN":os("Cloudflare-Workers")?"CLOUDFLARE":os("Deno/")?"DENO":os("Node.js/")?"NODE":mi.Bun&&typeof Bun.version=="string"?"BUN":mi.Deno&&typeof Deno.version=="object"?"DENO":VP(mi.process)==="process"?"NODE":mi.window&&mi.document?"BROWSER":"REST"}()});var us=h((nV,Dh)=>{"use strict";var OP=xo();Dh.exports=OP==="NODE"});var Vh=h((oV,Ch)=>{"use strict";var BP=jt();Ch.exports=function(i,e,t){return BP.f(i,e,t)}});var _h=h((uV,Bh)=>{"use strict";var _P=ut(),NP=Vh(),FP=ae(),qP=xe(),Oh=FP("species");Bh.exports=function(i){var e=_P(i);qP&&e&&!e[Oh]&&NP(e,Oh,{configurable:!0,get:function(){return this}})}});var Fh=h((lV,Nh)=>{"use strict";var UP=ti(),HP=TypeError;Nh.exports=function(i,e){if(UP(e,i))return i;throw new HP("Incorrect invocation")}});var ko=h((cV,qh)=>{"use strict";var jP=J(),GP=W(),Po=ai(),QP=jP(Function.toString);GP(Po.inspectSource)||(Po.inspectSource=function(i){return QP(i)});qh.exports=Po.inspectSource});var Ao=h((dV,Qh)=>{"use strict";var WP=J(),YP=ie(),Uh=W(),zP=ci(),KP=ut(),XP=ko(),Hh=function(){},jh=KP("Reflect","construct"),wo=/^\s*(?:class|function)\b/,JP=WP(wo.exec),ZP=!wo.test(Hh),fi=function(e){if(!Uh(e))return!1;try{return jh(Hh,[],e),!0}catch{return!1}},Gh=function(e){if(!Uh(e))return!1;switch(zP(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return ZP||!!JP(wo,XP(e))}catch{return!0}};Gh.sham=!0;Qh.exports=!jh||YP(function(){var i;return fi(fi.call)||!fi(Object)||!fi(function(){i=!0})||i})?Gh:fi});var Yh=h((pV,Wh)=>{"use strict";var ek=Ao(),tk=ri(),rk=TypeError;Wh.exports=function(i){if(ek(i))return i;throw new rk(tk(i)+" is not a constructor")}});var Ro=h((hV,Kh)=>{"use strict";var zh=Ze(),ik=Yh(),ak=fr(),sk=ae(),nk=sk("species");Kh.exports=function(i,e){var t=zh(i).constructor,r;return t===void 0||ak(r=zh(t)[nk])?e:ik(r)}});var Jh=h((mV,Xh)=>{"use strict";var ok=J();Xh.exports=ok([].slice)});var em=h((fV,Zh)=>{"use strict";var uk=TypeError;Zh.exports=function(i,e){if(i<e)throw new uk("Not enough arguments");return i}});var $o=h((bV,tm)=>{"use strict";var lk=Ht();tm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(lk)});var No=h((gV,cm)=>{"use strict";var we=Y(),ck=Sn(),dk=vr(),rm=W(),pk=Ue(),lm=ie(),im=uo(),hk=Jh(),am=Ua(),mk=em(),fk=$o(),bk=us(),Oo=we.setImmediate,Bo=we.clearImmediate,gk=we.process,Lo=we.Dispatch,Sk=we.Function,sm=we.MessageChannel,vk=we.String,Mo=0,bi={},nm="onreadystatechange",gi,Wt,Do,Co;lm(function(){gi=we.location});var _o=function(i){if(pk(bi,i)){var e=bi[i];delete bi[i],e()}},Vo=function(i){return function(){_o(i)}},om=function(i){_o(i.data)},um=function(i){we.postMessage(vk(i),gi.protocol+"//"+gi.host)};(!Oo||!Bo)&&(Oo=function(e){mk(arguments.length,1);var t=rm(e)?e:Sk(e),r=hk(arguments,1);return bi[++Mo]=function(){ck(t,void 0,r)},Wt(Mo),Mo},Bo=function(e){delete bi[e]},bk?Wt=function(i){gk.nextTick(Vo(i))}:Lo&&Lo.now?Wt=function(i){Lo.now(Vo(i))}:sm&&!fk?(Do=new sm,Co=Do.port2,Do.port1.onmessage=om,Wt=dk(Co.postMessage,Co)):we.addEventListener&&rm(we.postMessage)&&!we.importScripts&&gi&&gi.protocol!=="file:"&&!lm(um)?(Wt=um,we.addEventListener("message",om,!1)):nm in am("script")?Wt=function(i){im.appendChild(am("script"))[nm]=function(){im.removeChild(this),_o(i)}}:Wt=function(i){setTimeout(Vo(i),0)});cm.exports={set:Oo,clear:Bo}});var hm=h((SV,pm)=>{"use strict";var dm=Y(),yk=xe(),Tk=Object.getOwnPropertyDescriptor;pm.exports=function(i){if(!yk)return dm[i];var e=Tk(dm,i);return e&&e.value}});var Fo=h((vV,fm)=>{"use strict";var mm=function(){this.head=null,this.tail=null};mm.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}}};fm.exports=mm});var gm=h((yV,bm)=>{"use strict";var Ik=Ht();bm.exports=/ipad|iphone|ipod/i.test(Ik)&&typeof Pebble<"u"});var vm=h((TV,Sm)=>{"use strict";var Ek=Ht();Sm.exports=/web0s(?!.*chrome)/i.test(Ek)});var km=h((IV,Pm)=>{"use strict";var wr=Y(),xk=hm(),ym=vr(),qo=No().set,Pk=Fo(),kk=$o(),wk=gm(),Ak=vm(),Uo=us(),Tm=wr.MutationObserver||wr.WebKitMutationObserver,Im=wr.document,Em=wr.process,ls=wr.Promise,Go=xk("queueMicrotask"),kr,Ho,jo,cs,xm;Go||(Si=new Pk,vi=function(){var i,e;for(Uo&&(i=Em.domain)&&i.exit();e=Si.get();)try{e()}catch(t){throw Si.head&&kr(),t}i&&i.enter()},!kk&&!Uo&&!Ak&&Tm&&Im?(Ho=!0,jo=Im.createTextNode(""),new Tm(vi).observe(jo,{characterData:!0}),kr=function(){jo.data=Ho=!Ho}):!wk&&ls&&ls.resolve?(cs=ls.resolve(void 0),cs.constructor=ls,xm=ym(cs.then,cs),kr=function(){xm(vi)}):Uo?kr=function(){Em.nextTick(vi)}:(qo=ym(qo,wr),kr=function(){qo(vi)}),Go=function(i){Si.head||kr(),Si.add(i)});var Si,vi;Pm.exports=Go});var Am=h((EV,wm)=>{"use strict";wm.exports=function(i,e){try{arguments.length===1?console.error(i):console.error(i,e)}catch{}}});var ds=h((xV,Rm)=>{"use strict";Rm.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Yt=h((PV,$m)=>{"use strict";var Rk=Y();$m.exports=Rk.Promise});var Ar=h((kV,Cm)=>{"use strict";var $k=Y(),yi=Yt(),Lk=W(),Mk=Fn(),Dk=ko(),Ck=ae(),Lm=xo(),Vk=qe(),Qo=wn(),Mm=yi&&yi.prototype,Ok=Ck("species"),Wo=!1,Dm=Lk($k.PromiseRejectionEvent),Bk=Mk("Promise",function(){var i=Dk(yi),e=i!==String(yi);if(!e&&Qo===66||Vk&&!(Mm.catch&&Mm.finally))return!0;if(!Qo||Qo<51||!/native code/.test(i)){var t=new yi(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Ok]=r,Wo=t.then(function(){})instanceof r,!Wo)return!0}return!e&&(Lm==="BROWSER"||Lm==="DENO")&&!Dm});Cm.exports={CONSTRUCTOR:Bk,REJECTION_EVENT:Dm,SUBCLASSING:Wo}});var Rr=h((wV,Om)=>{"use strict";var Vm=Je(),_k=TypeError,Nk=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw new _k("Bad Promise constructor");e=r,t=a}),this.resolve=Vm(e),this.reject=Vm(t)};Om.exports.f=function(i){return new Nk(i)}});var tf=h(()=>{"use strict";var Fk=K(),qk=qe(),fs=us(),Et=Y(),Dr=Pe(),Bm=Pr(),_m=So(),Uk=di(),Hk=_h(),jk=Je(),ms=W(),Gk=ke(),Qk=Fh(),Wk=Ro(),Hm=No().set,Jo=km(),Yk=Am(),zk=ds(),Kk=Fo(),jm=ao(),bs=Yt(),Zo=Ar(),Gm=Rr(),gs="Promise",Qm=Zo.CONSTRUCTOR,Xk=Zo.REJECTION_EVENT,Jk=Zo.SUBCLASSING,Yo=jm.getterFor(gs),Zk=jm.set,$r=bs&&bs.prototype,zt=bs,ps=$r,Wm=Et.TypeError,zo=Et.document,eu=Et.process,Ko=Gm.f,ew=Ko,tw=!!(zo&&zo.createEvent&&Et.dispatchEvent),Ym="unhandledrejection",rw="rejectionhandled",Nm=0,zm=1,iw=2,tu=1,Km=2,hs,Fm,aw,qm,Xm=function(i){var e;return Gk(i)&&ms(e=i.then)?e:!1},Jm=function(i,e){var t=e.value,r=e.state===zm,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,d;try{a?(r||(e.rejection===Km&&nw(e),e.rejection=tu),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),d=!0)),u===i.promise?n(new Wm("Promise-chain cycle")):(l=Xm(u))?Dr(l,u,s,n):s(u)):n(t)}catch(c){o&&!d&&o.exit(),n(c)}},Zm=function(i,e){i.notified||(i.notified=!0,Jo(function(){for(var t=i.reactions,r;r=t.get();)Jm(r,i);i.notified=!1,e&&!i.rejection&&sw(i)}))},ef=function(i,e,t){var r,a;tw?(r=zo.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Et.dispatchEvent(r)):r={promise:e,reason:t},!Xk&&(a=Et["on"+i])?a(r):i===Ym&&Yk("Unhandled promise rejection",t)},sw=function(i){Dr(Hm,Et,function(){var e=i.facade,t=i.value,r=Um(i),a;if(r&&(a=zk(function(){fs?eu.emit("unhandledRejection",t,e):ef(Ym,e,t)}),i.rejection=fs||Um(i)?Km:tu,a.error))throw a.value})},Um=function(i){return i.rejection!==tu&&!i.parent},nw=function(i){Dr(Hm,Et,function(){var e=i.facade;fs?eu.emit("rejectionHandled",e):ef(rw,e,i.value)})},Lr=function(i,e,t){return function(r){i(e,r,t)}},Mr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=iw,Zm(i,!0))},Xo=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw new Wm("Promise can't be resolved itself");var r=Xm(e);r?Jo(function(){var a={done:!1};try{Dr(r,e,Lr(Xo,a,i),Lr(Mr,a,i))}catch(s){Mr(a,s,i)}}):(i.value=e,i.state=zm,Zm(i,!1))}catch(a){Mr({done:!1},a,i)}}};if(Qm&&(zt=function(e){Qk(this,ps),jk(e),Dr(hs,this);var t=Yo(this);try{e(Lr(Xo,t),Lr(Mr,t))}catch(r){Mr(t,r)}},ps=zt.prototype,hs=function(e){Zk(this,{type:gs,done:!1,notified:!1,parent:!1,reactions:new Kk,rejection:!1,state:Nm,value:void 0})},hs.prototype=Bm(ps,"then",function(e,t){var r=Yo(this),a=Ko(Wk(this,zt));return r.parent=!0,a.ok=ms(e)?e:!0,a.fail=ms(t)&&t,a.domain=fs?eu.domain:void 0,r.state===Nm?r.reactions.add(a):Jo(function(){Jm(a,r)}),a.promise}),Fm=function(){var i=new hs,e=Yo(i);this.promise=i,this.resolve=Lr(Xo,e),this.reject=Lr(Mr,e)},Gm.f=Ko=function(i){return i===zt||i===aw?new Fm(i):ew(i)},!qk&&ms(bs)&&$r!==Object.prototype)){qm=$r.then,Jk||Bm($r,"then",function(e,t){var r=this;return new zt(function(a,s){Dr(qm,r,a,s)}).then(e,t)},{unsafe:!0});try{delete $r.constructor}catch{}_m&&_m($r,ps)}Fk({global:!0,constructor:!0,wrap:!0,forced:Qm},{Promise:zt});Uk(zt,gs,!1,!0);Hk(gs)});var of=h(($V,nf)=>{"use strict";var ow=ae(),af=ow("iterator"),sf=!1;try{rf=0,ru={next:function(){return{done:!!rf++}},return:function(){sf=!0}},ru[af]=function(){return this},Array.from(ru,function(){throw 2})}catch{}var rf,ru;nf.exports=function(i,e){try{if(!e&&!sf)return!1}catch{return!1}var t=!1;try{var r={};r[af]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch{}return t}});var iu=h((LV,uf)=>{"use strict";var uw=Yt(),lw=of(),cw=Ar().CONSTRUCTOR;uf.exports=cw||!lw(function(i){uw.all(i).then(void 0,function(){})})});var lf=h(()=>{"use strict";var dw=K(),pw=Pe(),hw=Je(),mw=Rr(),fw=ds(),bw=ss(),gw=iu();dw({target:"Promise",stat:!0,forced:gw},{all:function(e){var t=this,r=mw.f(t),a=r.resolve,s=r.reject,n=fw(function(){var o=hw(t.resolve),u=[],l=0,d=1;bw(e,function(c){var p=l++,m=!1;d++,pw(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 df=h(()=>{"use strict";var Sw=K(),vw=qe(),yw=Ar().CONSTRUCTOR,su=Yt(),Tw=ut(),Iw=W(),Ew=Pr(),cf=su&&su.prototype;Sw({target:"Promise",proto:!0,forced:yw,real:!0},{catch:function(i){return this.then(void 0,i)}});!vw&&Iw(su)&&(au=Tw("Promise").prototype.catch,cf.catch!==au&&Ew(cf,"catch",au,{unsafe:!0}));var au});var pf=h(()=>{"use strict";var xw=K(),Pw=Pe(),kw=Je(),ww=Rr(),Aw=ds(),Rw=ss(),$w=iu();xw({target:"Promise",stat:!0,forced:$w},{race:function(e){var t=this,r=ww.f(t),a=r.reject,s=Aw(function(){var n=kw(t.resolve);Rw(e,function(o){Pw(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var hf=h(()=>{"use strict";var Lw=K(),Mw=Rr(),Dw=Ar().CONSTRUCTOR;Lw({target:"Promise",stat:!0,forced:Dw},{reject:function(e){var t=Mw.f(this),r=t.reject;return r(e),t.promise}})});var nu=h((FV,mf)=>{"use strict";var Cw=Ze(),Vw=ke(),Ow=Rr();mf.exports=function(i,e){if(Cw(i),Vw(e)&&e.constructor===i)return e;var t=Ow.f(i),r=t.resolve;return r(e),t.promise}});var gf=h(()=>{"use strict";var Bw=K(),_w=ut(),ff=qe(),Nw=Yt(),bf=Ar().CONSTRUCTOR,Fw=nu(),qw=_w("Promise"),Uw=ff&&!bf;Bw({target:"Promise",stat:!0,forced:ff||bf},{resolve:function(e){return Fw(Uw&&this===qw?Nw:this,e)}})});var Sf=h(()=>{"use strict";tf();lf();df();pf();hf();gf()});var If=h(()=>{"use strict";var Hw=K(),jw=qe(),Ss=Yt(),Gw=ie(),yf=ut(),Tf=W(),Qw=Ro(),vf=nu(),Ww=Pr(),uu=Ss&&Ss.prototype,Yw=!!Ss&&Gw(function(){uu.finally.call({then:function(){}},function(){})});Hw({target:"Promise",proto:!0,real:!0,forced:Yw},{finally:function(i){var e=Qw(this,yf("Promise")),t=Tf(i);return this.then(t?function(r){return vf(e,i()).then(function(){return r})}:i,t?function(r){return vf(e,i()).then(function(){throw r})}:i)}});!jw&&Tf(Ss)&&(ou=yf("Promise").prototype.finally,uu.finally!==ou&&Ww(uu,"finally",ou,{unsafe:!0}));var ou});var xf=h((WV,Ef)=>{"use strict";Lh();Sf();If();var zw=It();Ef.exports=zw("Promise","finally")});var kf=h((YV,Pf)=>{"use strict";var Kw=xf();Pf.exports=Kw});var vs=h((zV,wf)=>{"use strict";var Xw=kf();wf.exports=Xw});var Ff=h(()=>{"use strict";var dA=K(),pA=eo().values;dA({target:"Object",stat:!0},{values:function(e){return pA(e)}})});var Uf=h((DO,qf)=>{"use strict";Ff();var hA=br();qf.exports=hA.Object.values});var jf=h((CO,Hf)=>{"use strict";var mA=Uf();Hf.exports=mA});var Vr=h((VO,Gf)=>{"use strict";var fA=jf();Gf.exports=fA});var ab=h(()=>{"use strict";var LA=K(),MA=gr(),DA=Er(),CA=oi(),VA=ui();LA({target:"Array",proto:!0},{at:function(e){var t=MA(this),r=DA(t),a=CA(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});VA("at")});var nb=h((lB,sb)=>{"use strict";ab();var OA=It();sb.exports=OA("Array","at")});var ub=h((cB,ob)=>{"use strict";var BA=nb();ob.exports=BA});var Br=h((dB,lb)=>{"use strict";var _A=ub();lb.exports=_A});var Lu=h((B_,Nb)=>{"use strict";var vR=qt();Nb.exports=Array.isArray||function(e){return vR(e)==="Array"}});var qb=h((__,Fb)=>{"use strict";var yR=TypeError,TR=9007199254740991;Fb.exports=function(i){if(i>TR)throw yR("Maximum allowed index exceeded");return i}});var jb=h((N_,Hb)=>{"use strict";var IR=Lu(),ER=Er(),xR=qb(),PR=vr(),Ub=function(i,e,t,r,a,s,n,o){for(var u=a,l=0,d=n?PR(n,o):!1,c,p;l<r;)l in t&&(c=d?d(t[l],l,e):t[l],s>0&&IR(c)?(p=ER(c),u=Ub(i,e,c,p,u,s-1)-1):(xR(u+1),i[u]=c),u++),l++;return u};Hb.exports=Ub});var Yb=h((F_,Wb)=>{"use strict";var Gb=Lu(),kR=Ao(),wR=ke(),AR=ae(),RR=AR("species"),Qb=Array;Wb.exports=function(i){var e;return Gb(i)&&(e=i.constructor,kR(e)&&(e===Qb||Gb(e.prototype))?e=void 0:wR(e)&&(e=e[RR],e===null&&(e=void 0))),e===void 0?Qb:e}});var Kb=h((q_,zb)=>{"use strict";var $R=Yb();zb.exports=function(i,e){return new($R(i))(e===0?0:e)}});var Xb=h(()=>{"use strict";var LR=K(),MR=jb(),DR=Je(),CR=gr(),VR=Er(),OR=Kb();LR({target:"Array",proto:!0},{flatMap:function(e){var t=CR(this),r=VR(t),a;return DR(e),a=OR(t,0),a.length=MR(a,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),a}})});var Jb=h(()=>{"use strict";var BR=ui();BR("flatMap")});var eg=h((Q_,Zb)=>{"use strict";Xb();Jb();var _R=It();Zb.exports=_R("Array","flatMap")});var rg=h((W_,tg)=>{"use strict";var NR=eg();tg.exports=NR});var Mu=h((Y_,ig)=>{"use strict";var FR=rg();ig.exports=FR});var Vi=h((aN,hg)=>{"use strict";var YR=ci(),zR=String;hg.exports=function(i){if(YR(i)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return zR(i)}});var Cu=h((sN,mg)=>{"use strict";mg.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 gg=h((nN,bg)=>{"use strict";var KR=J(),XR=Tt(),JR=Vi(),Ou=Cu(),fg=KR("".replace),ZR=RegExp("^["+Ou+"]+"),e$=RegExp("(^|[^"+Ou+"])["+Ou+"]+$"),Vu=function(i){return function(e){var t=JR(XR(e));return i&1&&(t=fg(t,ZR,"")),i&2&&(t=fg(t,e$,"$1")),t}};bg.exports={start:Vu(1),end:Vu(2),trim:Vu(3)}});var Tg=h((oN,yg)=>{"use strict";var t$=oo().PROPER,r$=ie(),Sg=Cu(),vg="\u200B\x85\u180E";yg.exports=function(i){return r$(function(){return!!Sg[i]()||vg[i]()!==vg||t$&&Sg[i].name!==i})}});var Bu=h((uN,Ig)=>{"use strict";var i$=gg().start,a$=Tg();Ig.exports=a$("trimStart")?function(){return i$(this)}:"".trimStart});var xg=h(()=>{"use strict";var s$=K(),Eg=Bu();s$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Eg},{trimLeft:Eg})});var kg=h(()=>{"use strict";xg();var n$=K(),Pg=Bu();n$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Pg},{trimStart:Pg})});var Ag=h((hN,wg)=>{"use strict";kg();var o$=It();wg.exports=o$("String","trimLeft")});var $g=h((mN,Rg)=>{"use strict";var u$=Ag();Rg.exports=u$});var Mg=h((fN,Lg)=>{"use strict";var l$=$g();Lg.exports=l$});var Yg=h(()=>{"use strict"});var zg=h(()=>{"use strict"});var Xg=h((Nq,Kg)=>{"use strict";var M$=ke(),D$=qt(),C$=ae(),V$=C$("match");Kg.exports=function(i){var e;return M$(i)&&((e=i[V$])!==void 0?!!e:D$(i)==="RegExp")}});var Zg=h((Fq,Jg)=>{"use strict";var O$=Ze();Jg.exports=function(){var i=O$(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 rS=h((qq,tS)=>{"use strict";var B$=Pe(),_$=Ue(),N$=ti(),F$=Zg(),eS=RegExp.prototype;tS.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in eS)&&!_$(i,"flags")&&N$(eS,i)?B$(F$,i):e}});var aS=h((Uq,iS)=>{"use strict";var Qu=J(),q$=gr(),U$=Math.floor,ju=Qu("".charAt),H$=Qu("".replace),Gu=Qu("".slice),j$=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,G$=/\$([$&'`]|\d{1,2})/g;iS.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=G$;return a!==void 0&&(a=q$(a),u=j$),H$(s,u,function(l,d){var c;switch(ju(d,0)){case"$":return"$";case"&":return i;case"`":return Gu(e,0,t);case"'":return Gu(e,n);case"<":c=a[Gu(d,1,-1)];break;default:var p=+d;if(p===0)return l;if(p>o){var m=U$(p/10);return m===0?l:m<=o?r[m-1]===void 0?ju(d,1):r[m-1]+ju(d,1):l}c=r[p-1]}return c===void 0?"":c})}});var oS=h(()=>{"use strict";var Q$=K(),W$=Pe(),Yu=J(),sS=Tt(),Y$=W(),z$=fr(),K$=Xg(),Hr=Vi(),X$=ii(),J$=rS(),Z$=aS(),eL=ae(),tL=qe(),rL=eL("replace"),iL=TypeError,Wu=Yu("".indexOf),aL=Yu("".replace),nS=Yu("".slice),sL=Math.max;Q$({target:"String",proto:!0},{replaceAll:function(e,t){var r=sS(this),a,s,n,o,u,l,d,c,p,m,f=0,b="";if(!z$(e)){if(a=K$(e),a&&(s=Hr(sS(J$(e))),!~Wu(s,"g")))throw new iL("`.replaceAll` does not allow non-global regexes");if(n=X$(e,rL),n)return W$(n,e,r,t);if(tL&&a)return aL(Hr(r),e,t)}for(o=Hr(r),u=Hr(e),l=Y$(t),l||(t=Hr(t)),d=u.length,c=sL(1,d),p=Wu(o,u);p!==-1;)m=l?Hr(t(u,p,o)):Z$(u,o,p,[],void 0,t),b+=nS(o,f,p)+m,f=p+d,p=p+c>o.length?-1:Wu(o,u,p+c);return f<o.length&&(b+=nS(o,f)),b}})});var lS=h((Gq,uS)=>{"use strict";Yg();zg();oS();var nL=It();uS.exports=nL("String","replaceAll")});var dS=h((Qq,cS)=>{"use strict";var oL=lS();cS.exports=oL});var hS=h((Wq,pS)=>{"use strict";var uL=dS();pS.exports=uL});var fS=h((Yq,mS)=>{"use strict";var lL=oi(),cL=Vi(),dL=Tt(),pL=RangeError;mS.exports=function(e){var t=cL(dL(this)),r="",a=lL(e);if(a<0||a===1/0)throw new pL("Wrong number of repetitions");for(;a>0;(a>>>=1)&&(t+=t))a&1&&(r+=t);return r}});var yS=h((zq,vS)=>{"use strict";var SS=J(),hL=Qn(),bS=Vi(),mL=fS(),fL=Tt(),bL=SS(mL),gL=SS("".slice),SL=Math.ceil,gS=function(i){return function(e,t,r){var a=bS(fL(e)),s=hL(t),n=a.length,o=r===void 0?" ":bS(r),u,l;return s<=n||o===""?a:(u=s-n,l=bL(o,SL(u/o.length)),l.length>u&&(l=gL(l,0,u)),i?a+l:l+a)}};vS.exports={start:gS(!1),end:gS(!0)}});var IS=h((Kq,TS)=>{"use strict";var vL=Ht();TS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(vL)});var ES=h(()=>{"use strict";var yL=K(),TL=yS().start,IL=IS();yL({target:"String",proto:!0,forced:IL},{padStart:function(e){return TL(this,e,arguments.length>1?arguments[1]:void 0)}})});var PS=h((Zq,xS)=>{"use strict";ES();var EL=It();xS.exports=EL("String","padStart")});var wS=h((eU,kS)=>{"use strict";var xL=PS();kS.exports=xL});var RS=h((tU,AS)=>{"use strict";var PL=wS();AS.exports=PL});var Vl="2.0.123-dev.d53feee8.0";var pe=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(pe||{}),yt=(P=>(P.MPEG="MPEG",P.DASH="DASH",P.DASH_SEP="DASH_SEP",P.DASH_SEP_VK="DASH_SEP",P.DASH_WEBM="DASH_WEBM",P.DASH_WEBM_AV1="DASH_WEBM_AV1",P.DASH_STREAMS="DASH_STREAMS",P.DASH_WEBM_VK="DASH_WEBM",P.DASH_ONDEMAND="DASH_ONDEMAND",P.DASH_ONDEMAND_VK="DASH_ONDEMAND",P.DASH_LIVE="DASH_LIVE",P.DASH_LIVE_CMAF="DASH_LIVE_CMAF",P.DASH_LIVE_WEBM="DASH_LIVE_WEBM",P.HLS="HLS",P.HLS_ONDEMAND="HLS_ONDEMAND",P.HLS_JS="HLS",P.HLS_LIVE="HLS_LIVE",P.HLS_LIVE_CMAF="HLS_LIVE_CMAF",P.WEB_RTC_LIVE="WEB_RTC_LIVE",P))(yt||{});var Na=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(Na||{}),fn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(fn||{});var bn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(bn||{});var ny=M(He(),1);import{assertNever as Dd,assertNonNullable as _I,isNonNullable as ja,ValueSubject as Yn,Subject as NI,Subscription as FI,merge as qI,observableFrom as UI,fromEvent as Rd,map as $d,tap as Ld,filterChanged as HI,isNullable as zn,ErrorCategory as Md}from"@vkontakte/videoplayer-shared";var Ad=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 Ga=class{constructor(e){this.connection$=new Yn(void 0);this.castState$=new Yn("NOT_AVAILABLE");this.errorEvent$=new NI;this.realCastState$=new Yn("NOT_AVAILABLE");this.subscription=new FI;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=ja(window.chrome?.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&!this.isDestroyed&&this.initializeCastApi()},a||Ad("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Md.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(){ja(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();zn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();zn(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(Rd(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 Dd(a.sessionState)}})).add(qI(Rd(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ld(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),$d(a=>a.castState)),UI([r.getCastState()])).pipe(HI(),$d(jI),Ld(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{let s=a==="CONNECTED",n=ja(this.connection$.getValue());if(s&&!n){let o=r.getCurrentSession();_I(o);let u=o.getCastDevice(),l=o.getMediaSession()?.media?.contentId;(zn(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"?ja(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:Md.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},jI=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 Dd(i)}};var kl=M(He(),1),Fv=M(xr(),1),qv=M(Eo(),1);var Bf=M(vs(),1);import{assertNever as Af}from"@vkontakte/videoplayer-shared";var se=(i,e=0,t=0)=>{switch(t){case 0:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return i;let r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Af(t)}return i},ys=(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:Af(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as Jw,Subject as Ts,merge as Rf}from"@vkontakte/videoplayer-shared";var $=class{constructor(e){this.transitionStarted$=new Ts;this.transitionEnded$=new Ts;this.transitionUpdated$=new Ts;this.forceChanged$=new Ts;this.stateChangeStarted$=Rf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Rf(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||Jw(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 Zw}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 Zw(i)}};import{assertNever as Cr,assertNonNullable as Kt,debounce as Lf,ErrorCategory as Mf,fromEvent as Xt,isNonNullable as Df,map as Cf,merge as Vf,observableFrom as eA,Subject as tA,Subscription as lu,timeout as rA,getHighestQuality as iA}from"@vkontakte/videoplayer-shared";var aA=5,sA=5,nA=500,Of=7e3,Ti=class{constructor(e){this.subscription=new lu;this.loadMediaTimeoutSubscription=new lu;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:Cr(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:Cr(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:Cr(e)}break}default:Cr(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 lu;this.subscription.add(e),this.subscription.add(Vf(this.videoState.stateChangeStarted$.pipe(Cf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Cf(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 tA;e.add(a.pipe(Lf(nA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>aA)&&a.next(o),s=o})),e.add(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<sA&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Cr(n)}}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Xt(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Vf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,eA(["init"])).pipe(Lf(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="paused"||e==="playing")&&(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState();(this.videoState.getTransition()?.to==="playing"||e==="paused")&&(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.params.desiredState.playbackState.getTransition()?.to==="ready"&&I(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){let t=this.params.output.volume$.getValue(),r={volume:e.volume??t.volume,muted:e.muted??t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){let t=this.params.source,r,a,s;switch(e){case"MPEG":{let l=t[e];Kt(l);let d=iA(Object.keys(l));Kt(d);let c=l[d];Kt(c),r=c,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];Kt(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];Kt(l),r=l.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];Kt(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];Kt(l),r=se(l.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let l="Unsupported format for Chromecast",d=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Mf.VIDEO_PIPELINE,message:l,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Cr(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 Df(o)&&(n.metadata.title=o),Df(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(rA(Of).subscribe(()=>s(`timeout(${Of})`)))});(0,Bf.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:Mf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Ru=M(He(),1);import{clearVideoElement as Nf}from"@vkontakte/videoplayer-shared";import{clearVideoElement as oA}from"@vkontakte/videoplayer-shared";var _f=i=>{try{i.pause(),i.playbackRate=0,oA(i),i.remove()}catch(e){console.error(e)}};import{fromEvent as uA,Subscription as lA}from"@vkontakte/videoplayer-shared";var cu=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)}},du=window.WeakMap?new WeakMap:new cu,pu=window.WeakMap?new WeakMap:new Map,cA=(i,e=20)=>{let t=0;return uA(i,"ratechange").subscribe(r=>{t++,t>=e&&(i.currentTime=i.currentTime,t=0)})},he=(i,{audioVideoSyncRate:e})=>{let t=i.querySelector("video"),r=!!t;t?Nf(t):(t=document.createElement("video"),i.appendChild(t)),du.set(t,r);let a=new lA;return a.add(cA(t,e)),pu.set(t,a),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},me=i=>{pu.get(i)?.unsubscribe(),pu.delete(i);let t=du.get(i);du.delete(i),t?Nf(i):_f(i)};var mu=M(Vr(),1);import{assertNonNullable as Ii,isNonNullable as tt,isNullable as SA,fromEvent as Or,merge as Qf,observableFrom as Wf,filterChanged as Yf,map as Ei,Subject as zf,Subscription as vA,ValueSubject as yA,ErrorCategory as TA}from"@vkontakte/videoplayer-shared";import{isNonNullable as hu,isNullable as bA,Subscription as gA}from"@vkontakte/videoplayer-shared";var Is=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=bA(a),l=new gA;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},et=(i,e,t)=>Is(e,()=>i.loop,r=>{hu(r)&&(i.loop=r)},{onError:t}),fe=(i,e,t,r)=>Is(e,()=>({muted:i.muted,volume:i.volume}),a=>{hu(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||a?.muted===s?.muted&&a?.volume===s?.volume,changed$:t,onError:r}),$e=(i,e,t,r)=>Is(e,()=>i.playbackRate,a=>{hu(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),xt=Is;var IA=i=>["__",i.language,i.label].join("|"),EA=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},fu=class i{constructor(e){this.available$=new zf;this.current$=new yA(void 0);this.error$=new zf;this.subscription=new vA;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:TA.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,mu.default)(this.internalTracks),s=>{tt(s)&&this.setInternal(s)},{equal:(s,n)=>tt(s)&&tt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ei(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(xt(t.externalTextTracks,()=>(0,mu.default)(this.externalTracks),s=>{tt(s)&&this.setExternal(s)},{equal:(s,n)=>tt(s)&&tt(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ei(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(){Ii(this.video);let{textTracks:e}=this.video;this.subscription.add(Or(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(Qf(Or(e,"addtrack"),Or(e,"removetrack"),Wf(["init"])).pipe(Ei(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),Yf((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(Qf(Or(e,"change"),Wf(["init"])).pipe(Ei(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ei(r=>r&&this.htmlTextTrackToITextTrack(r).id),Yf()).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;tt(t.align)&&(a.align=t.align),tt(t.position)&&(a.position=t.position),tt(t.size)&&(a.size=t.size),tt(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){Ii(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:IA(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){Ii(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(SA(e)||!EA(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){Ii(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){Ii(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Le=fu;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 Kf=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e?.parentNode;return e??void 0},bu=i=>{let e=Kf(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Xf=i=>{let e=Kf(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Me,map as Pt,merge as Zf,filterChanged as PA,isNonNullable as eb,Subject as kA,filter as tb,mapTo as rb,combine as wA,once as AA,ErrorCategory as RA,ValueSubject as ib,clientChecker as $A}from"@vkontakte/videoplayer-shared";var xA=3,Jf=(i,e,t=xA)=>{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 be=i=>{let e=P=>Me(i,P).pipe(rb(void 0)),r=Zf(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(P=>Me(i,P))).pipe(Pt(P=>P.type==="ended"?i.readyState<2:i.readyState<3),PA()),a=Zf(Me(i,"progress"),Me(i,"timeupdate")).pipe(Pt(()=>Jf(i.buffered,i.currentTime))),s=$A.isSafari?wA({play:e("play").pipe(AA()),playing:e("playing")}).pipe(rb(void 0)):e("playing"),n=Me(i,"volumechange").pipe(Pt(()=>({muted:i.muted,volume:i.volume}))),o=Me(i,"ratechange").pipe(Pt(()=>i.playbackRate)),u=Me(i,"error").pipe(tb(()=>!!(i.error||i.played.length)),Pt(()=>{let P=i.error;return{id:P?`MediaError#${P.code}`:"HtmlVideoError",category:RA.VIDEO_PIPELINE,message:P?P.message:"Error event from HTML video element",thrown:i.error??void 0}})),l=Me(i,"timeupdate").pipe(Pt(()=>i.currentTime)),d=new kA,c=.3,p;l.subscribe(P=>{i.loop&&eb(p)&&eb(P)&&p>=i.duration-c&&P<=c&&d.next(p),p=P});let m=e("pause").pipe(tb(()=>!i.error&&p!==i.duration)),f=Me(i,"enterpictureinpicture"),b=Me(i,"leavepictureinpicture"),g=new ib(Xf(i));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new ib(bu(i));return Me(i,"fullscreenchange").pipe(Pt(()=>bu(i))).subscribe(S),{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$:Me(i,"durationchange").pipe(Pt(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S,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=M(Br(),1),bb=M(He(),1),Es=M(xr(),1);import{isNonNullable as Z,isNullable as Su,now as gb,isHigher as vu,isHigherOrEqual as yu,isInvariantQuality as hb,isLower as mb,isLowerOrEqual as Tu,videoSizeToQuality as NA,assertNotEmptyArray as Sb,assertNonNullable as FA}from"@vkontakte/videoplayer-shared";var gu=!1,pt={},cb=i=>{gu=i},db=()=>{pt={}},pb=i=>{i(pt)},xi=(i,e)=>{gu&&(pt.meta=pt.meta??{},pt.meta[i]=e)},le=class{constructor(e){this.name=e}next(e){if(!gu)return;pt.series=pt.series??{};let t=pt.series[this.name]??[];t.push([Date.now(),e]),pt.series[this.name]=t}};var qA=new le("best_bitrate"),vb=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;var Iu=i=>(e,t)=>i*(Number(e.bitrate)-Number(t.bitrate)),Pi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=gb()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},yb='Assertion "ABR Tracks is empty array" failed',xs=(i,e,t,r)=>{let a=[...e].sort(Iu(1)),s=[...t].sort(Iu(1)),n=s.filter(u=>Z(u.bitrate)&&Z(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,bb.default)(n,o)?o:n.length?(0,At.default)(n,-1):(0,At.default)(s,0)},fb=i=>"quality"in i,Tb=(i,e,t,r)=>{let a=Z(r?.last?.bitrate)&&Z(t?.bitrate)&&r.last.bitrate<t.bitrate?i.trackCooldownIncreaseQuality:i.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&gb()-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=fb(n)?"video":"audio",u=fb(n)?n.quality:n.bitrate;return e({message:`
|
|
8
8
|
[last ${o} selected] ${u}
|
|
9
|
-
`}),n}return r?.recordSwitch(t),t},
|
|
9
|
+
`}),n}return r?.recordSwitch(t),t},UA=(i,e)=>Math.log(e)/Math.log(i),Rt=(i,{container:e,estimatedThroughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:d,droppedVideoMaxQualityLimit:c,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:m,abrLogger:f})=>{Sb(i,yb);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let v=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(v-1)+1;else{let x=r.pixelRatioLogBase,[U=0,Ee=0,Ve=0]=r.pixelRatioLogCoefficients,w=UA(x,U*v+Ee)+Ve;Number.isFinite(w)&&(b*=w)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,S=r.considerPlaybackRate&&Z(o)?o:1,k=i.filter(v=>!hb(v.quality)).sort((v,x)=>vu(v.quality,x.quality)?-1:1),P=(0,At.default)(k,-1)?.quality,A=(0,At.default)(k,0)?.quality,y=Su(a)||Z(a.min)&&Z(a.max)&&mb(a.max,a.min)||Z(a.min)&&A&&vu(a.min,A)||Z(a.max)&&P&&mb(a.max,P),T=S*vb(n??.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),D={},N=k.filter(v=>{let x=!0;if(g)if(v.size)x=v.size.width<=g.width&&v.size.height<=g.height;else{let j=g&&NA(g);x=j?Tu(v.quality,j):!0}if(!x)return D[v.quality]="FitsContainer",!1;let U=m||t;if(!(Z(U)&&isFinite(U)&&Z(v.bitrate)?U-s>=v.bitrate*T:!0))return D[v.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&Z(r.minBufferToSwitchUp)&&u&&!hb(u.quality)&&(n??0)<r.minBufferToSwitchUp&&vu(v.quality,u.quality))return D[v.quality]="Buffer",!1;if(!!c&&yu(v.quality,c))return D[v.quality]="DroppedFramesLimit",!1;if(!!p&&yu(v.quality,p))return D[v.quality]="StallsLimit",!1;let B=y||(Su(a.max)||Tu(v.quality,a.max))&&(Su(a.min)||yu(v.quality,a.min)),R=Z(d)&&!d?Tu(v.quality,r.backgroundVideoQualityLimit):!0;return!B||!R?(D[v.quality]="FitsQualityLimits",!1):!0})[0];N&&N.bitrate&&qA.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
|
-
${i.map(
|
|
12
|
+
${i.map(v=>`{ id: ${v.id}, quality: ${v.quality}, bitrate: ${v.bitrate}, size: ${v.size?.width}:${v.size?.height} }`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[tuning]
|
|
16
|
-
${(0,
|
|
16
|
+
${(0,Es.default)(r??{}).map(([v,x])=>`${v}: ${x}`).join(`
|
|
17
17
|
`)}
|
|
18
18
|
|
|
19
19
|
[limit params]
|
|
20
|
-
|
|
20
|
+
containerSizeFactor: ${b},
|
|
21
|
+
containerSizeLimit: ${g?.width??0} x ${g?.height??0},
|
|
21
22
|
estimatedThroughput: ${t},
|
|
22
|
-
stallsPredictedThroughput: ${
|
|
23
|
+
stallsPredictedThroughput: ${m},
|
|
23
24
|
reserve: ${s},
|
|
24
25
|
playbackRate: ${o},
|
|
25
|
-
playbackRateFactor: ${
|
|
26
|
+
playbackRateFactor: ${S},
|
|
26
27
|
forwardBufferHealth: ${n},
|
|
27
|
-
bitrateFactor: ${
|
|
28
|
+
bitrateFactor: ${T},
|
|
28
29
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
29
|
-
droppedVideoMaxQualityLimit: ${
|
|
30
|
+
droppedVideoMaxQualityLimit: ${c},
|
|
30
31
|
stallsVideoMaxQualityLimit: ${p},
|
|
31
32
|
limitsAreInvalid: ${y},
|
|
32
33
|
maxQualityLimit: ${a?.max},
|
|
33
34
|
minQualityLimit: ${a?.min},
|
|
34
35
|
|
|
35
36
|
[limited video tracks]
|
|
36
|
-
${(0,
|
|
37
|
+
${(0,Es.default)(D).map(([v,x])=>`${v}: ${x}`).join(`
|
|
37
38
|
`)||"All tracks are available"}
|
|
38
39
|
|
|
39
|
-
[best video track] ${
|
|
40
|
-
[selected video track] ${
|
|
41
|
-
`}),
|
|
40
|
+
[best video track] ${N?.quality}
|
|
41
|
+
[selected video track] ${q?.quality}
|
|
42
|
+
`}),Tb(r,f,q,l)},Ib=(i,e,t,{estimatedThroughput:r,tuning:a,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{Sb(t,yb);let d=a.considerPlaybackRate&&Z(s)?s:1,c=[...t].sort(Iu(-1)),p=i.bitrate;FA(p);let m=d*vb(n??.5,a.bitrateAudioFactorAtEmptyBuffer,a.bitrateAudioFactorAtFullBuffer),f,b=xs(i,e,t,a.minVideoAudioRatio),g=l||r;return Z(g)&&isFinite(g)&&(f=c.find(S=>Z(S.bitrate)&&Z(b?.bitrate)?g-p>=S.bitrate*m&&S.bitrate>=b.bitrate:!1)),f||(f=b),f?.bitrate!==o?.last?.bitrate&&u({message:`
|
|
42
43
|
[AUDIO TRACKS ABR]
|
|
43
44
|
[available audio tracks]
|
|
44
|
-
${t.map(
|
|
45
|
+
${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
|
|
45
46
|
`)}
|
|
46
47
|
|
|
47
48
|
[tuning]
|
|
48
|
-
${(0,
|
|
49
|
+
${(0,Es.default)(a??{}).map(([S,k])=>`${S}: ${k}`).join(`
|
|
49
50
|
`)}
|
|
50
51
|
|
|
51
52
|
[limit params]
|
|
@@ -53,20 +54,20 @@ var ny=Object.create;var $l=Object.defineProperty;var oy=Object.getOwnPropertyDe
|
|
|
53
54
|
stallsPredictedThroughput: ${l},
|
|
54
55
|
reserve: ${p},
|
|
55
56
|
playbackRate: ${s},
|
|
56
|
-
playbackRateFactor: ${
|
|
57
|
+
playbackRateFactor: ${d},
|
|
57
58
|
forwardBufferHealth: ${n},
|
|
58
|
-
bitrateFactor: ${
|
|
59
|
+
bitrateFactor: ${m},
|
|
59
60
|
minBufferToSwitchUp: ${a.minBufferToSwitchUp},
|
|
60
61
|
|
|
61
62
|
[selected audio track] ${f?.id}
|
|
62
|
-
`}),f&&gb(a,u,f,o)};var Z=i=>new URL(i).hostname;import{assertNever as wb,assertNonNullable as Rb,combine as aR,debounce as sR,ErrorCategory as $b,filter as Lb,filterChanged as nR,isNonNullable as Pu,map as ks,merge as Mb,observableFrom as oR,once as uR,Subscription as lR,ValueSubject as ku,videoQualityToHeight as cR,videoSizeToQuality as dR}from"@vkontakte/videoplayer-shared";var yb=C(Ke(),1),Sb=i=>{if(i instanceof DOMException&&(0,yb.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"))},ge=async(i,e)=>{let t=i.muted;try{await i.play()}catch(r){if(!Sb(r))return!1;if(e&&e(),t)return console.warn(r),!1;i.muted=!0;try{await i.play()}catch(a){return Sb(a)&&(i.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as Es,isNullable as Fw,assertNonNullable as Ai}from"@vkontakte/videoplayer-shared";var Ib=C(yi(),1);import{isNonNullable as Tb,assertNonNullable as Is,now as _w}from"@vkontakte/videoplayer-shared";function ee(){return _w()}function Tu(i){return ee()-i}function Iu(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 Eb(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Vr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Is(c);let T=Tu(c),q;if(T<b){q=b-T,setTimeout(g,q);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,R()},v=T=>(s=T,S),k=T=>(d=T,S),E=()=>(h="json",S),A=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},y=T=>(p=T,S),R=()=>{c=ee(),n=new a,n.open("get",i);let T=0,q,ye=0,Ve=()=>(Is(c),Math.max(c,Math.max(q||0,ye||0)));if(s&&n.addEventListener("progress",P=>{let M=ee();s.updateChunk&&P.loaded>T&&(s.updateChunk(Ve(),P.loaded-T),T=P.loaded,q=M)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>A())),n.addEventListener("load",()=>{if(u)return;Is(n);let P=n.status;if(P>=200&&P<300){if(n.response.byteLength&&s){let M=n.response.byteLength-T;M&&s.updateChunk&&s.updateChunk(Ve(),M)}n.responseType==="json"&&!(0,Ib.default)(n.response).length?A():(d&&d(),e(n.response))}else A()}),n.addEventListener("error",()=>{A()}),p){let P=()=>{Is(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ye=ee(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=h,n.send(),S},S={withBitrateReporting:v,withParallel:y,withJSONResponse:E,withRetryCount:T=>(l=T,S),withRetryInterval:(T,q)=>(Tb(T)&&(b=T),Tb(q)&&(f=q),S),withTimeout:T=>(o=T,S),withFinally:k,send:R,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return S}var Pi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&r>0){let s=a*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var xb=C(yi(),1);var ki=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ee(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ee()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Vr(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,xb.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 qw}from"@vkontakte/videoplayer-shared";var xs=1e4,Eu=3;var Uw=6e4,Hw=10,jw=1,Gw=500,wi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new qw,this.chunkRateEstimator=new Pi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Iu(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=Iu(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||Es(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=()=>{Eb(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new ki(Eu,xs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let A=s&&(!c||c===this.rep);return A||t("Not running!"),A},p=(A,y,R)=>{u&&u.abort(),u=Vr(this.urlResolver.resolve(A,!1),y,R,()=>this._retryCallback()).withTimeout(xs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Eu).withFinally(()=>{u=null}).send()},h=(A,y,R)=>{Ai(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(A,!1),y,R,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=A=>{let y=r.playbackRate;r.playbackRate!==A&&(t(`Playback rate switch: ${y}=>${A}`),r.playbackRate=A)},b=A=>{this.lowLatency=A,t(`lowLatency changed to ${A}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let A=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let R=ee()-1e4,O=0;for(let _=0;_<this.bufferStates.length;_++){let H=this.bufferStates[_];A=Math.min(A,H.buf),H.ts<R&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${A} drop=${O} jitter=${this.sourceJitter}`);let F=A-jw;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?f(1.15):F>1?f(1.1):F>.3?f(1.05):f(1)}},v=A=>{let y,R=()=>y&&y.start?y.start.length:0,O=P=>y.start[P]/1e3,F=P=>y.dur[P]/1e3,_=P=>y.fragIndex+P,H=(P,M)=>({chunkIdx:_(P),startTS:O(P),dur:F(P),discontinuity:M}),S=()=>{let P=0;if(y&&y.dur){let M=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,w=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,K=M;this.sourceJitter>1&&(K+=this.sourceJitter-1);let te=y.dur.length-1;for(;te>=0&&(K-=y.dur[te],!(K<=0));--te);P=Math.min(te,y.dur.length-1-w),P=Math.max(P,0)}return H(P,!0)},T=P=>{let M=R();if(!(M<=0)){if(Es(P)){for(let w=0;w<M;w++)if(O(w)>P)return H(w)}return S()}},q=P=>{let M=R(),w=P?P.chunkIdx+1:0,K=w-y.fragIndex;if(!(M<=0)){if(!P||K<0||K-M>Hw)return t(`Resync: offset=${K} bChunks=${M} chunk=`+JSON.stringify(P)),S();if(!(K>=M))return H(w-y.fragIndex,!1)}},ye=(P,M,w)=>{l&&l.abort(),l=Vr(this.urlResolver.resolve(P,!0,this.lowLatency),M,w,()=>this._retryCallback()).withTimeout(xs).withRetryCount(Eu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(P,M)=>{ye(A,w=>{if(!d())return;y=w;let K=!!y.lowLatency;K!==this.lowLatency&&b(K);let te=0;for(let ht=0;ht<y.dur.length;++ht)te+=y.dur[ht];te>0&&(Ai(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(te/y.dur.length)),a({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,P(T(M))},()=>this._handleNetworkError())},nextChunk:q}},k=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ai(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:A=>{let{videoElement:y,logger:R}=this.params,O=v(e.jidxUrl),F,_,H,S,T=0,q,ye,Ve,P=()=>{q&&(clearTimeout(q),q=void 0);let V=Math.max(Gw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),re=T+V,Y=ee(),de=Math.min(1e4,re-Y);T=Y;let Te=()=>{l||d()&&O.seek(()=>{d()&&(T=ee(),M(),P())})};de>0?q=window.setTimeout(()=>{this.paused?P():Te()},de):Te()},M=()=>{let V;for(;V=O.nextChunk(S);)S=V,nr(V);let re=O.nextChunk(H);if(re){if(H&&re.discontinuity){R("Detected discontinuity; restarting playback"),this.paused?P():(k(),this._initPlayerWith(e));return}ht(re)}else P()},w=(V,re)=>{if(!d()||!this.sourceBuffer)return;let Y,de,Te,tt=je=>{window.setTimeout(()=>{d()&&w(V,re)},je)};if(this.sourceBuffer.updating)R("Source buffer is updating; delaying appendBuffer"),tt(100);else{let je=ee(),rt=y.currentTime;!this.paused&&y.buffered.length>1&&ye===rt&&je-Ve>500&&(R("Stall suspected; trying to fix"),this._fixupStall()),ye!==rt&&(ye=rt,Ve=je);let Ge=this._getBufferSizeSec();if(Ge>30)R(`Buffered ${Ge} seconds; delaying appendBuffer`),tt(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:je,buf:Ge}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),re&&re()}catch(or){if(or.name==="QuotaExceededError")R("QuotaExceededError; delaying appendBuffer"),Te=this.sourceBuffer.buffered.length,Te!==0&&(Y=this.sourceBuffer.buffered.start(0),de=rt,de-Y>4&&this.sourceBuffer.remove(Y,de-3)),tt(1e3);else throw or}}},K=()=>{_&&F&&(R([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(H)]),w(_,function(){_=null,M()}))},te=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),ht=V=>{d()&&h(te(V),(re,Y)=>{if(d()){if(Y/=1e3,_=re,H=V,n=V.startTS,Y){let de=Math.min(10,V.dur/Y);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*de:de}K()}},()=>this._handleNetworkError())},nr=V=>{d()&&(Ai(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(te(V),!1)))},Vt=V=>{d()&&(e.cachedHeader=V,w(V,()=>{F=!0,K()}))};s=!0,O.seek(V=>{if(d()){if(T=ee(),!V){P();return}S=V,!Fw(A)||V.startTS>A?ht(V):(H=V,M())}},A),e.cachedHeader?Vt(e.cachedHeader):p(e.headerUrl,Vt,()=>this._handleNetworkError())},stop:k,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Es(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ai(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Es(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=ee();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Tu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ee();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Vr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(xs).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;ge(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))},Uw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ab=C(Ir(),1);import{debounce as Qw,filter as Pb,fromEvent as Ww,interval as Yw,isHigher as zw,isInvariantQuality as Kw,isLower as Jw,merge as Xw,Subject as kb,Subscription as Zw}from"@vkontakte/videoplayer-shared";var xu=class{constructor(){this.onDroopedVideoFramesLimit$=new kb;this.subscription=new Zw;this.playing=!1;this.tracks=[];this.forceChecker$=new kb;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&&!Kw(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&&zw(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(Ww(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Yw(this.droppedFramesChecker.checkTime).pipe(Pb(()=>this.playing),Pb(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(Qw(this.droppedFramesChecker.checkTime)),r=Xw(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,Ab.default)(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>Jw(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}},Ps=xu;import{map as eR,Observable as tR}from"@vkontakte/videoplayer-shared";import{fromEvent as rR}from"@vkontakte/videoplayer-shared";var Ri=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var iR=(i,e)=>new tR(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ri()))},{...r,...e});a.observe(i);let s=rR(document,"visibilitychange").pipe(eR(n=>!document.hidden||Ri())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Ce=iR;var pR=["paused","playing","ready"],hR=["paused","playing","ready"],$i=class{constructor(e){this.subscription=new lR;this.videoState=new $("stopped");this.representations$=new ku([]);this.textTracksManager=new Le;this.droppedFramesManager=new Ps;this.maxSeekBackTime$=new ku(1/0);this.zeroTime$=new ku(void 0);this.liveOffset=new ot;this._dashCb=e=>{switch(e.name){case"buffering":{let t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:$b.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=Et(a.name)??dR(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),Pu(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,Au.default)(hR,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,Au.default)(pR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(se(this.params.source.url,u))}return;default:return wb(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:$b.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Mb(this.videoState.stateChangeStarted$.pipe(ks(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ks(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(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=be(this.video);this.subscription.add(this.representations$.pipe(ks(a=>a.map(({track:s})=>s)),Lb(a=>!!a.length),uR()).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(nR(),ks(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(aR({zeroTime:this.zeroTime$.pipe(Lb(Pu)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(Je(this.video,this.params.desiredState.isLooped,t)).add(fe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add($e(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ce(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&cR(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 wb(a.to)}},t)).add(Mb(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,oR(["init"])).pipe(sR(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),me(this.video)}createLiveDashPlayer(){let e=new wi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){let e=this.representations$.getValue(),t=this.params.desiredState.videoTrack.getTransition()?.to??this.params.desiredState.videoTrack.getState(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition()?.to??this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&Pu(t)?t:Pt(e.map(({track:l})=>l),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(r),n||u||s!==o){let l=e.find(({track:c})=>c.id===s)?.representation;Rb(l,"Representations missing"),this.dash.startPlay(l,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;Rb(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(se(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Cb=$i;var nS=C(Ke(),1);var Ze=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){let a=i.start(r)*1e3,s=i.end(r)*1e3;a<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as ZL,assertNonNullable as eM,debounce as tM,ErrorCategory as pl,filter as iS,filterChanged as ba,fromEvent as rM,isNonNullable as aS,map as hl,merge as Js,observableFrom as iM,once as sS,Subscription as aM}from"@vkontakte/videoplayer-shared";var As=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}},Or=class extends As{constructor(){super(),this.listeners||As.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},Li=class{constructor(){Object.defineProperty(this,"signal",{value:new Or,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document>"u")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch{r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol<"u"&&Symbol.toStringTag&&(Li.prototype[Symbol.toStringTag]="AbortController",Or.prototype[Symbol.toStringTag]="AbortSignal");function ws(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 wu(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!ws({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch{d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var Mi=ws({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Db=Mi?wu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,kt=Mi?Db.fetch:window.fetch,E_=Mi?Db.Request:window.Request,ke=Mi?Li:window.AbortController,x_=Mi?Or:window.AbortSignal;var ll=C($u(),1);var Ls=C(Dr(),1);var lt=()=>window.ManagedMediaSource||window.MediaSource,Rs=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),eg=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),tg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Ds,clientChecker as Ms}from"@vkontakte/videoplayer-shared";var Cs=document.createElement("video"),_R='video/mp4; codecs="avc1.42000a,mp4a.40.2"',NR='video/mp4; codecs="hev1.1.6.L93.B0"',rg='video/webm; codecs="vp09.00.10.08"',ig='video/webm; codecs="av01.0.00M.08"',FR='audio/mp4; codecs="mp4a.40.2"',qR='audio/webm; codecs="opus"',Ci={mms:Rs(),mse:eg(),hls:!!(Cs.canPlayType?.("application/x-mpegurl")||Cs.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ve={mp4:!!Cs.canPlayType?.("video/mp4"),webm:!!Cs.canPlayType?.("video/webm"),cmaf:!0},Se={h264:!!lt()?.isTypeSupported?.(_R),h265:!!lt()?.isTypeSupported?.(NR),vp9:!!lt()?.isTypeSupported?.(rg),av1:!!lt()?.isTypeSupported?.(ig),aac:!!lt()?.isTypeSupported?.(FR),opus:!!lt()?.isTypeSupported?.(qR)},Br=(Se.h264||Se.h265)&&Se.aac,Kt,UR=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:ig}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:rg}})]);Kt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{UR()}catch(i){console.error(i)}var _r=Ci.hls&&ve.mp4,ag=()=>Object.keys(Se).filter(i=>Se[i]),sg=(i,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let a=Ci.mse&&(!r||!!window.MediaStreamTrack)||Ci.mms&&t;return i.filter(s=>{switch(s){case"DASH_SEP":return a&&ve.mp4&&Br;case"DASH_WEBM":return a&&ve.webm&&Se.vp9&&Se.opus;case"DASH_WEBM_AV1":return a&&ve.webm&&Se.av1&&Se.opus;case"DASH_STREAMS":return a&&(ve.mp4&&Br||ve.webm&&(Se.vp9||Se.av1)&&(Se.opus||Se.aac));case"DASH_LIVE":return a&&ve.mp4&&Br;case"DASH_LIVE_CMAF":return a&&ve.mp4&&Br&&ve.cmaf;case"DASH_ONDEMAND":return a&&ve.mp4&&Br;case"HLS":case"HLS_ONDEMAND":return _r||e&&a&&ve.mp4&&Br;case"HLS_LIVE":case"HLS_LIVE_CMAF":return _r;case"MPEG":return ve.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Ci.webrtc&&Ci.ws&&Se.h264&&(ve.mp4||ve.webm);default:return Ds(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 Kt?Kt[t].smooth?[t,e]:Kt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Kt?Kt[t].powerEfficient?[t,e]:Kt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ds(i)}return[e,t]},ng=({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(Ms.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:Ds(e)}return _r?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},og=({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=Ms.isMac&&Ms.isSafari;if(Ms.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:Ds(i)}else _r&&!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"]},Lu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ug=i=>{if(i.size===0)return;if(i.size===1){let t=i.values().next();return(0,Ls.default)(t.value.split("."),0)}for(let t of i){let r=(0,Ls.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=i.values().next();return(0,Ls.default)(e.value.split("."),0)};var Rg=C(wg(),1);import{ErrorCategory as Vi}from"@vkontakte/videoplayer-shared";var $g=i=>{if(!i)return{id:"EmptyResponse",category:Vi.PARSER,message:"Empty response"};if(i.length<=2&&i.match(/^\d+$/))return{id:`UVError#${i}`,category:Vi.NETWORK,message:`UV Error ${i}`};let e=(0,Rg.default)(i).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Vi.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:Vi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Vi.PARSER,message:"Response is valid XML, but parser failed"}};var At=(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 nl,assertNonNullable as rr,clientChecker as CL,combine as pa,ErrorCategory as Lt,filter as js,filterChanged as ol,flattenObject as ha,fromEvent as ir,getTraceSubscriptionMethod as DL,interval as ul,isNonNullable as zv,map as ma,merge as ar,now as VL,Subject as Gs,Subscription as Kv,tap as OL,throttle as BL,ValueSubject as W}from"@vkontakte/videoplayer-shared";var Bs=C(Ke(),1),Ur=C(Dr(),1),_s=C($u(),1);var s$=(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)},n$=i=>window.clearTimeout(i),Lg=i=>typeof i=="function"&&i?.toString().endsWith("{ [native code] }"),Mg=!Lg(window.requestIdleCallback)||!Lg(window.cancelIdleCallback),Ou=Mg?s$:window.requestIdleCallback,Oi=Mg?n$:window.cancelIdleCallback;var Fv=C(bs(),1);import{assertNever as o$,ErrorCategory as Cg,clientChecker as Bu,Subject as Dg}from"@vkontakte/videoplayer-shared";var u$=18,Vg=!1;try{Vg=Bu.isSafari&&!!Bu.macVersion&&Bu.macVersion<=u$}catch(i){console.error(i)}var _u=class{constructor(e){this.bufferFull$=new Dg;this.error$=new Dg;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{try{if(this.currentTask){let e=this.currentTask.signal?.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(e){this.error$.next({id:"BufferTaskQueueUnknown",category:Cg.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;Vg&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:a}of this.queue)a(!1);r&&(this.queue=[r]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if(e.signal?.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:Cg.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:o$(t)}}},Og=_u;var Nu=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 Zt,assertNonNullable as le,ErrorCategory as Rt,fromEvent as tl,getExponentialDelay as rl,isNonNullable as Vs,isNullable as De,now as Os,once as EL,Subject as xL,Subscription as PL,ValueSubject as qr}from"@vkontakte/videoplayer-shared";var N=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Nr=class extends N{};var Bi=class extends N{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let a=this.content.byteOffset,s=a+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(a,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var _i=class extends N{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let a=this.readString(4);this.compatibleBrands.push(a),r-=4}}};var Ni=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var j=class extends N{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var Fi=class extends j{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var qi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ui=class extends N{constructor(e,t){super(e,t),this.data=this.content}};var Jt=class extends j{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let a=this.readUint32(),s=a>>>31,n=a<<1>>>1,o=this.readUint32();a=this.readUint32();let u=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var Hi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ji=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends j{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Qi=class extends j{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Wi=class extends j{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Yi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var zi=class extends j{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Ki=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ji=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Xi=class extends j{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Zi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ea=class extends j{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ta=class extends j{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ra=class extends j{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let a=0;a<this.sampleCount;a++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var c$={ftyp:_i,moov:Ni,mvhd:Fi,moof:qi,mdat:Ui,sidx:Jt,trak:Hi,mdia:Yi,mfhd:Xi,tkhd:zi,traf:Zi,tfhd:ea,tfdt:ta,trun:ra,minf:Ki,sv3d:ji,st3d:Gi,prhd:Qi,proj:Ji,equi:Wi,uuid:Bi,unknown:Nr},ct=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=c$[e];return r?new r(t,new i):new Nr(t,new i)}};var wt=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 p$=new TextDecoder("ascii"),h$=i=>p$.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",m$=i=>{let e=new Jt(i,new ct),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})},f$=(i,e)=>{let r=new ct().parse(i),a=new wt(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,d)},b$=i=>{let t=new ct().parse(i),r=new wt(t),a={},s=r.findAll("uuid");return s.length?s[s.length-1]:a},g$=i=>{let t=new ct().parse(i);return new wt(t).find("sidx")?.timescale},v$=(i,e)=>{let r=new ct().parse(i),s=new wt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},S$=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 ct().parse(i),a=new wt(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},Bg={validateData:h$,parseInit:S$,getIndexRange:()=>{},parseSegments:m$,parseFeedableSegmentChunk:f$,getChunkEndTime:v$,getServerLatencyTimestamps:b$,getTimescaleFromIndex:g$};var aa=C(Ke(),1);import{assertNonNullable as qu,isNonNullable as qg,isNullable as T$}from"@vkontakte/videoplayer-shared";import{assertNever as y$}from"@vkontakte/videoplayer-shared";var _g={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"}},Ng=i=>{let e=i.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=ia(i,t),a=r in _g,s=a?_g[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,c=ia(u),d=l*2**((o-1)*8)+c,p=t+o,h;return p+d>i.byteLength?h=new DataView(i.buffer,i.byteOffset+p):h=new DataView(i.buffer,i.byteOffset+p,d),{tag:a?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},ia=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{let t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ue=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return ia(i);case"float":return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case"string":return new TextDecoder("ascii").decode(i);case"utf8":return new TextDecoder("utf-8").decode(i);case"date":return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case"master":return i;case"binary":return i;default:y$(e)}},Xt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Ng(r);if(!e(a))return;a.type==="master"&&Xt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Fg=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Ng(i);return Xt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Ue(o,n):s===17026?t=Ue(o,n):s===17029&&(r=Ue(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Ug=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],I$=[231,22612,22743,167,171,163,160,175],E$=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return Xt(i,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ue(f,h);l=ia(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ue(f,h):p===17545?a=Ue(f,h):p===21420&&l===475249515?u=Ue(f,h):p===374648427?Xt(f,({tag:g,type:v,value:k})=>g===30321?(c=Ue(k,v)===1,!1):!0):s&&n&&(0,aa.default)(Ug,p)&&(o=!0),!o}),qu(e,"Failed to parse webm Segment start"),qu(t,"Failed to parse webm Segment end"),qu(a,"Failed to parse webm Segment duration"),r=r??1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},x$=i=>{if(T$(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},P$=(i,e)=>{let t=!1,r=!1,a=o=>qg(o.time)&&qg(o.position),s=[],n;return Xt(i,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ue(l,u));break;case 183:break;case 241:n&&(n.position=Ue(l,u));break;default:t&&(0,aa.default)(Ug,o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},k$=i=>{let e=0,t=!1;try{Xt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,aa.default)(I$,r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=(0,aa.default)([163,160,175],r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Hg={validateData:Fg,parseInit:E$,getIndexRange:x$,parseSegments:P$,parseFeedableSegmentChunk:k$};var sa=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Hg;case"mp4":return Bg}}throw new ReferenceError(`Unsupported mime type ${i}`)};var Yu=C(lv(),1),Mv=C(Ir(),1),Cv=C(Pv(),1),Dv=C(Dr(),1);var kv=C(Ke(),1),Wu=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,kv.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as Rv,isNullable as $v}from"@vkontakte/videoplayer-shared";var Av=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var wv=i=>{try{let e=TL(),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 TL(){let i="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
|
|
63
|
+
`}),f&&Tb(a,u,f,o)};var ee=i=>new URL(i).hostname;import{assertNever as Mb,assertNonNullable as Db,combine as lR,debounce as cR,ErrorCategory as Cb,filter as Vb,filterChanged as dR,isNonNullable as wu,map as Rs,merge as Ob,observableFrom as pR,once as hR,Subscription as mR,ValueSubject as Au,videoQualityToHeight as fR,videoSizeToQuality as bR}from"@vkontakte/videoplayer-shared";var xb=M(He(),1),Eb=i=>{if(i instanceof DOMException&&(0,xb.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"))},ge=async(i,e)=>{let t=i.muted;try{await i.play()}catch(r){if(!Eb(r))return!1;if(e&&e(),t)return console.warn(r),!1;i.muted=!0;try{await i.play()}catch(a){return Eb(a)&&(i.muted=!1,console.warn(a)),!1}}return!0};import{isNonNullable as ks,isNullable as GA,assertNonNullable as Ai}from"@vkontakte/videoplayer-shared";var kb=M(Vr(),1);import{isNonNullable as Pb,assertNonNullable as Ps,now as HA}from"@vkontakte/videoplayer-shared";function te(){return HA()}function Eu(i){return te()-i}function xu(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 wb(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;Ps(d);let x=Eu(d),U;if(x<b){U=b-x,setTimeout(g,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,T()},S=x=>(s=x,v),k=x=>(c=x,v),P=()=>(m="json",v),A=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,c&&c(),t&&t()}},y=x=>(p=x,v),T=()=>{d=te(),n=new a,n.open("get",i);let x=0,U,Ee=0,Ve=()=>(Ps(d),Math.max(d,Math.max(U||0,Ee||0)));if(s&&n.addEventListener("progress",w=>{let V=te();s.updateChunk&&w.loaded>x&&(s.updateChunk(Ve(),w.loaded-x),x=w.loaded,U=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>A())),n.addEventListener("load",()=>{if(u)return;Ps(n);let w=n.status;if(w>=200&&w<300){if(n.response.byteLength&&s){let V=n.response.byteLength-x;V&&s.updateChunk&&s.updateChunk(Ve(),V)}n.responseType==="json"&&!(0,kb.default)(n.response).length?A():(c&&c(),e(n.response))}else A()}),n.addEventListener("error",()=>{A()}),p){let w=()=>{Ps(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Ee=te(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=m,n.send(),v},v={withBitrateReporting:S,withParallel:y,withJSONResponse:P,withRetryCount:x=>(l=x,v),withRetryInterval:(x,U)=>(Pb(x)&&(b=x),Pb(U)&&(f=U),v),withTimeout:x=>(o=x,v),withFinally:k,send:T,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return v}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 Ab=M(Vr(),1);var wi=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=te(),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=te()-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=te()}_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=te();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,Ab.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 QA}from"@vkontakte/videoplayer-shared";var ws=1e4,Pu=3;var WA=6e4,YA=10,zA=1,KA=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 QA,this.chunkRateEstimator=new ki(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=xu(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=xu(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||ks(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=()=>{wb(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 wi(Pu,ws,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 A=s&&(!d||d===this.rep);return A||t("Not running!"),A},p=(A,y,T)=>{u&&u.abort(),u=_r(this.urlResolver.resolve(A,!1),y,T,()=>this._retryCallback()).withTimeout(ws).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Pu).withFinally(()=>{u=null}).send()},m=(A,y,T)=>{Ai(this.filesFetcher),o?.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(A,!1),y,T,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=A=>{let y=r.playbackRate;r.playbackRate!==A&&(t(`Playback rate switch: ${y}=>${A}`),r.playbackRate=A)},b=A=>{this.lowLatency=A,t(`lowLatency changed to ${A}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let A=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let T=te()-1e4,D=0;for(let N=0;N<this.bufferStates.length;N++){let q=this.bufferStates[N];A=Math.min(A,q.buf),q.ts<T&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${A} drop=${D} jitter=${this.sourceJitter}`);let G=A-zA;this.sourceJitter>=0?G-=this.sourceJitter/2:this.sourceJitter-=1,G>3?f(1.15):G>1?f(1.1):G>.3?f(1.05):f(1)}},S=A=>{let y,T=()=>y&&y.start?y.start.length:0,D=w=>y.start[w]/1e3,G=w=>y.dur[w]/1e3,N=w=>y.fragIndex+w,q=(w,V)=>({chunkIdx:N(w),startTS:D(w),dur:G(w),discontinuity:V}),v=()=>{let w=0;if(y&&y.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,B=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,R=V;this.sourceJitter>1&&(R+=this.sourceJitter-1);let j=y.dur.length-1;for(;j>=0&&(R-=y.dur[j],!(R<=0));--j);w=Math.min(j,y.dur.length-1-B),w=Math.max(w,0)}return q(w,!0)},x=w=>{let V=T();if(!(V<=0)){if(ks(w)){for(let B=0;B<V;B++)if(D(B)>w)return q(B)}return v()}},U=w=>{let V=T(),B=w?w.chunkIdx+1:0,R=B-y.fragIndex;if(!(V<=0)){if(!w||R<0||R-V>YA)return t(`Resync: offset=${R} bChunks=${V} chunk=`+JSON.stringify(w)),v();if(!(R>=V))return q(B-y.fragIndex,!1)}},Ee=(w,V,B)=>{l&&l.abort(),l=_r(this.urlResolver.resolve(w,!0,this.lowLatency),V,B,()=>this._retryCallback()).withTimeout(ws).withRetryCount(Pu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,V)=>{Ee(A,B=>{if(!c())return;y=B;let R=!!y.lowLatency;R!==this.lowLatency&&b(R);let j=0;for(let at=0;at<y.dur.length;++at)j+=y.dur[at];j>0&&(Ai(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(j/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(x(V))},()=>this._handleNetworkError())},nextChunk:U}},k=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ai(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:A=>{let{videoElement:y,logger:T}=this.params,D=S(e.jidxUrl),G,N,q,v,x=0,U,Ee,Ve,w=()=>{U&&(clearTimeout(U),U=void 0);let C=Math.max(KA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),re=x+C,oe=te(),X=Math.min(1e4,re-oe);x=oe;let ze=()=>{l||c()&&D.seek(()=>{c()&&(x=te(),V(),w())})};X>0?U=window.setTimeout(()=>{this.paused?w():ze()},X):ze()},V=()=>{let C;for(;C=D.nextChunk(v);)v=C,lr(C);let re=D.nextChunk(q);if(re){if(q&&re.discontinuity){T("Detected discontinuity; restarting playback"),this.paused?w():(k(),this._initPlayerWith(e));return}at(re)}else w()},B=(C,re)=>{if(!c()||!this.sourceBuffer)return;let oe,X,ze,Oe=Be=>{window.setTimeout(()=>{c()&&B(C,re)},Be)};if(this.sourceBuffer.updating)T("Source buffer is updating; delaying appendBuffer"),Oe(100);else{let Be=te(),st=y.currentTime;!this.paused&&y.buffered.length>1&&Ee===st&&Be-Ve>500&&(T("Stall suspected; trying to fix"),this._fixupStall()),Ee!==st&&(Ee=st,Ve=Be);let gt=this._getBufferSizeSec();if(gt>30)T(`Buffered ${gt} seconds; delaying appendBuffer`),Oe(2e3);else try{this.sourceBuffer.appendBuffer(C),this.videoPlayStarted?(this.bufferStates.push({ts:Be,buf:gt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),re&&re()}catch(nt){if(nt.name==="QuotaExceededError")T("QuotaExceededError; delaying appendBuffer"),ze=this.sourceBuffer.buffered.length,ze!==0&&(oe=this.sourceBuffer.buffered.start(0),X=st,X-oe>4&&this.sourceBuffer.remove(oe,X-3)),Oe(1e3);else throw nt}}},R=()=>{N&&G&&(T([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(q)]),B(N,function(){N=null,V()}))},j=C=>e.fragUrlTemplate.replace("%%id%%",C.chunkIdx),at=C=>{c()&&m(j(C),(re,oe)=>{if(c()){if(oe/=1e3,N=re,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}R()}},()=>this._handleNetworkError())},lr=C=>{c()&&(Ai(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(j(C),!1)))},Ye=C=>{c()&&(e.cachedHeader=C,B(C,()=>{G=!0,R()}))};s=!0,D.seek(C=>{if(c()){if(x=te(),!C){w();return}v=C,!GA(A)||C.startTS>A?at(C):(q=C,V())}},A),e.cachedHeader?Ye(e.cachedHeader):p(e.headerUrl,Ye,()=>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(),ks(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ai(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return ks(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=te();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&&Eu(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=te();c<o&&(n=p),o=c}}}_fetchManifest(e,t,r){this.manifestRequest=_r(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ws).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;ge(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))},WA))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Lb=M(xr(),1);import{debounce as XA,filter as Rb,fromEvent as JA,interval as ZA,isHigher as eR,isInvariantQuality as tR,isLower as rR,merge as iR,Subject as $b,Subscription as aR}from"@vkontakte/videoplayer-shared";var ku=class{constructor(){this.onDroopedVideoFramesLimit$=new $b;this.subscription=new aR;this.playing=!1;this.tracks=[];this.forceChecker$=new $b;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&&!tR(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&&eR(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(JA(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=ZA(this.droppedFramesChecker.checkTime).pipe(Rb(()=>this.playing),Rb(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(XA(this.droppedFramesChecker.checkTime)),r=iR(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,Lb.default)(this.limitCounts).filter(([,r])=>r>=this.droppedFramesChecker.countLimit).sort(([r],[a])=>rR(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}},As=ku;import{map as sR,Observable as nR}from"@vkontakte/videoplayer-shared";import{fromEvent as oR}from"@vkontakte/videoplayer-shared";var $i=()=>!!window.documentPictureInPicture?.window||!!document.pictureInPictureElement;var uR=(i,e)=>new nR(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=oR(document,"visibilitychange").pipe(sR(n=>!document.hidden||$i())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),De=uR;var gR=["paused","playing","ready"],SR=["paused","playing","ready"],Li=class{constructor(e){this.subscription=new mR;this.videoState=new $("stopped");this.representations$=new Au([]);this.droppedFramesManager=new As;this.maxSeekBackTime$=new Au(1/0);this.zeroTime$=new Au(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:Cb.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)??bR(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),wu(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,Ru.default)(SR,e)&&(n||o)){this.prepare();return}if(a?.to!=="paused"&&s.state==="requested"&&(0,Ru.default)(gR,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(se(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=a?.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(se(this.params.source.url,u))}return;default:return Mb(e)}};this.textTracksManager=new Le(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Cb.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Ob(this.videoState.stateChangeStarted$.pipe(Rs(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Rs(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ee(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=be(this.video);this.subscription.add(this.representations$.pipe(Rs(a=>a.map(({track:s})=>s)),Vb(a=>!!a.length),hR()).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(dR(),Rs(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(lR({zeroTime:this.zeroTime$.pipe(Vb(wu)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(et(this.video,this.params.desiredState.isLooped,t)).add(fe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add($e(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(De(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&fR(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 Mb(a.to)}},t)).add(Ob(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,pR(["init"])).pipe(cR(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),me(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&&wu(t)?t:Rt(e.map(({track:l})=>l),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=a?.id,n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.videoTrack.getState()?.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(r),n||u||s!==o){let l=e.find(({track:d})=>d.id===s)?.representation;Db(l,"Representations missing"),this.dash.startPlay(l,r)}}setVideoTrack(e){let t=this.representations$.getValue().find(({track:r})=>r.id===e.id)?.representation;Db(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),a=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(se(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Bb=Li;var cv=M(He(),1);var rt=(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 nM,assertNonNullable as oM,debounce as uM,ErrorCategory as fl,filter as ov,filterChanged as va,fromEvent as lM,isNonNullable as uv,map as bl,merge as Xs,observableFrom as gl,once as lv,Subscription as cM}from"@vkontakte/videoplayer-shared";var $s=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 $s{constructor(){super(),this.listeners||$s.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)}},Mi=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&&(Mi.prototype[Symbol.toStringTag]="AbortController",Nr.prototype[Symbol.toStringTag]="AbortSignal");function Ls(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 $u(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Ls({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 Di=Ls({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),_b=Di?$u({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ge=Di?_b.fetch:window.fetch,C_=Di?_b.Request:window.Request,ne=Di?Mi:window.AbortController,V_=Di?Nr:window.AbortSignal;var dl=M(Mu(),1);var Cs=M(Br(),1);var ht=()=>window.ManagedMediaSource||window.MediaSource,Ms=()=>!!(window.ManagedMediaSource&&window.ManagedSourceBuffer?.prototype?.appendBuffer),ag=()=>!!(window.MediaSource&&window.SourceBuffer?.prototype?.appendBuffer),sg=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Bs,clientChecker as Vs}from"@vkontakte/videoplayer-shared";var Os=document.createElement("video"),HR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',jR='video/mp4; codecs="hev1.1.6.L93.B0"',ng='video/webm; codecs="vp09.00.10.08"',og='video/webm; codecs="av01.0.00M.08"',GR='audio/mp4; codecs="mp4a.40.2"',QR='audio/webm; codecs="opus"',Ci={mms:Ms(),mse:ag(),hls:!!(Os.canPlayType?.("application/x-mpegurl")||Os.canPlayType?.("vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Se={mp4:!!Os.canPlayType?.("video/mp4"),webm:!!Os.canPlayType?.("video/webm"),cmaf:!0},ve={h264:!!ht()?.isTypeSupported?.(HR),h265:!!ht()?.isTypeSupported?.(jR),vp9:!!ht()?.isTypeSupported?.(ng),av1:!!ht()?.isTypeSupported?.(og),aac:!!ht()?.isTypeSupported?.(GR),opus:!!ht()?.isTypeSupported?.(QR)},Fr=(ve.h264||ve.h265)&&ve.aac,Jt,WR=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:og}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:ng}})]);Jt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{WR()}catch(i){console.error(i)}var qr=Ci.hls&&Se.mp4,ug=()=>Object.keys(ve).filter(i=>ve[i]),lg=(i,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let a=Ci.mse&&(!r||!!window.MediaStreamTrack)||Ci.mms&&t;return i.filter(s=>{switch(s){case"DASH_SEP":return a&&Se.mp4&&Fr;case"DASH_WEBM":return a&&Se.webm&&ve.vp9&&ve.opus;case"DASH_WEBM_AV1":return a&&Se.webm&&ve.av1&&ve.opus;case"DASH_STREAMS":return a&&(Se.mp4&&Fr||Se.webm&&(ve.vp9||ve.av1)&&(ve.opus||ve.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 Ci.webrtc&&Ci.ws&&ve.h264&&(Se.mp4||Se.webm);default:return Bs(s)}})},Ds=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 Jt?Jt[t].smooth?[t,e]:Jt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Jt?Jt[t].powerEfficient?[t,e]:Jt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Bs(i)}return[e,t]},cg=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...Ds(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],a=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Vs.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",...Ds(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ds(i),"MPEG",...a,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ds(i),...a,"HLS","HLS_ONDEMAND"];default:Bs(e)}return qr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},dg=({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=Vs.isMac&&Vs.isSafari;if(Vs.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:Bs(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"]},Du=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],pg=i=>{if(i.size===0)return;if(i.size===1){let t=i.values().next();return(0,Cs.default)(t.value.split("."),0)}for(let t of i){let r=(0,Cs.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=i.values().next();return(0,Cs.default)(e.value.split("."),0)};var Dg=M(Mg(),1);import{ErrorCategory as Oi}from"@vkontakte/videoplayer-shared";var Cg=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,Dg.default)(i).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Oi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(i,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Oi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Oi.PARSER,message:"Response is valid XML, but parser failed"}};var $t=(i,e,t=0)=>{for(let r=0;r<i.length;r++)if(i.start(r)*1e3-t<=e&&i.end(r)*1e3+t>e)return!0;return!1};import{abortable as ll,assertNonNullable as sr,clientChecker as FL,combine as Qr,ErrorCategory as Ct,filter as fa,filterChanged as Gs,flattenObject as ba,fromEvent as nr,getTraceSubscriptionMethod as qL,interval as cl,isNonNullable as ZS,map as ga,merge as or,now as UL,Subject as ev,Subscription as tv,tap as HL,throttle as jL,ValueSubject as z}from"@vkontakte/videoplayer-shared";var Ns=M(He(),1),jr=M(Br(),1),Fs=M(Mu(),1);var c$=(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)},d$=i=>window.clearTimeout(i),Vg=i=>typeof i=="function"&&i?.toString().endsWith("{ [native code] }"),Og=!Vg(window.requestIdleCallback)||!Vg(window.cancelIdleCallback),_u=Og?c$:window.requestIdleCallback,Bi=Og?d$:window.cancelIdleCallback;var GS=M(vs(),1);import{assertNever as p$,ErrorCategory as Bg,clientChecker as Nu,Subject as _g}from"@vkontakte/videoplayer-shared";var h$=18,Ng=!1;try{Ng=Nu.isSafari&&!!Nu.macVersion&&Nu.macVersion<=h$}catch(i){console.error(i)}var Fu=class{constructor(e){this.bufferFull$=new _g;this.error$=new _g;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:Bg.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)};Ng&&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:Bg.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:p$(t)}}},Fg=Fu;var qu=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 tr,assertNonNullable as Ce,clientChecker as RL,ErrorCategory as Mt,fromEvent as al,getExponentialDelay as sl,isNonNullable as ua,isNullable as Te,now as _s,once as $L,Subject as LL,Subscription as ML,ValueSubject as rr}from"@vkontakte/videoplayer-shared";var F=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Ur=class extends F{};var _i=class extends F{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 Ni=class extends F{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 Fi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Q=class extends F{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var qi=class extends Q{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 Ui=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Hi=class extends F{constructor(e,t){super(e,t),this.data=this.content}};var Zt=class extends Q{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 ji=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Gi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Qi=class extends Q{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 Wi=class extends Q{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Yi=class extends Q{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var zi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ki=class extends Q{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 Xi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ji=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Zi=class extends Q{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ea=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ta=class extends Q{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ra=class extends Q{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 ia=class extends Q{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 f$={ftyp:Ni,moov:Fi,mvhd:qi,moof:Ui,mdat:Hi,sidx:Zt,trak:ji,mdia:zi,mfhd:Zi,tkhd:Ki,traf:ea,tfhd:ta,tfdt:ra,trun:ia,minf:Xi,sv3d:Gi,st3d:Qi,prhd:Wi,proj:Ji,equi:Yi,uuid:_i,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=f$[e];return r?new r(t,new i):new Ur(t,new i)}};var Lt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{this.index[t.type]??=[],this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var g$=new TextDecoder("ascii"),S$=i=>g$.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",v$=i=>{let e=new Zt(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})},y$=(i,e)=>{let r=new mt().parse(i),a=new Lt(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,c)},T$=i=>{let t=new mt().parse(i),r=new Lt(t),a={},s=r.findAll("uuid");return s.length?s[s.length-1]:a},I$=i=>{let t=new mt().parse(i);return new Lt(t).find("sidx")?.timescale},E$=(i,e)=>{let r=new mt().parse(i),s=new Lt(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},x$=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 Lt(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},qg={validateData:S$,parseInit:x$,getIndexRange:()=>{},parseSegments:v$,parseFeedableSegmentChunk:y$,getChunkEndTime:E$,getServerLatencyTimestamps:T$,getTimescaleFromIndex:I$};var sa=M(He(),1);import{assertNonNullable as Hu,isNonNullable as Gg,isNullable as k$}from"@vkontakte/videoplayer-shared";import{assertNever as P$}from"@vkontakte/videoplayer-shared";var Ug={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"}},Hg=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=aa(i,t),a=r in Ug,s=a?Ug[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=aa(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}},aa=(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},Qe=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return aa(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:P$(e)}},er=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Hg(r);if(!e(a))return;a.type==="master"&&er(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},jg=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Hg(i);return er(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Qe(o,n):s===17026?t=Qe(o,n):s===17029&&(r=Qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Qg=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],w$=[231,22612,22743,167,171,163,160,175],A$=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,d=!1,c=0;return er(i,({tag:p,type:m,value:f,valueSize:b})=>{if(p===21419){let g=Qe(f,m);l=aa(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=Qe(f,m):p===17545?a=Qe(f,m):p===21420&&l===475249515?u=Qe(f,m):p===374648427?er(f,({tag:g,type:S,value:k})=>g===30321?(d=Qe(k,S)===1,!1):!0):s&&n&&(0,sa.default)(Qg,p)&&(o=!0),!o}),Hu(e,"Failed to parse webm Segment start"),Hu(t,"Failed to parse webm Segment end"),Hu(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}}}},R$=i=>{if(k$(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},$$=(i,e)=>{let t=!1,r=!1,a=o=>Gg(o.time)&&Gg(o.position),s=[],n;return er(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=Qe(l,u));break;case 183:break;case 241:n&&(n.position=Qe(l,u));break;default:t&&(0,sa.default)(Qg,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}}})},L$=i=>{let e=0,t=!1;try{er(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,sa.default)(w$,r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||=(0,sa.default)([163,160,175],r.tag)),!0):!1)}catch{}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Wg={validateData:jg,parseInit:A$,getIndexRange:R$,parseSegments:$$,parseFeedableSegmentChunk:L$};var na=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Wg;case"mp4":return qg}}throw new ReferenceError(`Unsupported mime type ${i}`)};var tl=M(hS(),1),NS=M(xr(),1),FS=M(RS(),1),qS=M(Br(),1),rl=M(Vr(),1);var $S=M(He(),1),zu=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,$S.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as AL,isNullable as BS}from"@vkontakte/videoplayer-shared";var LS=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var MS=i=>{try{let e=kL(),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 kL(){let i="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",d=`^(?:(?<langtag>${`
|
|
63
64
|
(?<language>${`(?:[a-z]{2,3}(?:-${i})?|[a-z]{4}|[a-z]{5,8})`})
|
|
64
65
|
(-(?<script>[a-z]{4}))?
|
|
65
66
|
(-(?<region>(?:[a-z]{2}|[0-9]{3})))?
|
|
66
67
|
(?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
|
|
67
68
|
(?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
|
|
68
69
|
(?:-(?<privateuse>(?:${e})))?
|
|
69
|
-
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Lv=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},dt=(i,e)=>{let t=i;t=(0,Yu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,Mv.default)(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,Yu.default)(t,n,(o,u)=>$v(s)?o:$v(u)?s:(0,Cv.default)(s,parseInt(u,10),"0"))}return t},Vv=(i,e)=>{let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(y=>y.textContent?.trim()??""),u=(0,Dv.default)(o,0)??"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),p=d?new Date(d).getTime():void 0,h,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),v=s.getElementsByTagName("vk:Attrs")[0]?.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)h=Lv(f);else if(b){let y=Lv(b);Rv(y)&&(h=y)}else v&&(h=parseInt(v,10));let k=0,E=s.getAttribute("profiles")?.split(",")??[];for(let y of l){let R=y.getAttribute("id")??"id"+(k++).toString(10),O=y.getAttribute("mimeType")??"",F=y.getAttribute("codecs")??"",_=y.getAttribute("contentType")??O?.split("/")[0],H=y.getAttribute("profiles")?.split(",")??[],S=wv(y.getAttribute("lang")??"")??{},T=y.querySelector("Label")?.textContent?.trim()??void 0,q=y.querySelectorAll("Representation"),ye=y.querySelector("SegmentTemplate"),Ve=y.querySelector("Role")?.getAttribute("value")??void 0,P=_,M={id:R,language:S.language,isDefault:Ve==="main",label:T,codecs:F,hdr:P==="video"&&Wu(F),mime:O,representations:[]};for(let w of q){let K=w.getAttribute("lang")??void 0,te=w.getAttribute("label")??void 0,ht=w.querySelector("BaseURL")?.textContent?.trim()??"",nr=new URL(ht||u,e).toString(),Vt=w.getAttribute("mimeType")??O,V=w.getAttribute("codecs")??F??"",re;if(_==="text"){let Y=w.getAttribute("id")||"",de=S.privateuse?.includes("x-auto")||Y.includes("_auto"),Te=w.querySelector("SegmentTemplate");if(Te){let tt={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},je=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,rt=parseInt(Te.getAttribute("startNumber")??"",10)??1,Ge=parseInt(Te.getAttribute("timescale")??"",10),or=Te.querySelectorAll("SegmentTimeline S")??[],ur=Te.getAttribute("media");if(!ur)continue;let $a=[],La=0,Ma="",lr=0,Wr=rt,oe=0;for(let Oe of or){let Ot=parseInt(Oe.getAttribute("d")??"",10),Re=parseInt(Oe.getAttribute("r")??"",10)||0,mt=parseInt(Oe.getAttribute("t")??"",10);oe=Number.isFinite(mt)?mt:oe;let Bt=Ot/Ge*1e3,cr=oe/Ge*1e3;for(let Qe=0;Qe<Re+1;Qe++){let ft=dt(ur,{...tt,segmentNumber:Wr.toString(10),segmentTime:(oe+Qe*Ot).toString(10)}),dr=(cr??0)+Qe*Bt,zr=dr+Bt;Wr++,$a.push({time:{from:dr,to:zr},url:ft})}oe+=(Re+1)*Ot,La+=(Re+1)*Bt}lr=oe/Ge*1e3,Ma=dt(ur,{...tt,segmentNumber:Wr.toString(10),segmentTime:oe.toString(10)});let Yr={time:{from:lr,to:1/0},url:Ma},it={type:"template",baseUrl:nr,segmentTemplateUrl:ur,initUrl:"",totalSegmentsDurationMs:La,segments:$a,nextSegmentBeyondManifest:Yr,timescale:Ge};re={id:Y,kind:"text",segmentReference:it,profiles:[],duration:h,bitrate:je,mime:"",codecs:"",width:0,height:0,isAuto:de}}else re={id:Y,isAuto:de,kind:"text",url:nr}}else{let Y=w.getAttribute("contentType")??Vt?.split("/")[0]??_,de=y.getAttribute("profiles")?.split(",")??[],Te=parseInt(w.getAttribute("width")??"",10),tt=parseInt(w.getAttribute("height")??"",10),je=parseInt(w.getAttribute("bandwidth")??"",10)/1e3,rt=w.getAttribute("frameRate")??"",Ge=w.getAttribute("quality")??void 0,or=rt?Av(rt):void 0,ur=w.getAttribute("id")??"id"+(k++).toString(10),$a=Y==="video"?`${tt}p`:Y==="audio"?`${je}Kbps`:V,La=`${ur}@${$a}`,Ma=[...E,...H,...de],lr,Wr=w.querySelector("SegmentBase"),oe=w.querySelector("SegmentTemplate")??ye;if(Wr){let it=w.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[Oe,Ot]=it.split("-").map(ft=>parseInt(ft,10)),Re={from:Oe,to:Ot},mt=w.querySelector("SegmentBase")?.getAttribute("indexRange"),[Bt,cr]=mt?mt.split("-").map(ft=>parseInt(ft,10)):[],Qe=mt?{from:Bt,to:cr}:void 0;lr={type:"byteRange",url:nr,initRange:Re,indexRange:Qe}}else if(oe){let it={representationId:w.getAttribute("id")??void 0,bandwidth:w.getAttribute("bandwidth")??void 0},Oe=parseInt(oe.getAttribute("timescale")??"",10),Ot=oe.getAttribute("initialization")??"",Re=oe.getAttribute("media"),mt=parseInt(oe.getAttribute("startNumber")??"",10)??1,Bt=dt(Ot,it);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let cr=oe.querySelectorAll("SegmentTimeline S")??[],Qe=[],ft=0,dr="",zr=0;if(cr.length){let Ca=mt,Be=0;for(let pr of cr){let We=parseInt(pr.getAttribute("d")??"",10),_t=parseInt(pr.getAttribute("r")??"",10)||0,Da=parseInt(pr.getAttribute("t")??"",10);Be=Number.isFinite(Da)?Da:Be;let pn=We/Oe*1e3,iy=Be/Oe*1e3;for(let Va=0;Va<_t+1;Va++){let ay=dt(Re,{...it,segmentNumber:Ca.toString(10),segmentTime:(Be+Va*We).toString(10)}),Rl=(iy??0)+Va*pn,sy=Rl+pn;Ca++,Qe.push({time:{from:Rl,to:sy},url:ay})}Be+=(_t+1)*We,ft+=(_t+1)*pn}zr=Be/Oe*1e3,dr=dt(Re,{...it,segmentNumber:Ca.toString(10),segmentTime:Be.toString(10)})}else if(Rv(h)){let Be=parseInt(oe.getAttribute("duration")??"",10)/Oe*1e3,pr=Math.ceil(h/Be),We=0;for(let _t=1;_t<pr;_t++){let Da=dt(Re,{...it,segmentNumber:_t.toString(10),segmentTime:We.toString(10)});Qe.push({time:{from:We,to:We+Be},url:Da}),We+=Be}zr=We,dr=dt(Re,{...it,segmentNumber:pr.toString(10),segmentTime:We.toString(10)})}let ry={time:{from:zr,to:1/0},url:dr};lr={type:"template",baseUrl:nr,segmentTemplateUrl:Re,initUrl:Bt,totalSegmentsDurationMs:ft,segments:Qe,nextSegmentBeyondManifest:ry,timescale:Oe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Y||!Vt)continue;let Yr={video:"video",audio:"audio",text:"text"}[Y];if(!Yr)continue;P||=Yr,re={id:La,kind:Yr,segmentReference:lr,profiles:Ma,duration:h,bitrate:je,mime:Vt,codecs:V,width:Te,height:tt,fps:or,quality:Ge}}M.language||=K,M.label||=te,M.mime||=Vt,M.codecs||=V,M.hdr||=P==="video"&&Wu(V),M.representations.push(re)}P&&a[P].push(M)}return{dynamic:c,liveAvailabilityStartTime:p,duration:h,streams:a,baseUrls:o}};var Ju=C(Dr(),1);import{videoSizeToQuality as IL}from"@vkontakte/videoplayer-shared";var Ov=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s,streamId:n})=>{let o=(s?Et(s):void 0)??IL({width:e,height:t});return o&&{id:i,quality:o,bitrate:r,size:{width:e,height:t},fps:a,streamId:n}},Bv=({id:i,bitrate:e})=>({id:i,bitrate:e}),_v=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Nv=({language:i,label:e,id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Xu=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Ju.default)(r.split("."),0),isDefault:a}),Zu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Ju.default)(a.split("."),0)}),el=i=>"url"in i,Ae=i=>i.type==="template",na=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var oa=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new qr(0);this.currentSegmentLength$=new qr(0);this.onLastSegment$=new qr(!1);this.fullyBuffered$=new qr(!1);this.playingRepresentation$=new qr(void 0);this.playingRepresentationInit$=new qr(void 0);this.error$=new xL;this.gaps=[];this.subscription=new PL;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ke;this.switchAbortController=new ke;this.destroyAbortController=new ke;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Zt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);le(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Og(this.sourceBuffer),this.subscription.add(tl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Rt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(tl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Rt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,Nu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=Ze(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),a=this.segments.get(t.id),s=this.parsedInitData.get(t.id);le(r,"No init buffer for starting representation"),le(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=Zt(this.destroyAbortController.signal,async function*(e,t=!1){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);le(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(De(s)||De(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),le(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();Vs(n)&&(this.isLive||(this.bufferLimit=1/0,await this.pruneBuffer(n,1/0,!0)),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}}.bind(this));this.seekLive=Zt(this.destroyAbortController.signal,async function*(e){let t=(0,_s.default)(e,u=>u.representations)??[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let u of this.representations.keys()){let l=t.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!Ae(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let r=this.switchingToRepresentationId??this.downloadingRepresentationId,a=this.representations.get(r);le(a);let s=this.segments.get(r);le(s,"No segments for starting representation");let n=this.initData.get(r);if(le(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,a),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));this.fetcher=a,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!l?.dynamic,this.baseUrls=l?.baseUrls??[],this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ke,Zt(this.switchAbortController.signal,async function*(r,a=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);le(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(De(o)||De(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),le(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),a)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();Vs(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ke,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(De(e)||De(this.downloadingRepresentationId)||De(this.playingRepresentationId)||De(this.sourceBuffer)||Vs(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(le(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);this.currentSegmentLength$.next((a?.time.to??0)-(a?.time.from??0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=Ze(this.sourceBuffer.buffered,e),d=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=a.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Nu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=Ze(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if((0,Bs.default)(o,a))l="high";else{let c=(0,Ur.default)(o,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&Ze(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,Ur.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;Vs(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,a=[],s=0,n=t.length-1;do a.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){let t=(0,_s.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,_s.default)(e?.streams[this.kind],r=>r.representations)??[];for(let r of t){if(!r||!Ae(r.segmentReference))return;let a=r.segmentReference.segments.map(u=>({...u,status:"none",size:void 0})),s=this.segments.get(r.id)??[],n=(0,Ur.default)(s,-1)?.time.to??0,o=a?.findIndex(u=>Math.floor(n)>=Math.floor(u.time.from)&&Math.floor(n)<=Math.floor(u.time.to));if(o===-1){this.liveUpdateSegmentIndex=0;let u=this.getActualLiveStartingSegments(r.segmentReference);this.segments.set(r.id,u)}else{let u=a.slice(o+1);this.segments.set(r.id,[...s,...u])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;le(e);let t=this.segments.get(e);if(t?.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){for(let t of this.representations.values()){let r=t.segmentReference;if(!Ae(r))return;let a=this.segments.get(t.id)??[],s=a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(o=>Math.floor(o.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let o=Math.round(e.time.to*r.timescale/1e3).toString(10),u=dt(r.segmentTemplateUrl,{segmentTime:o});a.push({status:"none",time:{from:e.time.to,to:1/0},url:u})}}}findSegmentStartTime(e){let t=this.switchingToRepresentationId??this.downloadingRepresentationId??this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);return r?r.find(s=>s.time.from<=e&&s.time.to>=e)?.time.from??void 0:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),this.sourceBufferTaskQueue?.destroy(),this.gapDetectionIdleCallback&&Oi&&Oi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Oi&&Oi(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(e){if(!(e instanceof DOMException&&e.name==="NotFoundError"))throw e}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let a=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),k=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&k&&this.sourceBuffer&&!(At(this.sourceBuffer.buffered,p)&&At(this.sourceBuffer.buffered,h)))&&g&&k});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,r="auto"){Ae(t.segmentReference)?await this.loadTemplateSegment(e[0],t,r):await this.loadByteRangeSegments(e,t,r)}async loadTemplateSegment(e,t,r="auto"){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Zt(o,async function*(){let c=rl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=await this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Os(),!c)return;let d=new DataView(c),p=sa(t.mime);if(!isFinite(a.segment.time.to)){let b=t.segmentReference.timescale;a.segment.time.to=p.getChunkEndTime(d,b)}u&&a.feedingBytes&&l?await Promise.all(l):await this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),na(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ae(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await Zt(n,async function*(){let u=rl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),tl(window,"online").pipe(EL()).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=Os(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),na(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}}prepareByteRangeFetchSegmentParams(e,t){if(Ae(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Ur.default)(e,0).byte.from,to:(0,Ur.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Os(),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:Rt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ae(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Os();let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Rt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Bs.default)(e,t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!this.activeSegments.size)return;let n=this.representations.get(t);if(n)for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let l=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=sa(n.mime).parseFeedableSegmentChunk(l,this.isLive);c?.byteLength&&(u.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}async onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:a,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId!==t)continue;if(s.aborted){n();continue}let c=l.byte.from-r,d=l.byte.to-r,p=d-c+1,h=c<a,f=d<=a;if(!h)continue;let b=sa(o.mime);if(l.status==="downloading"&&f){l.status="downloaded";let g=new DataView(e.buffer,e.byteOffset+c,p);await this.sourceBufferTaskQueue.append(g,s)&&!s.aborted?this.onSegmentFullyAppended(u,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(l.status==="downloading"||l.status==="partially_fed")&&(u.loadedBytes=Math.min(p,a-c),u.loadedBytes>u.feedingBytes)){let g=new DataView(e.buffer,e.byteOffset+c+u.feedingBytes,u.loadedBytes-u.feedingBytes),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)):n())}}}onSegmentFullyAppended(e,t){this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(le(this.sourceBuffer),At(this.sourceBuffer.buffered,e.segment.time.from,100)&&At(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Rt.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",el(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");le(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of 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=Ou(()=>(0,Fv.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?Zt(this.destroyAbortController.signal,async function*(){let o=rl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,sa(e.mime),a)).then(async o=>{if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ae(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Rt.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||!this.playingRepresentationId||De(e)||this.sourceBuffer.updating)return!1;let a=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{if(s>=t)return a;a.push({...u.time}),a=n(a);let l=el(u)?u.size??0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,Bs.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(a.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return a.length?(await Promise.all(a.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||De(e)?0:Ze(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){le(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=Ou(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Rt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(De(this.sourceBuffer)||De(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=100;for(let r of 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(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var ua=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var qv=i=>{let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e??void 0,a=t===null?void 0:{1:!0,0:!1}[t]??void 0;return{type:r,reused:a}};import{abortable as la,assertNever as Hv,fromEvent as jv,merge as kL,now as ca,Subscription as AL,Subject as Gv,ValueSubject as il,flattenObject as Hr,ErrorCategory as jr}from"@vkontakte/videoplayer-shared";var Uv=i=>{let e=new URL(i);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Fs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new il(void 0);this.lastConnectionReused$=new il(void 0);this.lastRequestFirstBytes$=new il(void 0);this.recoverableError$=new Gv;this.error$=new Gv;this.abortAllController=new ke;this.subscription=new AL;this.fetchManifest=la(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ua(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Uv(r));let a=yield this.doFetch(r,{signal:this.abortAllController.signal}).catch(Ns);return a?(t.log("success",Hr({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(a.headers),a.text()):(t.error("error",Hr({url:r,message:"No data in request manifest"})),t.end(),null)}.bind(this));this.fetch=la(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){let l=e,c=new Headers,d=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let S=new URL(l,location.href);S.searchParams.append("bytes",`${r.from}-${r.to}`),l=S.toString();break}default:Hv(t)}this.requestQuic&&(l=ua(l));let p=this.abortAllController.signal,h;if(n){let S=new ke;if(h=kL(jv(this.abortAllController.signal,"abort"),jv(n,"abort")).subscribe(()=>{try{S.abort()}catch(T){Ns(T)}}),this.abortAllController.signal.aborted||n.aborted)try{S.abort()}catch(T){Ns(T)}p=S.signal}let f=ca();d.log("startRequest",Hr({url:l,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:f}));let b=yield this.doFetch(l,{priority:s,headers:c,signal:p}),g=ca();if(!b)return d.error("error",{message:"No response in request"}),d.end(),h?.unsubscribe(),null;if(this.throughputEstimator?.addRawRtt(g-f),!b.ok||!b.body){h?.unsubscribe();let S=`Fetch error ${b.status}: ${b.statusText}`;return d.error("error",{message:S}),d.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){h?.unsubscribe();let S=ca(),T={requestStartedAt:f,requestEndedAt:S,duration:S-f};return d.log("endRequest",Hr(T)),d.end(),b.arrayBuffer()}let[v,k]=b.body.tee(),E=v.getReader();o&&this.throughputEstimator?.trackStream(k,u);let A=0,y=new Uint8Array(0),R=!1,O=S=>{h?.unsubscribe(),R=!0,Ns(S)},F=la(p,async function*({done:S,value:T}){if(A===0&&this.lastRequestFirstBytes$.next(ca()-f),p.aborted){h?.unsubscribe();return}if(!S&&T){let q=new Uint8Array(y.length+T.length);q.set(y),q.set(T,y.length),y=q,A+=T.byteLength,a?.(new DataView(y.buffer),A),yield E?.read().then(F,O)}}.bind(this));yield E?.read().then(F,O),h?.unsubscribe();let _=ca(),H={failed:R,requestStartedAt:f,requestEndedAt:_,duration:_-f};return R?(d.error("endRequest",Hr(H)),d.end(),null):(d.log("endRequest",Hr(H)),d.end(),y.buffer)}.bind(this));this.fetchByteRangeRepresentation=la(this.abortAllController.signal,async function*(e,t,r){if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=e.indexRange??t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let 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,h,f);return{init:h,dataView:new DataView(d),segments:g}}.bind(this));this.fetchTemplateRepresentation=la(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),a=yield this.fetch(r,{priority:t,measureThroughput:!1});return a?{init:null,segments:e.segments.map(n=>({...n,status:"none",size:void 0})),dataView:new DataView(a)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=a,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=qv(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:Hv(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}async doFetch(e,t){try{let r=await kt(e,t);if(r.ok)return r;let a=await r.text(),s=parseInt(a);switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:jr.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:jr.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:jr.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:jr.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:jr.FATAL})}}catch(r){throw this.error$.next({id:"GeneralVideoDataFetchError",message:r.toString(),category:jr.FATAL}),r}}},Ns=i=>{if(!na(i))throw i};var er=(i,e,t)=>t*e+(1-t)*i,al=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Qv=(i,e,t,r)=>{let a=0,s=t,n=al(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 wL,ValueSubject as Wv}from"@vkontakte/videoplayer-shared";var $t=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 Wv(e.initial),this.debounced$=new Wv(e.initial);let t=e.label??"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ue(`raw_${t}`),this.smoothedSeries$=new ue(`smoothed_${t}`),this.reportedSeries$=new ue(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,r++);this.takenMeasures=r,t/=r;let a=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*a,n=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(wL(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}};var qs=class extends $t{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=er(this.slow,e,this.params.emaAlphaSlow),this.fast=er(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Us=class extends $t{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=al(this.pastMeasures,this.takenMeasures);this.emaSmoothed=er(this.emaSmoothed,e,this.params.emaAlpha);let r=Qv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Hs=class extends $t{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?er(this.smoothed,t,this.params.emaAlpha):t}};var tr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new qs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Us({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Hs({initial:e,label:"liveEdgeDelay",...t})}};var sl=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};import{isNullable as RL,ValueSubject as $L}from"@vkontakte/videoplayer-shared";var da=class i{constructor(e,t){this.currentRepresentation$=new $L(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(!RL(e))for(let t of this.representations)for(let r of t){let a=r.segmentReference,s=a.segments.length,n=a.segments[0].time.from,o=a.segments[s-1].time.to;if(e<n||e>o)continue;let u=a.segments.find(l=>l.time.from<=e&&l.time.to>=e);!u||this.currentSegment?.time.from===u.time.from&&this.currentSegment.time.to===u.time.to||(this.currentSegment=u,this.currentRepresentation$.next({...r,label:"Live Text",language:"ru",isAuto:!0,url:new URL(u.url,a.baseUrl).toString()}))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e??[]){let r=i.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!e?.some(t=>i.filterRepresentations(t.representations))}static filterRepresentations(e){return e?.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ae(t.segmentReference))}};var _L=["timeupdate","progress","play","seeked","stalled","waiting"],NL=["timeupdate","progress","loadeddata","playing","seeked"];var Qs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Kv;this.representationSubscription=new Kv;this.state$=new $("none");this.currentVideoRepresentation$=new W(void 0);this.currentVideoRepresentationInit$=new W(void 0);this.currentAudioRepresentation$=new W(void 0);this.currentVideoSegmentLength$=new W(0);this.currentAudioSegmentLength$=new W(0);this.error$=new Gs;this.lastConnectionType$=new W(void 0);this.lastConnectionReused$=new W(void 0);this.lastRequestFirstBytes$=new W(void 0);this.currentLiveTextRepresentation$=new W(null);this.isLive$=new W(!1);this.liveDuration$=new W(0);this.liveAvailabilityStartTime$=new W(void 0);this.bufferLength$=new W(0);this.liveLatency$=new W(void 0);this.liveLoadBufferLength$=new W(0);this.livePositionFromPlayer$=new W(0);this.isLowLatency$=new W(!1);this.isActiveLowLatency$=new W(!1);this.currentStallDuration$=new W(0);this.videoLastDataObtainedTimestamp$=new W(0);this.fetcherRecoverableError$=new Gs;this.fetcherError$=new Gs;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Gs;this.gapWatchdogActive=!1;this.destroyController=new ke;this.initManifest=nl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Lt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=nl(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:Lt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=Vv(e??"",this.manifestUrlString)}catch(n){let o=$g(e)??{id:"ManifestParsing",category:Lt.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)&<()?.isTypeSupported?.(`${o}; codecs="${u}"`)||n==="text");t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*(t.duration??0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let a={text:t.streams.text,video:[],audio:[]};for(let n of["video","audio"]){let u=t.streams[n].filter(({mime:d,codecs:p})=>r(n,d,p)),l=new Set(u.map(({codecs:d})=>d)),c=ug(l);if(c&&(a[n]=u.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=this.tuning.preferHDR,p=a.video.some(f=>f.hdr),h=a.video.some(f=>!f.hdr);CL.isHDR&&d&&p?a.video=a.video.filter(f=>f.hdr):h&&(a.video=a.video.filter(f=>!f.hdr))}}let s={...t,streams:a};return this.tracer.log("updateManifestEnd",ha(s)),s}.bind(this));this.initRepresentations=nl(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",ha({initialVideo:e,initialAudio:t,sourceHls:r})),rr(this.manifest),rr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(ir(p,"error").pipe(js(h=>!!this.element?.played.length)).subscribe(h=>{this.error$.next({id:"VideoSource",category:Lt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?tg():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Rs())if(r){let p=document.createElement("source");a(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new oa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],zv(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new oa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}da.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new da(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(ul(1e3).subscribe(p=>{if(this.element?.paused){let h=gs(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,h+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(ar(...NL.map(p=>ir(this.element,p))).pipe(ma(p=>this.element?Ze(this.element.buffered,this.element.currentTime*1e3):0),ol(),OL(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(ar(ir(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(ol()).subscribe(h=>sl(this.element,1))),this.representationSubscription.add(pa({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(js(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(pa({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(js(({isLive:h})=>h),ma(h=>({...h})),ol((h,f)=>f.bufferLength<h.bufferLength),ma(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=gs(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(pa({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,k=h-b,E=1;Math.abs(k)>g&&(E=1+Math.sign(k)*v),sl(this.element,E)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{let f=0;if(h){let b=(this.element?.currentTime??0)*1e3;f=Math.min(...this.bufferManagers.map(v=>v.getLiveSegmentsToLoadState(this.manifest)?.to??b))-b}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(pa({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(BL(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:f})=>{if(rr(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,g=gs(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,A=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,y=isFinite(h)?h:f,R=this.isActiveLowLatency$.getValue(),O=v<=this.tuning.live.activeLiveDelay&&g===0;this.isActiveLowLatency$.next(R&&O);let F="none";if(R?F="active_low_latency":this.isLowLatency$.getValue()&&O?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),F="active_low_latency"):g!==0&&y<k?F="live_forward_buffering":y<k+A&&(F="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),F==="live_forward_buffering"||F==="live_with_target_offset"){let _=p-(k+E),H=this.normolizeLiveOffset(Math.trunc(g+_/b)),S=Math.abs(H-g),T;!h||S<=this.tuning.dashCmafLive.offsetCalculationError?T=g:H>0&&S>this.tuning.dashCmafLive.offsetCalculationError?T=H:T=0,this.manifestUrlString=se(this.manifestUrlString,T,2)}F!=="none"&&F!=="active_low_latency"&&(p=0,this.updateLive())}))}let l=ar(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(ma(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=ar(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(ma(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(ar(this.forceEnded$,pa({allBuffersFull:l,someBufferEnded:c}).pipe(js(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(p=>!p.updating))try{this.source?.endOfStream()}catch(p){this.error$.next({id:"EndOfStream",category:Lt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:p})}})),this.representationSubscription.add(ar(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>this.source?.addEventListener("sourceopen",p)));let d=[this.manifest.duration??0,...(0,ll.default)((0,ll.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let h=[];return p.duration&&h.push(p.duration),Ae(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&h.push(p.segmentReference.totalSegmentsDurationMs),h})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&zv(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=ul(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Lt.WTF,message:"Error handling gaps",thrown:t})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Fs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=tr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){rr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=se(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){rr(this.element),this.state$.setState("running"),this.subscription.add(ar(..._L.map(e=>ir(this.element,e)),ir(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Lt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(ir(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(ir(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&At(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=VL(),s=100,n=this.videoBufferManager?.lastDataObtainedTimestamp??0;this.videoLastDataObtainedTimestamp$.next(n);let o=this.audioBufferManager?.lastDataObtainedTimestamp??0,u=this.videoBufferManager?.getForwardBufferDuration()??0,l=this.audioBufferManager?.getForwardBufferDuration()??0,c=u<s&&a-n>this.tuning.dash.crashOnStallTWithoutDataTimeout,d=this.audioBufferManager&&l<s&&a-o>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((c||d)&&t>this.tuning.dash.crashOnStallTWithoutDataTimeout||t>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${t} ms`);if(this.isLive$.getValue()&&t%5e3===0)this.seekLive(this.liveLastSeekOffset),r.liveLastSeekOffset=this.liveLastSeekOffset;else{let p=this.element.currentTime*1e3;this.videoBufferManager?.maintain(p),this.audioBufferManager?.maintain(p),r.position=p}this.tracer.log("stallIntervalCallback",ha(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=ul(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Lt.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,r)}seek(e,t){rr(this.element),rr(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),At(this.element.buffered,r)||(this.videoBufferManager.abort(),this.audioBufferManager?.abort()),this.videoBufferManager.maintain(r),this.audioBufferManager?.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",ha({requestedPosition:e,forcePrecise:t,position:r}))}stop(){this.tracer.log("stop"),this.element?.querySelectorAll("source").forEach(e=>e.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),this.videoBufferManager?.destroy(),this.videoBufferManager=null,this.audioBufferManager?.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){return this.manifest?.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source?.readyState==="open"&&Array.from(this.source.sourceBuffers).every(e=>!e.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=DL(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ha(t)))}}};var Ws=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ys=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 Jv=`attribute vec2 a_vertex;
|
|
70
|
+
`})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(d,"i")}var Xu=M(Br(),1);import{videoSizeToQuality as wL}from"@vkontakte/videoplayer-shared";var DS=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s,streamId:n})=>{let o=(s?wt(s):void 0)??wL({width:e,height:t});return o&&{id:i,quality:o,bitrate:r,size:{width:e,height:t},fps:a,streamId:n}},CS=({id:i,bitrate:e})=>({id:i,bitrate:e}),VS=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),OS=({language:i,label:e,id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),Ju=({id:i,language:e,label:t,codecs:r,isDefault:a})=>({id:i,language:e,label:t,codec:(0,Xu.default)(r.split("."),0),isDefault:a}),Zu=({id:i,language:e,label:t,hdr:r,codecs:a})=>({id:i,language:e,hdr:r,label:t,codec:(0,Xu.default)(a.split("."),0)}),el=i=>"url"in i,ce=i=>i.type==="template",oa=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var _S=i=>{if(!i?.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=r?.[1]==="-"?-1:1,s={days:e(r?.[5],a),hours:e(r?.[6],a),minutes:e(r?.[7],a),seconds:e(r?.[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},ft=(i,e)=>{let t=i;t=(0,tl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of(0,NS.default)(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,tl.default)(t,n,(o,u)=>BS(s)?o:BS(u)?s:(0,FS.default)(s,parseInt(u,10),"0"))}return t},US=(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,qS.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,T)=>({...y,[T.id]:T.children}),{}),S=b.reduce((y,T)=>({...y,[T.id]:T.getAttribute("duration")}),{});p?c=_S(p):(0,rl.default)(S).filter(y=>y).length&&!u?c=(0,rl.default)(S).reduce((y,T)=>y+(_S(T)??0),0):f&&(c=parseInt(f,10));let k=0,P=s.getAttribute("profiles")?.split(",")??[];for(let y of b.map(T=>T.id))for(let T of g[y]){let D=T.getAttribute("id")??"id"+(k++).toString(10),G=T.getAttribute("mimeType")??"",N=T.getAttribute("codecs")??"",q=T.getAttribute("contentType")??G?.split("/")[0],v=T.getAttribute("profiles")?.split(",")??[],x=MS(T.getAttribute("lang")??"")??{},U=T.querySelector("Label")?.textContent?.trim()??void 0,Ee=T.querySelectorAll("Representation"),Ve=T.querySelector("SegmentTemplate"),w=T.querySelector("Role")?.getAttribute("value")??void 0,V=q,B={id:D,language:x.language,isDefault:w==="main",label:U,codecs:N,hdr:V==="video"&&zu(N),mime:G,representations:[]};for(let R of Ee){let j=R.getAttribute("lang")??void 0,at=R.getAttribute("label")??void 0,lr=R.querySelector("BaseURL")?.textContent?.trim()??"",Ye=new URL(lr||o,e).toString(),C=R.getAttribute("mimeType")??G,re=R.getAttribute("codecs")??N??"",oe;if(q==="text"){let X=R.getAttribute("id")||"",ze=x.privateuse?.includes("x-auto")||X.includes("_auto"),Oe=R.querySelector("SegmentTemplate");if(Oe){let Be={representationId:R.getAttribute("id")??void 0,bandwidth:R.getAttribute("bandwidth")??void 0},st=parseInt(R.getAttribute("bandwidth")??"",10)/1e3,gt=parseInt(Oe.getAttribute("startNumber")??"",10)??1,nt=parseInt(Oe.getAttribute("timescale")??"",10),hn=Oe.querySelectorAll("SegmentTimeline S")??[],cr=Oe.getAttribute("media");if(!cr)continue;let Da=[],Ca=0,Va="",dr=0,zr=gt,ue=0;for(let _e of hn){let _t=parseInt(_e.getAttribute("d")??"",10),Re=parseInt(_e.getAttribute("r")??"",10)||0,St=parseInt(_e.getAttribute("t")??"",10);ue=Number.isFinite(St)?St:ue;let Nt=_t/nt*1e3,pr=ue/nt*1e3;for(let Ke=0;Ke<Re+1;Ke++){let vt=ft(cr,{...Be,segmentNumber:zr.toString(10),segmentTime:(ue+Ke*_t).toString(10)}),hr=(pr??0)+Ke*Nt,Xr=hr+Nt;zr++,Da.push({time:{from:hr,to:Xr},url:vt})}ue+=(Re+1)*_t,Ca+=(Re+1)*Nt}dr=ue/nt*1e3,Va=ft(cr,{...Be,segmentNumber:zr.toString(10),segmentTime:ue.toString(10)});let Kr={time:{from:dr,to:1/0},url:Va},ot={type:"template",baseUrl:Ye,segmentTemplateUrl:cr,initUrl:"",totalSegmentsDurationMs:Ca,segments:Da,nextSegmentBeyondManifest:Kr,timescale:nt};oe={id:X,kind:"text",segmentReference:ot,profiles:[],duration:c,bitrate:st,mime:"",codecs:"",width:0,height:0,isAuto:ze}}else oe={id:X,isAuto:ze,kind:"text",url:Ye}}else{let X=R.getAttribute("contentType")??C?.split("/")[0]??q,ze=T.getAttribute("profiles")?.split(",")??[],Oe=parseInt(R.getAttribute("width")??"",10),Be=parseInt(R.getAttribute("height")??"",10),st=parseInt(R.getAttribute("bandwidth")??"",10)/1e3,gt=R.getAttribute("frameRate")??"",nt=R.getAttribute("quality")??void 0,hn=gt?LS(gt):void 0,cr=R.getAttribute("id")??"id"+(k++).toString(10),Da=X==="video"?`${Be}p`:X==="audio"?`${st}Kbps`:re,Ca=`${cr}@${Da}`,Va=[...P,...v,...ze],dr,zr=R.querySelector("SegmentBase"),ue=R.querySelector("SegmentTemplate")??Ve;if(zr){let ot=R.querySelector("SegmentBase Initialization")?.getAttribute("range")??"",[_e,_t]=ot.split("-").map(vt=>parseInt(vt,10)),Re={from:_e,to:_t},St=R.querySelector("SegmentBase")?.getAttribute("indexRange"),[Nt,pr]=St?St.split("-").map(vt=>parseInt(vt,10)):[],Ke=St?{from:Nt,to:pr}:void 0;dr={type:"byteRange",url:Ye,initRange:Re,indexRange:Ke}}else if(ue){let ot={representationId:R.getAttribute("id")??void 0,bandwidth:R.getAttribute("bandwidth")??void 0},_e=parseInt(ue.getAttribute("timescale")??"",10),_t=ue.getAttribute("initialization")??"",Re=ue.getAttribute("media"),St=parseInt(ue.getAttribute("startNumber")??"",10)??1,Nt=ft(_t,ot);if(!Re)throw new ReferenceError("No media attribute in SegmentTemplate");let pr=ue.querySelectorAll("SegmentTimeline S")??[],Ke=[],vt=0,hr="",Xr=0;if(pr.length){let Oa=St,Ne=0;for(let mr of pr){let Xe=parseInt(mr.getAttribute("d")??"",10),Ft=parseInt(mr.getAttribute("r")??"",10)||0,Ba=parseInt(mr.getAttribute("t")??"",10);Ne=Number.isFinite(Ba)?Ba:Ne;let mn=Xe/_e*1e3,uy=Ne/_e*1e3;for(let _a=0;_a<Ft+1;_a++){let ly=ft(Re,{...ot,segmentNumber:Oa.toString(10),segmentTime:(Ne+_a*Xe).toString(10)}),Dl=(uy??0)+_a*mn,cy=Dl+mn;Oa++,Ke.push({time:{from:Dl,to:cy},url:ly})}Ne+=(Ft+1)*Xe,vt+=(Ft+1)*mn}Xr=Ne/_e*1e3,hr=ft(Re,{...ot,segmentNumber:Oa.toString(10),segmentTime:Ne.toString(10)})}else if(AL(c)){let Ne=parseInt(ue.getAttribute("duration")??"",10)/_e*1e3,mr=Math.ceil(c/Ne),Xe=0;for(let Ft=1;Ft<mr;Ft++){let Ba=ft(Re,{...ot,segmentNumber:Ft.toString(10),segmentTime:Xe.toString(10)});Ke.push({time:{from:Xe,to:Xe+Ne},url:Ba}),Xe+=Ne}Xr=Xe,hr=ft(Re,{...ot,segmentNumber:mr.toString(10),segmentTime:Xe.toString(10)})}let oy={time:{from:Xr,to:1/0},url:hr};dr={type:"template",baseUrl:Ye,segmentTemplateUrl:Re,initUrl:Nt,totalSegmentsDurationMs:vt,segments:Ke,nextSegmentBeyondManifest:oy,timescale:_e}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!X||!C)continue;let Kr={video:"video",audio:"audio",text:"text"}[X];if(!Kr)continue;V||=Kr,oe={id:Ca,kind:Kr,segmentReference:dr,profiles:Va,duration:c,bitrate:st,mime:C,codecs:re,width:Oe,height:Be,fps:hn,quality:nt}}B.language||=j,B.label||=at,B.mime||=C,B.codecs||=re,B.hdr||=V==="video"&&zu(re),B.representations.push(oe)}if(V){let R=a[V].find(j=>j.id===B.id);if(R&&B.representations.every(j=>ce(j.segmentReference)))for(let j of R.representations){let lr=B.representations.find(C=>C.id===j.id)?.segmentReference,Ye=j.segmentReference;Ye.segments.push(...lr.segments),Ye.nextSegmentBeyondManifest=lr.nextSegmentBeyondManifest}else a[V].push(B)}}return{dynamic:u,liveAvailabilityStartTime:d,duration:c,streams:a,baseUrls:n}};var jS=M(He(),1);import{isNonNullable as HS}from"@vkontakte/videoplayer-shared";var ye=(i,e)=>HS(i)&&HS(e)&&i.readyState==="open"&&(0,jS.default)([...i.activeSourceBuffers],e);var la=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new rr(0);this.currentLowLatencySegmentLength$=new rr(0);this.currentSegmentLength$=new rr(0);this.onLastSegment$=new rr(!1);this.fullyBuffered$=new rr(!1);this.playingRepresentation$=new rr(void 0);this.playingRepresentationInit$=new rr(void 0);this.error$=new LL;this.gaps=[];this.subscription=new ML;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ne;this.switchAbortController=new ne;this.destroyAbortController=new ne;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=tr(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Ce(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Fg(this.sourceBuffer),this.subscription.add(al(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o??={id:"SegmentEjection",category:Mt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n},this.error$.next(o)})),this.subscription.add(al(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Mt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ye(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,qu(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=rt(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);Ce(r,"No init buffer for starting representation"),Ce(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchToOld=tr(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);Ce(r,`No such representation ${e}`);let a=this.segments.get(e),s=this.initData.get(e);if(Te(s)||Te(a)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),a=this.segments.get(e),Ce(a,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ye(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();ua(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=tr(this.destroyAbortController.signal,async function*(e){let t=(0,Fs.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);Ce(a);let s=this.segments.get(r);Ce(s,"No segments for starting representation");let n=this.initData.get(r);if(Ce(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}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ne,tr(this.switchAbortController.signal,async function*(r,a=!1){this.switchingToRepresentationId=r;let s=this.representations.get(r);Ce(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(Te(o)||Te(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),Ce(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ye(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();ua(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(){!Te(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 ne,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Te(e)||Te(this.downloadingRepresentationId)||Te(this.playingRepresentationId)||Te(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer)||ua(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Ce(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(l=>e>=l.time.from&&e<l.time.to);ua(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=rt(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)&&qu(this.sourceBuffer.buffered)>=this.bufferLimit){let l=rt(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,Ns.default)(o,a))l="high";else{let d=(0,jr.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&&rt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,jr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,a=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+a}),r=s.time.to;ua(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,Fs.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,Fs.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,jr.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;Ce(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&&Bi&&Bi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Bi&&Bi(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,S=Math.min(this.forwardBufferTarget,this.bufferLimit),k=this.preloadOnly&&p<=r+S||m<=r+S;return(c==="none"||c==="partially_ejected"&&g&&k&&this.sourceBuffer&&ye(this.mediaSource,this.sourceBuffer)&&!($t(this.sourceBuffer.buffered,p)&&$t(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 tr(o,async function*(){let d=sl(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=_s(),!d)return;let c=new DataView(d),p=na(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]),oa(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 tr(n,async function*(){let u=sl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),al(window,"online").pipe($L()).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=_s(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),oa(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,jr.default)(e,0).byte.from,to:(0,jr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:async(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=_s(),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:Mt.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=_s();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:Mt.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,Ns.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=na(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=na(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),S=u.loadedBytes===p?g:b.parseFeedableSegmentChunk(g);S?.byteLength&&(l.status="partially_fed",u.feedingBytes+=S.byteLength,await this.sourceBufferTaskQueue.append(S,s)&&!s.aborted?(u.fedBytes+=S.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):await n())}}}onSegmentFullyAppended(e,t){if(!(Te(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer))){!this.isLive&&RL.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&($t(this.sourceBuffer.buffered,e.segment.time.from,100)&&$t(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Mt.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",el(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=_u(()=>(0,GS.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?tr(this.destroyAbortController.signal,async function*(){let o=sl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,na(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:Mt.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||!ye(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Te(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=el(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,Ns.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||!ye(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||!ye(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||!ye(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Te(e)?0:rt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer)))for(let r of t){let a={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){a=void 0;break}o>r.time.from&&o<r.time.to&&(a.from=o),n<r.time.to&&n>r.time.from&&(a.to=n)}}a&&a.to-a.from>1&&!this.gaps.some(s=>a&&s.from===a.from&&s.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))){for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(a=>this.sourceBuffer&&(Math.round(a.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(a.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=_u(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Mt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Te(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer)||Te(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 ca=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var QS=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 da,assertNever as YS,fromEvent as zS,merge as DL,now as pa,Subscription as CL,ValueSubject as nl,flattenObject as Gr}from"@vkontakte/videoplayer-shared";var WS=i=>{let e=new URL(i);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var qs=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:a=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new nl(void 0);this.lastConnectionReused$=new nl(void 0);this.lastRequestFirstBytes$=new nl(void 0);this.abortAllController=new ne;this.subscription=new CL;this.fetchManifest=da(this.abortAllController.signal,async function*(e){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=ca(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=WS(r));let a=yield Ge(r,{signal:this.abortAllController.signal}).catch(ha);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=da(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 v=new URL(l,location.href);v.searchParams.append("bytes",`${r.from}-${r.to}`),l=v.toString();break}default:YS(t)}this.requestQuic&&(l=ca(l));let p=this.abortAllController.signal,m;if(n){let v=new ne;if(m=DL(zS(this.abortAllController.signal,"abort"),zS(n,"abort")).subscribe(()=>{try{v.abort()}catch(x){ha(x)}}),this.abortAllController.signal.aborted||n.aborted)try{v.abort()}catch(x){ha(x)}p=v.signal}let f=pa();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(ha),g=pa();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 v=`Fetch error ${b.status}: ${b.statusText}`;return c.error("error",{message:v}),c.end(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`))}if(this.onHeadersReceived(b.headers),!a&&!o){m?.unsubscribe();let v=pa(),x={requestStartedAt:f,requestEndedAt:v,duration:v-f};return c.log("endRequest",Gr(x)),c.end(),b.arrayBuffer()}let[S,k]=b.body.tee(),P=S.getReader();o&&this.throughputEstimator?.trackStream(k,u);let A=0,y=new Uint8Array(0),T=!1,D=v=>{m?.unsubscribe(),T=!0,ha(v)},G=da(p,async function*({done:v,value:x}){if(A===0&&this.lastRequestFirstBytes$.next(pa()-f),p.aborted){m?.unsubscribe();return}if(!v&&x){let U=new Uint8Array(y.length+x.length);U.set(y),U.set(x,y.length),y=U,A+=x.byteLength,a?.(new DataView(y.buffer),A),yield P?.read().then(G,D)}}.bind(this));yield P?.read().then(G,D),m?.unsubscribe();let N=pa(),q={failed:T,requestStartedAt:f,requestEndedAt:N,duration:N-f};return T?(c.error("endRequest",Gr(q)),c.end(),null):(c.log("endRequest",Gr(q)),c.end(),y.buffer)}.bind(this));this.fetchByteRangeRepresentation=da(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 S=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,m,f);return{init:m,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=da(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}=QS(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:YS(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ha=i=>{if(!oa(i))throw i};var ir=(i,e,t)=>t*e+(1-t)*i,ol=(i,e)=>i.reduce((t,r)=>t+r,0)/e,KS=(i,e,t,r)=>{let a=0,s=t,n=ol(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 VL,ValueSubject as XS}from"@vkontakte/videoplayer-shared";var Dt=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 XS(e.initial),this.debounced$=new XS(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)&&(VL(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 Us=class extends Dt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ir(this.slow,e,this.params.emaAlphaSlow),this.fast=ir(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Hs=class extends Dt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=ol(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ir(this.emaSmoothed,e,this.params.emaAlpha);let r=KS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var js=class extends Dt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?ir(this.smoothed,t,this.params.emaAlpha):t}};var ar=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Us({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Hs({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 js({initial:e,label:"liveEdgeDelay",...t})}};var ul=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};import{isNullable as OL,ValueSubject as BL}from"@vkontakte/videoplayer-shared";var ma=class i{constructor(e,t){this.currentRepresentation$=new BL(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(!OL(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 GL=["timeupdate","progress","play","seeked","stalled","waiting"],QL=["timeupdate","progress","loadeddata","playing","seeked"];var Qs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new tv;this.representationSubscription=new tv;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 ev;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 ev;this.gapWatchdogActive=!1;this.destroyController=new ne;this.initManifest=ll(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=se(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),this.manifest?.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ct.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=ll(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:Ct.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t=null;try{t=US(e??"",this.manifestUrlString)}catch(n){let o=Cg(e)??{id:"ManifestParsing",category:Ct.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=pg(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);FL.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",ba(s)),s}.bind(this));this.initRepresentations=ll(this.destroyController.signal,async function*(e,t,r){this.tracer.log("initRepresentationsStart",ba({initialVideo:e,initialAudio:t,sourceHls:r})),sr(this.manifest),sr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=c=>{this.representationSubscription.add(nr(c,"error").pipe(fa(p=>!!this.element?.played.length)).subscribe(p=>{this.error$.next({id:"VideoSource",category:Ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:p})}))};this.source=this.tuning.useManagedMediaSource?sg():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&Ms())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 la("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],ZS(t)){let c=this.manifest.streams.audio.reduce((p,m)=>[...p,...m.representations],[]);this.audioBufferManager=new la("audio",this.source,c,n),this.bufferManagers.push(this.audioBufferManager)}ma.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ma(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(cl(1e3).subscribe(c=>{if(this.element?.paused){let p=ys(this.manifestUrlString,2);this.manifestUrlString=se(this.manifestUrlString,p+1e3,2)}}));let u=()=>{this.stallWatchdogSubscription?.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(or(...QL.map(c=>nr(this.element,c))).pipe(ga(c=>this.element?rt(this.element.buffered,this.element.currentTime*1e3):0),Gs(),HL(c=>{c>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(or(nr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Gs()).subscribe(p=>ul(this.element,1))),this.representationSubscription.add(Qr({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(fa(({bufferLength:p,isActiveLowLatency:m})=>m&&!!p)).subscribe(({bufferLength:p})=>this.liveBuffer.next(p))),this.representationSubscription.add(Qr({isActiveLowLatency:this.isActiveLowLatency$.pipe(Gs()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(fa(({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(Qr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(fa(({isLive:p})=>p),ga(p=>({...p})),Gs((p,m)=>m.bufferLength<p.bufferLength),ga(({rtt:p,bufferLength:m,segmentServerLatency:f})=>{let b=ys(this.manifestUrlString,2);return(p/2+m+f+b)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Qr({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,S=p-f,k=1;Math.abs(S)>b&&(k=1+Math.sign(S)*g),ul(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(Qr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(jL(1e3)).subscribe(async({liveLoadBufferLength:p,bufferLength:m})=>{if(sr(this.element),this.isUpdatingLive)return;let f=this.element.playbackRate,b=ys(this.manifestUrlString,2),g=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(g,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*f),k=this.tuning.dashCmafLive.normalizedActualBufferOffset*f,P=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*f,A=isFinite(p)?p:m,y=this.isActiveLowLatency$.getValue(),T=g<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(y&&T);let D="none";if(y?D="active_low_latency":this.isLowLatency$.getValue()&&T?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(G=>G.proceedLowLatencyLive()),D="active_low_latency"):b!==0&&A<S?D="live_forward_buffering":A<S+P&&(D="live_with_target_offset"),isFinite(p)&&(c=p>c?p:c),D==="live_forward_buffering"||D==="live_with_target_offset"){let G=c-(S+k),N=this.normolizeLiveOffset(Math.trunc(b+G/f)),q=Math.abs(N-b),v;!p||q<=this.tuning.dashCmafLive.offsetCalculationError?v=b:N>0&&q>this.tuning.dashCmafLive.offsetCalculationError?v=N:v=0,this.manifestUrlString=se(this.manifestUrlString,v,2)}D!=="none"&&D!=="active_low_latency"&&(c=0,this.updateLive())}))}let l=or(...this.bufferManagers.map(c=>c.fullyBuffered$)).pipe(ga(()=>this.bufferManagers.every(c=>c.fullyBuffered$.getValue()))),d=or(...this.bufferManagers.map(c=>c.onLastSegment$)).pipe(ga(()=>this.bufferManagers.some(c=>c.onLastSegment$.getValue())));if(this.representationSubscription.add(or(this.forceEnded$,Qr({allBuffersFull:l,someBufferEnded:d}).pipe(fa(({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:Ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.representationSubscription.add(or(...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,dl.default)((0,dl.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&&ZS(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")}.bind(this));this.tick=()=>{if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),this.audioBufferManager?.maintain(e),this.liveTextManager?.maintain(e),(this.videoBufferManager.gaps.length||this.audioBufferManager?.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=cl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),t=>{this.error$.next({id:"GapWatchdog",category:Ct.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 qs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=ar.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.bufferEstimator}),this.initTracerSubscription()}async seekLive(e){sr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=se(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await this.videoBufferManager?.seekLive(this.manifest.streams.video),await this.audioBufferManager?.seekLive(this.manifest.streams.audio),this.liveTextManager?.seekLive(this.manifest.streams.text))}initBuffer(){sr(this.element),this.state$.setState("running"),this.subscription.add(or(...GL.map(e=>nr(this.element,e)),nr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(nr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(nr(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&$t(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(!this.element)return;let t=this.currentStallDuration$.getValue();t+=50,this.currentStallDuration$.next(t);let r={timeInWaiting:t},a=UL(),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",ba(r))};this.stallWatchdogSubscription?.unsubscribe(),this.stallWatchdogSubscription=cl(50).subscribe(e,t=>{this.error$.next({id:"StallWatchdogCallback",category:Ct.NETWORK,message:"Can't restore DASH after stall.",thrown:t})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t,r=!1){return{video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e]?.switchTo(t,r)}async seek(e,t){sr(this.element),sr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max(this.videoBufferManager.findSegmentStartTime(e)??e,this.audioBufferManager?.findSegmentStartTime(e)??e),$t(this.element.buffered,r)||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",ba({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=qL(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&(this.bufferManagers?.forEach(e=>e.updateLive(this.manifest)),this.liveTextManager?.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,a=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?a.push(1/0):a.push(o.to));if(a.length){let n=Math.max(...a)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t={...t,gapEnds:a,jumpTo:n,resultCurrentTime:this.element.currentTime},this.tracer.log("jumpGap",ba(t)))}}};var Ws=class{constructor(e,t){this.fov=e,this.orientation=t}};var Ys=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 rv=`attribute vec2 a_vertex;
|
|
70
71
|
attribute vec2 a_texel;
|
|
71
72
|
|
|
72
73
|
varying vec2 v_texel;
|
|
@@ -77,7 +78,7 @@ void main(void) {
|
|
|
77
78
|
// save texel vector to pass to fragment shader
|
|
78
79
|
v_texel = a_texel;
|
|
79
80
|
}
|
|
80
|
-
`;var
|
|
81
|
+
`;var iv=`#ifdef GL_ES
|
|
81
82
|
precision highp float;
|
|
82
83
|
precision highp int;
|
|
83
84
|
#else
|
|
@@ -120,5 +121,6 @@ void main(void) {
|
|
|
120
121
|
// sample using new coordinates
|
|
121
122
|
gl_FragColor = texture2D(u_texture, tc);
|
|
122
123
|
}
|
|
123
|
-
`;var zs=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 Ws(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ys(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(Jv,this.gl.VERTEX_SHADER),r=this.createShader(Xv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,u=t-a,l=e+r,c=t+a,d=e-r,p=t+a;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as UL,now as Zv,Subscription as HL,filter as jL,combine as eS,ValueSubject as tS,isNonNullable as GL}from"@vkontakte/videoplayer-shared";var cl=class{constructor(){this.isSeeked$=new tS(!1);this.isBuffering$=new tS(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new HL}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(eS({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(jL(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(eS({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(UL(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:a,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=Zv(),p=n&&this.currentStallsCount>=n,h=a&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=a+u&&t>=a,f=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(p||h||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,GL(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){this.lastUniqueVideoTrackSelected?.id!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Zv(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},rS=cl;import{combine as QL,map as WL,observeElementSize as YL,Subscription as zL,ValueSubject as dl,noop as KL}from"@vkontakte/videoplayer-shared";var Ks=class{constructor(){this.subscription=new zL;this.pipSize$=new dl(void 0);this.videoSize$=new dl(void 0);this.elementSize$=new dl(void 0);this.pictureInPictureWindowRemoveEventListener=KL}connect({observableVideo:e,video:t}){let r=a=>{let s=a.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(YL(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(QL({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(WL(({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 sr=class{constructor(e){this.subscription=new aM;this.videoState=new $("stopped");this.textTracksManager=new Le;this.droppedFramesManager=new Ps;this.stallsManager=new rS;this.elementSizeManager=new Ks;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new xi;this.audioTrackSwitchHistory=new xi;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state==="requested"&&r?.to!=="paused"&&e!=="stopped"&&t!=="stopped"){let n=this.liveOffset?.getTotalPausedTime()??0;this.seek(a.position-n,a.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&I(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return ZL(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new zs(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.params=e,this.video=he(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(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 Qs({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=be(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:pl.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(iS(c=>!!c.length),sS()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(hl(c=>c.to.state!=="none"),ba());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(ba()),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.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(iS(aS),sS()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(hl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Je(this.video,t.isLooped,a)),this.subscription.add(fe(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add($e(this.video,t.playbackRate,r.playbackRateState$,a)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ce(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(eM(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(Xu(f));let b=[];for(let g of f.representations){let v=Bv(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Zu(h));let f=[];for(let b of h.representations){let g=Ov({...b,streamId:h.id});g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let f of h.representations){let b=_v(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let o=c=>e.error$.next({id:"RepresentationSwitch",category:pl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Js(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$,rM(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,nS.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=[...this.videoTracksMap.keys()].find(v=>this.videoTracksMap.get(v)?.representation.id===h.id);aS(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,f?.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),f){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,v).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ba()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Zu(h))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(ba()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Xu(h))},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{if(c?.is3dVideo&&this.params.tuning.spherical?.enabled)try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(d){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${d}`})}else this.destroy3DScene(),this.params.tuning.spherical?.enabled&&e.is3DVideo$.next(!1)},a)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,a)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,a)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(hl(({to:c})=>c==="ready"),ba());this.subscription.add(Js(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Js(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Js(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,iM(["init"])).pipe(tM(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=e.videoTrack.getState()?.id,n=[...this.videoTracksMap.keys()].find(({id:R})=>R===a),o=t.currentVideoTrack$.getValue(),u=e.videoStream.getState()??(n&&this.videoTracksMap.get(n)?.stream)??this.videoStreamsMap.size===1?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:R})=>R===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=Ze(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:R})=>R===f?.id)??this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let R=Ts(n,c,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,R?.bitrate??-1/0)}if(o){let R=Ts(o,c,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,R?.bitrate??-1/0)}}let v=Pt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),k=r?v??n:n??v,E=b&&vb(k,c,this.audioStreamsMap.get(b)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(k)?.representation,y=E&&this.audioTracksMap.get(E)?.representation;if(A&&y)return[A,y];if(A&&!y&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:pl.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),me(this.video),this.tracer.end()}};var ga=class extends sr{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 oS,interval as sM,map as uS}from"@vkontakte/videoplayer-shared";var va=class extends sr{constructor(e){super(e),this.liveOffset=new ot,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(uS(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(oS({interval:sM(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(oS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(uS(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=Nv(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 cS=C(bs(),1);import{assertNever as Sa,assertNonNullable as lS,debounce as nM,ErrorCategory as Xs,filter as oM,isNonNullable as uM,isNullable as lM,map as Zs,merge as cM,Observable as dM,observableFrom as pM,Subscription as hM,videoSizeToQuality as mM}from"@vkontakte/videoplayer-shared";var He={};var Gr=(i,e)=>new dM(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),ya=class{constructor(e){this.subscription=new hM;this.videoState=new $("initializing");this.textTracksManager=new Le;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),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:Sa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Sa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Sa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Sa(e)}break;default:Sa(t)}};this.video=he(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),me(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Xs.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,cS.default)(import("hls.js").then(a=>{e||(He.Hls=a.default,He.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){lS(He.Hls,"hls.js not loaded"),this.hls=new He.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){lS(He.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Xs.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=be(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.loadedMetadata$,t.loadedMetadataEvent$),s(a.playing$,t.firstFrameEvent$),s(a.canplay$,t.canplay$),s(a.seeked$,t.seekedEvent$),s(a.inPiP$,t.inPiP$),s(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Je(this.video,e.isLooped,r)),this.subscription.add(fe(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add($e(this.video,e.playbackRate,a.playbackRateState$,r)),s(Ce(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Zs(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Gr(this.hls,He.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Xs.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Gr(this.hls,He.Events.MANIFEST_PARSED).pipe(Zs(({levels:l})=>l.reduce((c,d)=>{let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=Et(d.attrs.QUALITY??"")??mM({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(Gr(this.hls,He.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(Gr(this.hls,He.Events.LEVEL_LOADING).pipe(Zs(({url:l})=>Z(l))),t.hostname$),s(Gr(this.hls,He.Events.FRAG_CHANGED),l=>{let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next(((c?.endPTS??0)-(c?.startPTS??0))*1e3),t.currentAudioSegmentLength$.next(((d?.endPTS??0)-(d?.startPTS??0))*1e3)}),this.subscription.add(yt(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:c})=>c===l)?.track,o=Gr(this.hls,He.Events.LEVEL_SWITCHED).pipe(Zs(({level:l})=>n(this.hls.levels[l])));o.pipe(oM(uM)).subscribe(t.currentVideoTrack$,r),this.subscription.add(yt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(lM(l))return;let c=this.trackLevels.get(l.id)?.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=cM(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,pM(["init"])).pipe(nM(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 ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xs.DOM,thrown:t}))||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0)}};var dS="X-Playback-Duration",ml=async i=>{let e=await kt(i),t=await e.text(),r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t)?.[1];return r?parseInt(r,10):e.headers.has(dS)?parseInt(e.headers.get(dS),10):void 0};import{assertNever as yM,combine as TM,debounce as IM,ErrorCategory as tn,filter as EM,filterChanged as xM,isNonNullable as hS,isNullable as rn,map as mS,merge as PM,observableFrom as kM,Subscription as AM,ValueSubject as gl,VideoQuality as wM}from"@vkontakte/videoplayer-shared";var bl=C(To(),1);import{videoSizeToQuality as fM,getExponentialDelay as bM}from"@vkontakte/videoplayer-shared";var gM=i=>{let e=null;if(i.QUALITY&&(e=Et(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=fM({width:t,height:r})}return e??null},vM=(i,e)=>{let t=i.split(`
|
|
124
|
-
`),r=[],a=[];for(let s=0;s<t.length;s++){let n=t[s],o=n.match(/^#EXT-X-STREAM-INF:(.+)/),u=n.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!o&&!u)){if(o){let l=(0,bl.default)(o[1].split(",").map(g=>g.split("="))),c=l.QUALITY??`stream-${l.BANDWIDTH}`,d=gM(l),p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let h=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0,f;if(l.RESOLUTION){let[g,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();d&&r.push({id:c,quality:d,url:b,bandwidth:p,size:f,fps:h})}if(u){let l=(0,bl.default)(u[1].split(",").map(h=>h.split("=")).map(([h,f])=>[h,f.replace(/^"|"$/g,"")])),c=l.URI?.replace(/playlist$/,"subtitles.vtt"),d=l.LANGUAGE,p=l.NAME;c&&d&&a.push({type:"internal",id:d,label:p,language:d,url:c,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},SM=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),fl=0,pS=async(i,e=i,t)=>{let a=await(await kt(i)).text();fl+=1;try{let{qualityManifests:s,textTracks:n}=vM(a,e);return{qualityManifests:s,textTracks:n}}catch{if(fl<=t.manifestRetryMaxCount)return await SM(bM(fl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),pS(i,e,t)}return{qualityManifests:[],textTracks:[]}},en=pS;var Ta=class{constructor(e){this.subscription=new AM;this.videoState=new $("stopped");this.textTracksManager=new Le;this.manifests$=new gl([]);this.liveOffset=new ot;this.manifestStartTime$=new gl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if(a?.to!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else a?.to==="paused"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return yM(t)}};this.params=e,this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:wM.INVARIANT,url:this.params.source.url},en(se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t})=>{t.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:tn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...t])},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:tn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new gl(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:tn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=be(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(fe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ce(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(xM(),mS(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&hS(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{let o=this.video?.getStartDate?.()?.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(TM({startTime:this.manifestStartTime$.pipe(EM(hS)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(mS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=PM(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,kM(["init"])).pipe(IM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),me(this.video)}prepare(){let e=this.selectManifest();if(rn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=t?.to??r??{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=se(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),ml(n).then(o=>{if(!rn(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();if(rn(u)||!isFinite(u))try{kt(n).then(l=>l.text()).then(l=>{let c=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l)?.[1];if(c){let d=new URL(c,n).toString();ml(d).then(p=>{rn(p)||this.maxSeekBackTime$.next(p)})}})}catch{}}})}playIfAllowed(){ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as RM,debounce as $M,ErrorCategory as vl,fromEvent as Sl,isNonNullable as LM,isNullable as MM,map as fS,merge as bS,observableFrom as gS,Subscription as CM,ValueSubject as DM,VideoQuality as VM,clientChecker as OM}from"@vkontakte/videoplayer-shared";var Ia=class{constructor(e){this.subscription=new CM;this.videoState=new $("stopped");this.textTracksManager=new Le;this.manifests$=new DM([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch(a?.to!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return RM(t)}};this.params=e,this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:VM.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),en(se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:vl.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:vl.WTF,message:"HlsProvider internal logic error",thrown:o})},a=be(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(fS(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&LM(l.to)){let h=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let f=this.manifests$.getValue().find(b=>b.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Z(f.url)))}let d=this.params.desiredState.playbackRate.getState(),p=this.params.output.element$.getValue()?.playbackRate;if(d!==p){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(d),h.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(fS(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!OM.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(bS(Sl(o,"addtrack"),Sl(o,"removetrack"),Sl(o,"change"),gS(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=bS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,gS(["init"])).pipe($M(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),me(this.video)}prepare(){let e=this.selectManifest();if(MM(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(){ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var TS=C(Ir(),1),Ea=C(yi(),1);import{assertNever as BM,assertNonNullable as vS,debounce as _M,ErrorCategory as SS,isHigher as NM,isHigherOrEqual as FM,isInvariantQuality as yS,isLowerOrEqual as qM,isNonNullable as UM,merge as HM,observableFrom as jM,Subscription as GM,map as QM}from"@vkontakte/videoplayer-shared";var xa=class{constructor(e){this.subscription=new GM;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Le;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?I(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return BM(e)}};this.params=e,this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),(0,TS.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,Ea.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:SS.WTF,message:"MpegProvider internal logic error",thrown:o})},a=be(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(QM(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Je(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,r)),s(Ce(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&UM(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let u=this.params.desiredState.playbackRate.getState(),l=this.params.output.element$.getValue()?.playbackRate;if(u!==l){let c=this.params.output.element$.getValue();c&&(this.params.desiredState.playbackRate.setState(u),c.playbackRate=u)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=HM(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,jM(["init"])).pipe(_M(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),me(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;vS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];vS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ua(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Z(t))}playIfAllowed(){ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:SS.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=(0,Ea.default)(this.trackUrls).find(o=>!yS(o.track.quality)&&qM(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&FM(n.quality,a.quality)&&(t=a),!t){let o=(0,Ea.default)(this.trackUrls).filter(l=>!yS(l.track.quality)&&NM(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(r=t.quality)}else if(!e){let a=(0,Ea.default)(this.trackUrls).map(s=>s.track);t=Pt(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as ES,debounce as KM,merge as xS,observableFrom as JM,Subscription as XM,map as PS,ValueSubject as ZM,ErrorCategory as Tl,VideoQuality as e0}from"@vkontakte/videoplayer-shared";import{ErrorCategory as WM}from"@vkontakte/videoplayer-shared";var IS=["stun:videostun.mycdn.me:80"],YM=1e3,zM=3,yl=()=>null,an=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=yl;this.externalStopCallback=yl;this.externalErrorCallback=yl;this.options=this.normalizeOptions(t);let 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:IS}]};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:WM.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),YM)}normalizeOptions(e={}){let t={stunServerList:IS,maxRetryNumber:zM,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Pa=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new ZM(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return ES(e)}};this.subscription=new XM,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=he(e.container,e.tuning),this.liveStreamClient=new an(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),me(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Tl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};xS(this.videoState.stateChangeStarted$.pipe(PS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(PS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=be(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(a.timeUpdate$,e.liveTime$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(Ce(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(a.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(fe(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 ES(n.to)}},r)).add(xS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,JM(["init"])).pipe(KM(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:e0.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Tl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Tl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ka=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Aa,assertNonNullable as Mt,ErrorCategory as sn,filter as LS,isNonNullable as MS,isNullable as u0,map as l0,merge as c0,once as d0,Subject as ne,Subscription as CS,ValueSubject as L,flattenObject as DS}from"@vkontakte/videoplayer-shared";import{Observable as t0,map as kS,Subscription as r0,Subject as i0}from"@vkontakte/videoplayer-shared";var AS=i=>new t0(e=>{let t=new r0,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(kS(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(kS(({type:l})=>l!==void 0)),n=new i0,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 a0,Subscription as s0,combine as n0,filter as RS,once as $S}from"@vkontakte/videoplayer-shared";function wS(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as o0}from"@vkontakte/videoplayer-shared";var Qr=class i{constructor(e,t,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.destroyController=new ke;this.subscriptions=new s0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(RS(s=>!!s.type),$S()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){o0.isSafari&&e!=="MPEG"||this.subscriptions.add(n0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(RS(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),$S()).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=wS();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:a0.VIDEO_PIPELINE,message:e?.message??`${i.errorId} exception`,thrown:e})}};var p0={chunkDuration:5e3,maxParallelRequests:5},wa=class{constructor(e){this.current$=new L({type:void 0});this.providerError$=new ne;this.noAvailableProvidersError$=new ne;this.volumeMultiplierError$=new ne;this.providerOutput={position$:new L(0),duration$:new L(1/0),volume$:new L({muted:!1,volume:1}),availableVideoStreams$:new L([]),currentVideoStream$:new L(void 0),availableVideoTracks$:new L([]),currentVideoTrack$:new L(void 0),availableAudioStreams$:new L([]),currentAudioStream$:new L(void 0),availableAudioTracks$:new L([]),currentVideoSegmentLength$:new L(0),currentAudioSegmentLength$:new L(0),isAudioAvailable$:new L(!0),autoVideoTrackLimitingAvailable$:new L(!1),autoVideoTrackLimits$:new L(void 0),currentBuffer$:new L(void 0),isBuffering$:new L(!0),error$:new ne,fetcherError$:new ne,fetcherRecoverableError$:new ne,warning$:new ne,willSeekEvent$:new ne,soundProhibitedEvent$:new ne,seekedEvent$:new ne,loopedEvent$:new ne,endedEvent$:new ne,firstBytesEvent$:new ne,loadedMetadataEvent$:new ne,firstFrameEvent$:new ne,canplay$:new ne,isLive$:new L(void 0),isLowLatency$:new L(!1),canChangePlaybackSpeed$:new L(!0),liveTime$:new L(void 0),liveBufferTime$:new L(void 0),liveLatency$:new L(void 0),availableTextTracks$:new L([]),currentTextTrack$:new L(void 0),hostname$:new L(void 0),httpConnectionType$:new L(void 0),httpConnectionReused$:new L(void 0),inPiP$:new L(!1),inFullscreen$:new L(!1),element$:new L(void 0),elementVisible$:new L(!0),availableSources$:new L(void 0),is3DVideo$:new L(!1),playbackState$:new L("")};this.subscription=new CS;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=sg([...og(this.params.tuning),...ng(this.params.tuning)],this.params.tuning).filter(l=>MS(e.sources[l])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(l=>!(0,Il.default)(a,l)),...t.filter(l=>(0,Il.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",DS(s)),this.screenFormatsIterator=new ka(s);let n=[...Lu(!0),...Lu(!1)];this.chromecastFormatsIterator=new ka(n.filter(l=>MS(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Qr.isSupported()&&(this.volumeMultiplierManager=new Qr(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(u0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:sn.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 Aa(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 Mt(o),new ga({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new va({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Mt(o),_r||!this.params.tuning.useHlsJs?new Ia({...n,source:o}):new ya({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Ta({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Mt(o),new xa({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Cb({...n,source:o,config:{...p0,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Mt(o),new Pa({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 Aa(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 Mt(o),new Si({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 Aa(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Aa(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 Aa(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,OS.default)((0,VS.default)(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new CS,t=!1,r=0;return e.add(c0(this.providerOutput.error$.pipe(LS(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),AS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(l0(a=>({id:`ProviderHangup:${a}`,category:sn.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let a=this.params.desiredState.playbackState.transitionEnded$.pipe(LS(({to:s})=>s==="playing"),d0()).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===sn.NETWORK,u=a.category===sn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n={...n,isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c},c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s??"SCREEN")}this.tracer.error("providerError",DS(n))})),e}};import{fromEvent as nn,once as h0,combine as m0,Subscription as BS,ValueSubject as El,map as f0,filter as b0,isNonNullable as on,now as we,safeStorage as xl}from"@vkontakte/videoplayer-shared";var g0=5e3,_S="one_video_throughput",NS="one_video_rtt",Ra=window.navigator.connection,FS=()=>{let i=Ra?.downlink;if(on(i)&&i!==10)return i*1e3},qS=()=>{let i=Ra?.rtt;if(on(i)&&i!==3e3)return i},US=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Pl=class i{constructor(e){this.subscription=new BS;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(_S)||(e.useBrowserEstimation?FS():void 0)||g0,r=i.load(NS)??(e.useBrowserEstimation?qS():void 0)??0;if(this.throughput$=new El(t),this.rtt$=new El(r),this.rttAdjustedThroughput$=new El(US(t,r,e.rttPenaltyRequestSize)),this.throughput=tr.getSmoothedValue(t,-1,e),this.rtt=tr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=FS();n&&this.throughput.next(n);let o=qS();on(o)&&this.rtt.next(o)};Ra&&"onchange"in Ra&&this.subscription.add(nn(Ra,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{xl.set(_S,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{xl.set(NS,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(m0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(f0(({throughput:a,rtt:s})=>US(a,s,e.rttPenaltyRequestSize)),b0(a=>{let s=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(a-s)/s>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=we(),a=new BS;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(nn(e,"progress").pipe(h0()).subscribe(s=>{t=s.loaded,r=we()}));break;case 1:case 0:a.add(nn(e,"loadstart").subscribe(()=>{t=0,r=we()}));break}a.add(nn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=we(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=we(),n=0,o=we(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,we()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=we();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=we()}else n+=d.byteLength;o=we()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&we()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,we()-o,this.concurrentDownloads.size),n=0,o=we());await r?.read().then(l,u)}};this.concurrentDownloads.add(e),r?.read().then(l,u)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){let t=xl.get(e);if(on(t))return parseInt(t,10)??void 0}},HS=Pl;import{fillWithDefault as v0,VideoQuality as jS}from"@vkontakte/videoplayer-shared";var GS={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:jS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:jS.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!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,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,exposeInternalsToGlobal:!1},QS=i=>({...v0(i,GS),configName:[...i.configName??[],...GS.configName]});import{assertNonNullable as un,combine as pt,ErrorCategory as ln,filter as ce,filterChanged as B,fromEvent as Al,isNonNullable as P0,isNullable as k0,Logger as A0,map as D,mapTo as KS,merge as Ct,now as cn,once as et,Subject as U,Subscription as JS,tap as XS,ValueSubject as x,isHigher as w0,isInvariantQuality as ZS,flattenObject as Dt,throttle as wl,getTraceSubscriptionMethod as ey,Tracer as R0,InternalsExposure as $0}from"@vkontakte/videoplayer-shared";import{merge as S0,map as y0,filter as WS,isNonNullable as T0}from"@vkontakte/videoplayer-shared";var kl=({seekState:i,position$:e})=>S0(i.stateChangeEnded$.pipe(y0(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),WS(T0)),e.pipe(WS(()=>i.getState().state==="none")));import{assertNonNullable as I0}from"@vkontakte/videoplayer-shared";var YS=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return I0(e,`Wrong container or containerId {${i.container}}`),e};import{filter as E0,once as x0}from"@vkontakte/videoplayer-shared";var zS=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(E0(a=>a.length>0),x0()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var dn=class{constructor(e={configName:[]},t=R0.createRootTracer(!1)){this.subscription=new JS;this.logger=new A0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new x(!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 x("stopped"),position$:new x(0),duration$:new x(1/0),muted$:new x(!1),volume$:new x(1),availableVideoStreams$:new x([]),currentVideoStream$:new x(void 0),availableQualities$:new x([]),availableQualitiesFps$:new x({}),currentQuality$:new x(void 0),isAutoQualityEnabled$:new x(!0),autoQualityLimitingAvailable$:new x(!1),autoQualityLimits$:new x({}),availableAudioStreams$:new x([]),currentAudioStream$:new x(void 0),availableAudioTracks$:new x([]),isAudioAvailable$:new x(!0),currentPlaybackRate$:new x(1),currentBuffer$:new x({start:0,end:0}),isBuffering$:new x(!0),isStalled$:new x(!1),isEnded$:new x(!1),isLooped$:new x(!1),isLive$:new x(void 0),canChangePlaybackSpeed$:new x(void 0),atLiveEdge$:new x(void 0),atLiveDurationEdge$:new x(void 0),liveTime$:new x(void 0),liveBufferTime$:new x(void 0),liveLatency$:new x(void 0),currentFormat$:new x(void 0),availableTextTracks$:new x([]),currentTextTrack$:new x(void 0),throughputEstimation$:new x(void 0),rttEstimation$:new x(void 0),videoBitrate$:new x(void 0),hostname$:new x(void 0),httpConnectionType$:new x(void 0),httpConnectionReused$:new x(void 0),surface$:new x("none"),chromecastState$:new x("NOT_AVAILABLE"),chromecastDeviceName$:new x(void 0),intrinsicVideoSize$:new x(void 0),availableSources$:new x(void 0),is3DVideo$:new x(!1),currentVideoSegmentLength$:new x(0),currentAudioSegmentLength$:new x(0)};this.events={inited$:new U,ready$:new U,started$:new U,playing$:new U,paused$:new U,stopped$:new U,willStart$:new U,willResume$:new U,willPause$:new U,willStop$:new U,willDestruct$:new U,watchCoverageRecord$:new U,watchCoverageLive$:new U,managedError$:new U,fatalError$:new U,fetcherRecoverableError$:new U,ended$:new U,looped$:new U,seeked$:new U,willSeek$:new U,autoplaySoundProhibited$:new U,firstBytes$:new U,loadedMetadata$:new U,firstFrame$:new U,canplay$:new U,log$:new U,fetcherError$:new U};this.experimental={element$:new x(void 0),tuningConfigName$:new x([]),enableDebugTelemetry$:new x(!1),dumpTelemetry:ub};if(this.initLogs(),this.tuning=QS(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ua({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new HS(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new $0("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,(h,f)=>{let b=typeof f;return(0,ty.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(a)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:ln.WTF,message:d,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Dt(r)),this.domContainer=YS(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new wa({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&&!Ri()?(this.tracer.log("request play from hidden tab"),Al(document,"visibilitychange").pipe(et()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=r&&!a&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){un(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(ce(r=>r.length>0),et()).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",Dt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){un(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",Dt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return zS(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(k0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return P0(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(Ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(D(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ce(({from:e})=>e==="stopped"),et()).subscribe(()=>{this.initedAt=cn(),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",Dt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:ln.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(et()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Dt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(D(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(n=>n.destination),B()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(pt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(D(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>ZS(u)?1:ZS(l)?-1:w0(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(B()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n?.quality),this.info.videoBitrate$.next(n?.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(B((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(B((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(B()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(B()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(B()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n??{})})).add(e.providerOutput.currentBuffer$.pipe(D(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(pt({hasLiveOffsetByPaused:Ct(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(n=>n.to),B(),D(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(pt({atLiveEdge:pt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),B(),XS(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(pt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),B(),XS(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(n=>n.muted),B()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(n=>n.volume),B()).subscribe(this.info.volume$)).add(kl({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ct(e.providerOutput.endedEvent$.pipe(KS(!0)),e.providerOutput.seekedEvent$.pipe(KS(!1))).pipe(B()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(D(n=>({id:n?`No${n}`:"NoProviders",category:ln.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(et(),D(n=>n??cn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(et(),D(()=>cn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(et(),D(()=>cn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new x(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new x(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ce(({to:n})=>n==="playing"),et()).subscribe(()=>r.next(!1)));let a=0,s=Ct(e.providerOutput.isBuffering$,t,r).pipe(D(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),B());this.subscription.add(s.subscribe(n=>{n?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(Ct(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(Ct(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(D(e=>e?.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new JS;this.subscription.add(t),this.subscription.add(e.current$.pipe(B((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ce(r=>r.length>0),et()).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=Pt(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(Ct(this.desiredState.videoTrack.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(D(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(D(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(D(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){let e=this.providerContainer?.providerOutput;un(this.providerContainer),un(e),ob(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>nb(t)),this.providerContainer.current$.subscribe(({type:t})=>Ei("provider",t)),e.duration$.subscribe(t=>Ei("duration",t)),e.availableVideoTracks$.pipe(ce(t=>!!t.length),et()).subscribe(t=>Ei("tracks",t)),this.events.fatalError$.subscribe(new ue("fatalError")),this.events.managedError$.subscribe(new ue("managedError")),e.position$.subscribe(new ue("position")),e.currentVideoTrack$.pipe(D(t=>t?.quality)).subscribe(new ue("quality")),this.info.currentBuffer$.subscribe(new ue("buffer")),e.isBuffering$.subscribe(new ue("isBuffering"))].forEach(t=>this.subscription.add(t)),Ei("codecs",ag())}initTracerSubscription(){let e=ey(this.tracer.log.bind(this.tracer)),t=ey(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(B()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(pt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ce(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),B((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ce(r=>r>0),B()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ce(r=>r>0),B()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(pt({currentBuffer:this.info.currentBuffer$.pipe(ce(r=>r.end>0),B((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe(B())}).pipe(wl(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(B()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(B()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(B()).subscribe(e("canChangePlaybackSpeed"))).add(pt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ce(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),wl(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(B(),ce(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(B(),ce(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(B()).subscribe(e("muted"))).add(this.info.volume$.pipe(B()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(B(),ce(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(pt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ce(({throughputEstimation:r,rtt:a})=>!!r&&!!a),wl(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(B(),ce(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:ln.DOM,message:String(a)})})};this.subscription.add(Ct(Al(document,"visibilitychange"),Al(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",Dt({quality:t,availableTracks:Dt(e),track:Dt(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 W3,Observable as Y3,Subject as z3,ValueSubject as K3,VideoQuality as J3}from"@vkontakte/videoplayer-shared";var X3=`@vkontakte/videoplayer-core@${Ll}`;export{Oa as ChromecastState,hn as HttpConnectionType,Y3 as Observable,pe as PlaybackState,dn as Player,X3 as SDK_VERSION,z3 as Subject,W3 as Subscription,mn as Surface,Ll as VERSION,K3 as ValueSubject,bt as VideoFormat,J3 as VideoQuality};
|
|
124
|
+
`;var zs=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 Ws(this.params.fov,this.params.orientation),this.cameraRotationManager=new Ys(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(rv,this.gl.VERTEX_SHADER),r=this.createShader(iv,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 zL,now as av,Subscription as KL,filter as XL,combine as sv,ValueSubject as pl,isNonNullable as JL}from"@vkontakte/videoplayer-shared";var hl=class{constructor(){this.isSeeked$=new pl(!1);this.isBuffering$=new pl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new KL;this.severeStallOccurred$=new pl(!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(sv({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(XL(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(sv({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(zL(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=av(),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,JL(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=av(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},nv=hl;import{combine as ZL,map as eM,observeElementSize as tM,Subscription as rM,ValueSubject as ml,noop as iM}from"@vkontakte/videoplayer-shared";var Ks=class{constructor(){this.subscription=new rM;this.pipSize$=new ml(void 0);this.videoSize$=new ml(void 0);this.elementSize$=new ml(void 0);this.pictureInPictureWindowRemoveEventListener=iM}connect({observableVideo:e,video:t}){let r=a=>{let s=a.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(tM(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(ZL({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(eM(({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 ur=class{constructor(e){this.subscription=new cM;this.videoState=new $("stopped");this.droppedFramesManager=new As;this.stallsManager=new nv;this.elementSizeManager=new Ks;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Pi;this.audioTrackSwitchHistory=new Pi;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"),I(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="ready"&&I(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset?.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return nM(e)}}};this.init3DScene=e=>{if(this.scene3D)return;this.scene3D=new zs(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 Le(e.source.url),this.params=e,this.video=he(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ee(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 Qs({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=be(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:fl.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(ov(d=>!!d.length),lv()).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(bl(d=>d.to.state!=="none"),va());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(va()),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(ov(uv),lv()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(bl(d=>d.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(et(this.video,t.isLooped,a)),this.subscription.add(fe(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add($e(this.video,t.playbackRate,r.playbackRateState$,a)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(De(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{if(d==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(oM(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let m=[];for(let f of c.audio){m.push(Ju(f));let b=[];for(let g of f.representations){let S=CS(g);b.push(S),this.audioTracksMap.set(S,{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(Zu(m));let f=[];for(let b of m.representations){let g=DS({...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=VS(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:fl.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(Xs(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$,lM(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,cv.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(S=>this.videoTracksMap.get(S)?.representation.id===m.id);uv(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 S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,S).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(va()).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(Zu(m))},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(va()).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(Ju(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(bl(({to:d})=>d==="ready"),va());this.subscription.add(Xs(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,gl(["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(Xs(u,this.player.state$.stateChangeEnded$,gl(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Xs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,gl(["init"])).pipe(uM(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:T})=>T===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:T})=>T===u.id),d=l&&this.videoStreamsMap.get(l);if(!d)return;let c=rt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(c/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=e.audioStream.getState()??(this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0),b=[...this.audioStreamsMap.keys()].find(({id:T})=>T===f?.id)??this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let T=xs(n,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,T?.bitrate??-1/0)}if(o){let T=xs(o,d,this.audioStreamsMap.get(b)??[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,T?.bitrate??-1/0)}}let S=Rt(d,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),k=r?S??n:n??S,P=b&&Ib(k,d,this.audioStreamsMap.get(b)??[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),A=this.videoTracksMap.get(k)?.representation,y=P&&this.audioTracksMap.get(P)?.representation;if(A&&y)return[A,y];if(A&&!y&&this.audioTracksMap.size===0)return[A,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.liveOffset?.pause(),this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fl.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),me(this.video),this.tracer.end()}};var ya=class extends ur{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as dv,interval as dM,map as pv}from"@vkontakte/videoplayer-shared";var Ta=class extends ur{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(pv(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(dv({interval:dM(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(dv({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(pv(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=OS(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 mv=M(vs(),1);import{assertNever as Ia,assertNonNullable as hv,debounce as pM,ErrorCategory as Js,filter as hM,isNonNullable as mM,isNullable as fM,map as Zs,merge as bM,Observable as gM,observableFrom as SM,Subscription as vM,videoSizeToQuality as yM}from"@vkontakte/videoplayer-shared";var We={};var Wr=(i,e)=>new gM(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Ea=class{constructor(e){this.subscription=new vM;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:Ia(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ia(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ia(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ia(e)}break;default:Ia(t)}};this.textTracksManager=new Le(e.source.url),this.video=he(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(ee(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),me(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Js.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,mv.default)(import("hls.js").then(a=>{e||(We.Hls=a.default,We.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){hv(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){hv(We.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Js.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=be(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(et(this.video,e.isLooped,r)),this.subscription.add(fe(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add($e(this.video,e.playbackRate,a.playbackRateState$,r)),s(De(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Zs(l=>l.to)),this.params.output.playbackState$),this.subscription.add(Wr(this.hls,We.Events.ERROR).subscribe(l=>{l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Js.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${l.err?.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Wr(this.hls,We.Events.MANIFEST_PARSED).pipe(Zs(({levels:l})=>l.reduce((d,c)=>{let p=c.name||c.height.toString(10),{width:m,height:f}=c,b=wt(c.attrs.QUALITY??"")??yM({width:m,height:f});if(!b)return d;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:c.bitrate/1e3,size:{width:m,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:c}),d.push(S),d},[]))),t.availableVideoTracks$),s(Wr(this.hls,We.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(Wr(this.hls,We.Events.LEVEL_LOADING).pipe(Zs(({url:l})=>ee(l))),t.hostname$),s(Wr(this.hls,We.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=Wr(this.hls,We.Events.LEVEL_SWITCHED).pipe(Zs(({level:l})=>n(this.hls.levels[l])));o.pipe(hM(mM)).subscribe(t.currentVideoTrack$,r),this.subscription.add(xt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{if(fM(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=bM(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,SM(["init"])).pipe(pM(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 ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Js.DOM,thrown:t}))||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0)}};var fv="X-Playback-Duration",Sl=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(fv)?parseInt(e.headers.get(fv),10):void 0};import{assertNever as LM,combine as MM,debounce as DM,ErrorCategory as rn,filter as CM,filterChanged as VM,isNonNullable as Sv,isNullable as an,map as vv,merge as OM,observableFrom as BM,Subscription as _M,ValueSubject as Tl,VideoQuality as NM}from"@vkontakte/videoplayer-shared";var yl=M(Eo(),1);import{videoSizeToQuality as TM,getExponentialDelay as IM}from"@vkontakte/videoplayer-shared";var EM=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=TM({width:t,height:r})}return e??null},xM=(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,yl.default)(o[1].split(",").map(g=>g.split("="))),d=l.QUALITY??`stream-${l.BANDWIDTH}`,c=EM(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,S]=l.RESOLUTION.split("x").map(k=>parseInt(k,10));g&&S&&(f={width:g,height:S})}let b=new URL(t[++s],e).toString();c&&r.push({id:d,quality:c,url:b,bandwidth:p,size:f,fps:m})}if(u){let l=(0,yl.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}},PM=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),vl=0,bv=async(i,e=i,t,r)=>{let s=await(await Ge(i,r)).text();vl+=1;try{let{qualityManifests:n,textTracks:o}=xM(s,e);return{qualityManifests:n,textTracks:o}}catch{if(vl<=t.manifestRetryMaxCount)return await PM(IM(vl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),bv(i,e,t)}return{qualityManifests:[],textTracks:[]}},en=bv;import{isNonNullable as kM,Subscription as wM,throttle as AM,ValueSubject as gv,Subject as RM,ErrorCategory as $M}from"@vkontakte/videoplayer-shared";var tn=class{constructor(e,t,r,a,s){this.subscription=new wM;this.abortControllers={destroy:new ne,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new gv(null);this.getCurrentTime$=new gv(null);this.error$=new RM;this.params={fetchManifestData:r,sourceUrl:a,downloadThreshold:s},this.subscription.add(e.pipe(AM(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(kM(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 ne;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:$M.WTF,thrown:t,message:e})}};var xa=class{constructor(e){this.subscription=new _M;this.videoState=new $("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new Tl([]);this.liveOffset=new dt;this.manifestStartTime$=new Tl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let 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"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return LM(t)}};this.params=e,this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:NM.INVARIANT,url:this.params.source.url};let t=(r,a)=>en(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 tn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Le(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:a})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:rn.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:rn.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(ee(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Tl(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:rn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=be(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(fe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,r)),s(De(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(VM(),vv(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&&Sv(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(ee(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(MM({startTime:this.manifestStartTime$.pipe(CM(Sv)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(vv(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=OM(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,BM(["init"])).pipe(DM(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),me(this.video)}prepare(){let e=this.selectManifest();if(an(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=se(a.toString(),this.liveOffset.getTotalOffset(),s);this.liveTextManager?.prepare(n),this.video.setAttribute("src",n),this.video.load(),Sl(n).then(o=>{if(!an(o))this.maxSeekBackTime$.next(o);else{let u=this.params.source.maxSeekBackTime??this.maxSeekBackTime$.getValue();(an(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();Sl(c).then(p=>{an(p)||this.maxSeekBackTime$.next(p)})}}).catch(()=>{})}})}playIfAllowed(){ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:rn.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=se(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 FM,debounce as qM,ErrorCategory as Il,fromEvent as El,isNonNullable as UM,isNullable as HM,map as yv,merge as Tv,observableFrom as Iv,Subscription as jM,ValueSubject as GM,VideoQuality as QM,clientChecker as WM}from"@vkontakte/videoplayer-shared";var Pa=class{constructor(e){this.subscription=new jM;this.videoState=new $("stopped");this.manifests$=new GM([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let 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"?I(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):a?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):a?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return FM(t)}};this.textTracksManager=new Le(e.source.url),this.params=e,this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:QM.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(ee(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),en(se(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Il.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=a?.to?.id??t.getState()?.id??"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(u=>u.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Il.WTF,message:"HlsProvider internal logic error",thrown:o})},a=be(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(yv(o=>o.to)),this.params.output.playbackState$),this.subscription.add(et(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&UM(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(ee(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(yv(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)),!WM.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Tv(El(o,"addtrack"),El(o,"removetrack"),El(o,"change"),Iv(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Tv(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Iv(["init"])).pipe(qM(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),me(this.video)}prepare(){let e=this.selectManifest();if(HM(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(){ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Il.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var kv=M(xr(),1),ka=M(Vr(),1);import{assertNever as YM,assertNonNullable as Ev,debounce as zM,ErrorCategory as xv,isHigher as KM,isHigherOrEqual as XM,isInvariantQuality as Pv,isLowerOrEqual as JM,isNonNullable as ZM,merge as eD,observableFrom as tD,Subscription as rD,map as iD}from"@vkontakte/videoplayer-shared";var wa=class{constructor(e){this.subscription=new rD;this.videoState=new $("stopped");this.trackUrls={};this.textTracksManager=new Le;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0}),n.to&&this.params.desiredState.autoVideoTrackLimits.getState()?.max!==this.trackUrls[n.to.id]?.track?.quality&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch(r?.to!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?I(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return YM(e)}};this.params=e,this.video=he(e.container,e.tuning),this.params.output.element$.next(this.video),(0,kv.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,ka.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:xv.WTF,message:"MpegProvider internal logic error",thrown:o})},a=be(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(iD(o=>o.to)),this.params.output.playbackState$),this.subscription.add(et(this.video,t.isLooped,r)),this.subscription.add(fe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add($e(this.video,t.playbackRate,a.playbackRateState$,r)),s(De(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),I(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),I(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&ZM(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=eD(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,tD(["init"])).pipe(zM(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),me(this.video)}prepare(){let e=this.params.desiredState.videoTrack.getState()?.id;Ev(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Ev(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=ca(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ee(t))}playIfAllowed(){ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:xv.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){let t,r=e;if(e&&this.params.output.currentVideoTrack$.getValue()?.quality!==e){let a=(0,ka.default)(this.trackUrls).find(o=>!Pv(o.track.quality)&&JM(o.track.quality,e))?.track,s=this.params.desiredState.videoTrack.getState()?.id,n=this.trackUrls[s??"0"]?.track;if(a&&n&&XM(n.quality,a.quality)&&(t=a),!t){let o=(0,ka.default)(this.trackUrls).filter(l=>!Pv(l.track.quality)&&KM(l.track.quality,e)),u=o.length;u&&(t=o[u-1].track)}t&&(r=t.quality)}else if(!e){let a=(0,ka.default)(this.trackUrls).map(s=>s.track);t=Rt(a,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as Av,debounce as oD,merge as Rv,observableFrom as uD,Subscription as lD,map as $v,ValueSubject as cD,ErrorCategory as Pl,VideoQuality as dD}from"@vkontakte/videoplayer-shared";import{ErrorCategory as aD}from"@vkontakte/videoplayer-shared";var wv=["stun:videostun.mycdn.me:80"],sD=1e3,nD=3,xl=()=>null,sn=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=xl;this.externalStopCallback=xl;this.externalErrorCallback=xl;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:wv}]};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:aD.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),sD)}normalizeOptions(e={}){let t={stunServerList:wv,maxRetryNumber:nD,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Aa=class{constructor(e){this.videoState=new $("stopped");this.maxSeekBackTime$=new cD(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),I(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):r?.to==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):r?.to==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Av(e)}};this.subscription=new lD,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=he(e.container,e.tuning),this.liveStreamClient=new sn(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),me(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Pl.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Rv(this.videoState.stateChangeStarted$.pipe($v(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe($v(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=be(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(De(this.video),this.params.output.elementVisible$),this.subscription.add(a.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(a.canplay$.subscribe(()=>{this.videoState.getTransition()?.to==="ready"&&this.videoState.setState("ready")},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(fe(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 Av(n.to)}},r)).add(Rv(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,uD(["init"])).pipe(oD(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(ee(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:dD.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Pl.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ge(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Pl.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ra=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 $a,assertNonNullable as Vt,ErrorCategory as nn,filter as Ov,isNonNullable as Bv,isNullable as vD,map as yD,merge as TD,once as ID,Subject as Ie,Subscription as _v,ValueSubject as L,flattenObject as Nv}from"@vkontakte/videoplayer-shared";import{Observable as pD,map as Lv,Subscription as hD,Subject as mD}from"@vkontakte/videoplayer-shared";var Mv=i=>new pD(e=>{let t=new hD,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Lv(({from:l,to:d})=>`${l}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Lv(({type:l})=>l!==void 0)),n=new mD,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 fD,Subscription as bD,combine as gD,filter as Cv,once as Vv}from"@vkontakte/videoplayer-shared";function Dv(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as SD}from"@vkontakte/videoplayer-shared";var Yr=class i{constructor(e,t,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=a;this.destroyController=new ne;this.subscriptions=new bD;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(Cv(s=>!!s.type),Vv()).subscribe(({type:s})=>this.subscribe(s)))}static{this.errorId="VolumeMultiplierManager"}subscribe(e){SD.isSafari&&e!=="MPEG"||this.subscriptions.add(gD({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Cv(({playbackState:t,video:r,volume:{muted:a,volume:s}})=>t==="playing"&&!!r&&!a&&!!s),Vv()).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=Dv();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:fD.VIDEO_PIPELINE,message:e?.message??`${i.errorId} exception`,thrown:e})}};var ED={chunkDuration:5e3,maxParallelRequests:5},La=class{constructor(e){this.current$=new L({type:void 0});this.providerError$=new Ie;this.noAvailableProvidersError$=new Ie;this.volumeMultiplierError$=new Ie;this.providerOutput={position$:new L(0),duration$:new L(1/0),volume$:new L({muted:!1,volume:1}),availableVideoStreams$:new L([]),currentVideoStream$:new L(void 0),availableVideoTracks$:new L([]),currentVideoTrack$:new L(void 0),availableAudioStreams$:new L([]),currentAudioStream$:new L(void 0),availableAudioTracks$:new L([]),currentVideoSegmentLength$:new L(0),currentAudioSegmentLength$:new L(0),isAudioAvailable$:new L(!0),autoVideoTrackLimitingAvailable$:new L(!1),autoVideoTrackLimits$:new L(void 0),currentBuffer$:new L(void 0),isBuffering$:new L(!0),error$:new 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 L(void 0),isLowLatency$:new L(!1),canChangePlaybackSpeed$:new L(!0),liveTime$:new L(void 0),liveBufferTime$:new L(void 0),liveLatency$:new L(void 0),availableTextTracks$:new L([]),currentTextTrack$:new L(void 0),hostname$:new L(void 0),httpConnectionType$:new L(void 0),httpConnectionReused$:new L(void 0),inPiP$:new L(!1),inFullscreen$:new L(!1),element$:new L(void 0),elementVisible$:new L(!0),availableSources$:new L(void 0),is3DVideo$:new L(!1),playbackState$:new L(""),getCurrentTime$:new L(null)};this.subscription=new _v;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=lg([...dg(this.params.tuning),...cg(this.params.tuning)],this.params.tuning).filter(l=>Bv(e.sources[l])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(l=>!(0,kl.default)(a,l)),...t.filter(l=>(0,kl.default)(a,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",Nv(s)),this.screenFormatsIterator=new Ra(s);let n=[...Du(!0),...Du(!1)];this.chromecastFormatsIterator=new Ra(n.filter(l=>Bv(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&Yr.isSupported()&&(this.volumeMultiplierManager=new Yr(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(vD(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:nn.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 $a(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 Vt(o),new ya({...n,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Vt(o),new Ta({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Vt(o),qr||!this.params.tuning.useHlsJs?new Pa({...n,source:o}):new Ea({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Vt(o),new xa({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Vt(o),new wa({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Vt(o),new Bb({...n,source:o,config:{...ED,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Vt(o),new Aa({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 $a(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 Vt(o),new Ti({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 $a(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return $a(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 $a(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,qv.default)((0,Fv.default)(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new _v,t=!1,r=0;return e.add(TD(this.providerOutput.error$.pipe(Ov(a=>!this.params.tuning.ignoreAudioRendererError||!a.message||!/AUDIO_RENDERER_ERROR/ig.test(a.message))),Mv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(yD(a=>({id:`ProviderHangup:${a}`,category:nn.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(Ov(({to:s})=>s==="playing"),ID()).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===nn.NETWORK,u=a.category===nn.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",Nv(n))})),e}};import{fromEvent as on,once as xD,combine as PD,Subscription as Uv,ValueSubject as wl,map as kD,filter as wD,isNonNullable as un,now as Ae,safeStorage as Al}from"@vkontakte/videoplayer-shared";var AD=5e3,Hv="one_video_throughput",jv="one_video_rtt",Ma=window.navigator.connection,Gv=()=>{let i=Ma?.downlink;if(un(i)&&i!==10)return i*1e3},Qv=()=>{let i=Ma?.rtt;if(un(i)&&i!==3e3)return i},Wv=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Rl=class i{constructor(e){this.subscription=new Uv;this.concurrentDownloads=new Set;this.tuningConfig=e;let t=i.load(Hv)||(e.useBrowserEstimation?Gv():void 0)||AD,r=i.load(jv)??(e.useBrowserEstimation?Qv():void 0)??0;if(this.throughput$=new wl(t),this.rtt$=new wl(r),this.rttAdjustedThroughput$=new wl(Wv(t,r,e.rttPenaltyRequestSize)),this.throughput=ar.getSmoothedValue(t,-1,e),this.rtt=ar.getSmoothedValue(r,1,e),e.useBrowserEstimation){let a=()=>{let n=Gv();n&&this.throughput.next(n);let o=Qv();un(o)&&this.rtt.next(o)};Ma&&"onchange"in Ma&&this.subscription.add(on(Ma,"change").subscribe(a)),a()}this.subscription.add(this.throughput.smoothed$.subscribe(a=>{Al.set(Hv,a.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(a=>{Al.set(jv,a.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(PD({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(kD(({throughput:a,rtt:s})=>Wv(a,s,e.rttPenaltyRequestSize)),wD(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 Uv;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(on(e,"progress").pipe(xD()).subscribe(s=>{t=s.loaded,r=Ae()}));break;case 1:case 0:a.add(on(e,"loadstart").subscribe(()=>{t=0,r=Ae()}));break}a.add(on(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=Al.get(e);if(un(t))return parseInt(t,10)??void 0}},Yv=Rl;import{fillWithDefault as RD,VideoQuality as zv}from"@vkontakte/videoplayer-shared";var Kv={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:zv.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:zv.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,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},Xv=i=>({...RD(i,Kv),configName:[...i.configName??[],...Kv.configName]});import{assertNonNullable as ln,combine as bt,ErrorCategory as cn,filter as de,filterChanged as _,fromEvent as Ll,isNonNullable as OD,isNullable as BD,Logger as _D,map as O,mapTo as ty,merge as Ot,now as dn,once as it,Subject as H,Subscription as ry,tap as iy,ValueSubject as E,isHigher as ND,isInvariantQuality as ay,flattenObject as Bt,throttle as Ml,getTraceSubscriptionMethod as sy,Tracer as FD,InternalsExposure as qD}from"@vkontakte/videoplayer-shared";import{merge as $D,map as LD,filter as Jv,isNonNullable as MD}from"@vkontakte/videoplayer-shared";var $l=({seekState:i,position$:e})=>$D(i.stateChangeEnded$.pipe(LD(({to:t})=>t.state==="none"?void 0:(t.position??NaN)/1e3),Jv(MD)),e.pipe(Jv(()=>i.getState().state==="none")));import{assertNonNullable as DD}from"@vkontakte/videoplayer-shared";var Zv=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return DD(e,`Wrong container or containerId {${i.container}}`),e};import{filter as CD,once as VD}from"@vkontakte/videoplayer-shared";var ey=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&t?.getValue().length===0?t.pipe(CD(a=>a.length>0),VD()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t?.getValue().find(r))&&e.startTransitionTo(i)};var pn=class{constructor(e={configName:[]},t=FD.createRootTracer(!1)){this.subscription=new ry;this.logger=new _D;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({}),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:pb,getCurrentTime$:new E(null)};if(this.initLogs(),this.tuning=Xv(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ga({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Yv(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new qD("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,ny.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:cn.WTF,message:c,thrown:u}),u}}}})}initVideo(e){this.config=e;let{container:t,...r}=e;return this.tracer.log("initVideo",Bt(r)),this.domContainer=Zv(e),this.chromecastInitializer.contentId=e.meta?.videoId,this.providerContainer=new La({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"),Ll(document,"visibilitychange").pipe(it()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue(),s=e;return e>=r&&!a&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:a,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){ln(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(de(r=>r.length>0),it()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Bt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){ln(this.providerContainer);let t=this.providerContainer?.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Bt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){return ey(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(BD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return OD(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(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(de(({from:e})=>e==="stopped"),it()).subscribe(()=>{this.initedAt=dn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Bt(n)),n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:cn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(it()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Bt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(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)=>ay(u)?1:ay(l)?-1:ND(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}),_(),iy(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),_(),iy(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(ty(!0)),e.providerOutput.seekedEvent$.pipe(ty(!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:cn.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(it(),O(n=>n??dn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(it(),O(()=>dn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(it(),O(()=>dn()-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(de(({to:n})=>n==="playing"),it()).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 ry;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(de(r=>r.length>0),it()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.wasSetStartedQuality=!0;let r=this.explicitInitialQuality??this.desiredState.videoTrack.getState()?.quality;r&&(t=e.find(({quality:a})=>a===r),t||this.setAutoQuality(!0)),t||(t=Rt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(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;ln(this.providerContainer),ln(e),db(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(t=>cb(t)),this.providerContainer.current$.subscribe(({type:t})=>xi("provider",t)),e.duration$.subscribe(t=>xi("duration",t)),e.availableVideoTracks$.pipe(de(t=>!!t.length),it()).subscribe(t=>xi("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)),xi("codecs",ug())}initTracerSubscription(){let e=sy(this.tracer.log.bind(this.tracer)),t=sy(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(de(({currentQuality:r,videoBitrate:a})=>!!r&&!!a),_((r,a)=>r.currentQuality===a.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(de(r=>r>0),_()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(de(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(de(r=>r.end>0),_((r,a)=>r.end===a.end&&r.start===a.start)),position:this.info.position$.pipe(_())}).pipe(Ml(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(de(({liveTime:r,liveBufferTime:a})=>!!r&&!!a),Ml(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(_(),de(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(_(),de(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(_(),de(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(bt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(de(({throughputEstimation:r,rtt:a})=>!!r&&!!a),Ml(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(_(),de(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:cn.DOM,message:String(a)})})};this.subscription.add(Ot(Ll(document,"visibilitychange"),Ll(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!e?.released;a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);this.tracer.log("setVideoTrackIdByQuality",Bt({quality:t,availableTracks:Bt(e),track:Bt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as T3,Observable as I3,Subject as E3,ValueSubject as x3,VideoQuality as P3}from"@vkontakte/videoplayer-shared";var k3=`@vkontakte/videoplayer-core@${Vl}`;export{Na as ChromecastState,fn as HttpConnectionType,I3 as Observable,pe as PlaybackState,pn as Player,k3 as SDK_VERSION,E3 as Subject,T3 as Subscription,bn as Surface,Vl as VERSION,x3 as ValueSubject,yt as VideoFormat,P3 as VideoQuality};
|