@vkontakte/videoplayer-core 2.0.105-dev.419be451.0 → 2.0.105-dev.498f6d5a.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/es2018.esm.js CHANGED
@@ -1,40 +1,40 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.105-dev.419be451.0
3
- * Thu, 11 Jul 2024 16:26:35 GMT
2
+ * @vkontakte/videoplayer-core v2.0.105-dev.498f6d5a.0
3
+ * Tue, 23 Jul 2024 11:16:31 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-105/doc/
5
5
  */
6
- var xg=Object.create;var pl=Object.defineProperty;var Pg=Object.getOwnPropertyDescriptor;var Ag=Object.getOwnPropertyNames;var wg=Object.getPrototypeOf,kg=Object.prototype.hasOwnProperty;var f=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Rg=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ag(e))!kg.call(i,a)&&a!==t&&pl(i,a,{get:()=>e[a],enumerable:!(r=Pg(e,a))||r.enumerable});return i};var _e=(i,e,t)=>(t=i!=null?xg(wg(i)):{},Rg(e||!i||!i.__esModule?pl(t,"default",{value:i,enumerable:!0}):t,i));var be=f((w$,yl)=>{"use strict";yl.exports=function(i){try{return!!i()}catch(e){return!0}}});var Dr=f((k$,Tl)=>{"use strict";var Vg=be();Tl.exports=!Vg(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ie=f((R$,xl)=>{"use strict";var Il=Dr(),El=Function.prototype,Zs=El.call,_g=Il&&El.bind.bind(Zs,Zs);xl.exports=Il?_g:function(i){return function(){return Zs.apply(i,arguments)}}});var Zt=f(($$,Al)=>{"use strict";var Pl=ie(),Ng=Pl({}.toString),Fg=Pl("".slice);Al.exports=function(i){return Fg(Ng(i),8,-1)}});var kl=f((L$,wl)=>{"use strict";var qg=ie(),Ug=be(),Hg=Zt(),en=Object,jg=qg("".split);wl.exports=Ug(function(){return!en("z").propertyIsEnumerable(0)})?function(i){return Hg(i)=="String"?jg(i,""):en(i)}:en});var er=f((C$,Rl)=>{"use strict";Rl.exports=function(i){return i==null}});var ua=f((M$,$l)=>{"use strict";var Gg=er(),Yg=TypeError;$l.exports=function(i){if(Gg(i))throw Yg("Can't call method on "+i);return i}});var tr=f((D$,Ll)=>{"use strict";var Wg=kl(),Qg=ua();Ll.exports=function(i){return Wg(Qg(i))}});var tn=f((O$,Cl)=>{"use strict";Cl.exports=function(){}});var At=f((B$,Ml)=>{"use strict";Ml.exports={}});var K=f((Dl,Ol)=>{"use strict";var la=function(i){return i&&i.Math==Math&&i};Ol.exports=la(typeof globalThis=="object"&&globalThis)||la(typeof window=="object"&&window)||la(typeof self=="object"&&self)||la(typeof global=="object"&&global)||function(){return this}()||Dl||Function("return this")()});var an=f((V$,Bl)=>{"use strict";var rn=typeof document=="object"&&document.all,zg=typeof rn=="undefined"&&rn!==void 0;Bl.exports={all:rn,IS_HTMLDDA:zg}});var j=f((_$,_l)=>{"use strict";var Vl=an(),Kg=Vl.all;_l.exports=Vl.IS_HTMLDDA?function(i){return typeof i=="function"||i===Kg}:function(i){return typeof i=="function"}});var ql=f((N$,Fl)=>{"use strict";var Jg=K(),Xg=j(),Nl=Jg.WeakMap;Fl.exports=Xg(Nl)&&/native code/.test(String(Nl))});var Ne=f((F$,jl)=>{"use strict";var Ul=j(),Hl=an(),Zg=Hl.all;jl.exports=Hl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Ul(i)||i===Zg}:function(i){return typeof i=="object"?i!==null:Ul(i)}});var Fe=f((q$,Gl)=>{"use strict";var ev=be();Gl.exports=!ev(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var ca=f((U$,Wl)=>{"use strict";var tv=K(),Yl=Ne(),sn=tv.document,rv=Yl(sn)&&Yl(sn.createElement);Wl.exports=function(i){return rv?sn.createElement(i):{}}});var nn=f((H$,Ql)=>{"use strict";var iv=Fe(),av=be(),sv=ca();Ql.exports=!iv&&!av(function(){return Object.defineProperty(sv("div"),"a",{get:function(){return 7}}).a!=7})});var on=f((j$,zl)=>{"use strict";var nv=Fe(),ov=be();zl.exports=nv&&ov(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Re=f((G$,Kl)=>{"use strict";var uv=Ne(),lv=String,cv=TypeError;Kl.exports=function(i){if(uv(i))return i;throw cv(lv(i)+" is not an object")}});var ae=f((Y$,Jl)=>{"use strict";var dv=Dr(),da=Function.prototype.call;Jl.exports=dv?da.bind(da):function(){return da.apply(da,arguments)}});var pa=f((W$,Xl)=>{"use strict";Xl.exports={}});var He=f((Q$,ec)=>{"use strict";var un=pa(),ln=K(),pv=j(),Zl=function(i){return pv(i)?i:void 0};ec.exports=function(i,e){return arguments.length<2?Zl(un[i])||Zl(ln[i]):un[i]&&un[i][e]||ln[i]&&ln[i][e]}});var Or=f((z$,tc)=>{"use strict";var hv=ie();tc.exports=hv({}.isPrototypeOf)});var Br=f((K$,rc)=>{"use strict";rc.exports=typeof navigator!="undefined"&&String(navigator.userAgent)||""});var dn=f((J$,uc)=>{"use strict";var oc=K(),cn=Br(),ic=oc.process,ac=oc.Deno,sc=ic&&ic.versions||ac&&ac.version,nc=sc&&sc.v8,$e,ha;nc&&($e=nc.split("."),ha=$e[0]>0&&$e[0]<4?1:+($e[0]+$e[1]));!ha&&cn&&($e=cn.match(/Edge\/(\d+)/),(!$e||$e[1]>=74)&&($e=cn.match(/Chrome\/(\d+)/),$e&&(ha=+$e[1])));uc.exports=ha});var pn=f((X$,cc)=>{"use strict";var lc=dn(),fv=be(),mv=K(),bv=mv.String;cc.exports=!!Object.getOwnPropertySymbols&&!fv(function(){var i=Symbol();return!bv(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&lc&&lc<41})});var hn=f((Z$,dc)=>{"use strict";var Sv=pn();dc.exports=Sv&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var fn=f((eL,pc)=>{"use strict";var gv=He(),vv=j(),yv=Or(),Tv=hn(),Iv=Object;pc.exports=Tv?function(i){return typeof i=="symbol"}:function(i){var e=gv("Symbol");return vv(e)&&yv(e.prototype,Iv(i))}});var Vr=f((tL,hc)=>{"use strict";var Ev=String;hc.exports=function(i){try{return Ev(i)}catch(e){return"Object"}}});var je=f((rL,fc)=>{"use strict";var xv=j(),Pv=Vr(),Av=TypeError;fc.exports=function(i){if(xv(i))return i;throw Av(Pv(i)+" is not a function")}});var _r=f((iL,mc)=>{"use strict";var wv=je(),kv=er();mc.exports=function(i,e){var t=i[e];return kv(t)?void 0:wv(t)}});var Sc=f((aL,bc)=>{"use strict";var mn=ae(),bn=j(),Sn=Ne(),Rv=TypeError;bc.exports=function(i,e){var t,r;if(e==="string"&&bn(t=i.toString)&&!Sn(r=mn(t,i))||bn(t=i.valueOf)&&!Sn(r=mn(t,i))||e!=="string"&&bn(t=i.toString)&&!Sn(r=mn(t,i)))return r;throw Rv("Can't convert object to primitive value")}});var Le=f((sL,gc)=>{"use strict";gc.exports=!0});var Tc=f((nL,yc)=>{"use strict";var vc=K(),$v=Object.defineProperty;yc.exports=function(i,e){try{$v(vc,i,{value:e,configurable:!0,writable:!0})}catch(t){vc[i]=e}return e}});var fa=f((oL,Ec)=>{"use strict";var Lv=K(),Cv=Tc(),Ic="__core-js_shared__",Mv=Lv[Ic]||Cv(Ic,{});Ec.exports=Mv});var gn=f((uL,Pc)=>{"use strict";var Dv=Le(),xc=fa();(Pc.exports=function(i,e){return xc[i]||(xc[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:Dv?"pure":"global",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var Nr=f((lL,Ac)=>{"use strict";var Ov=ua(),Bv=Object;Ac.exports=function(i){return Bv(Ov(i))}});var Ce=f((cL,wc)=>{"use strict";var Vv=ie(),_v=Nr(),Nv=Vv({}.hasOwnProperty);wc.exports=Object.hasOwn||function(e,t){return Nv(_v(e),t)}});var vn=f((dL,kc)=>{"use strict";var Fv=ie(),qv=0,Uv=Math.random(),Hv=Fv(1 .toString);kc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Hv(++qv+Uv,36)}});var Z=f((pL,$c)=>{"use strict";var jv=K(),Gv=gn(),Rc=Ce(),Yv=vn(),Wv=pn(),Qv=hn(),rr=jv.Symbol,yn=Gv("wks"),zv=Qv?rr.for||rr:rr&&rr.withoutSetter||Yv;$c.exports=function(i){return Rc(yn,i)||(yn[i]=Wv&&Rc(rr,i)?rr[i]:zv("Symbol."+i)),yn[i]}});var Dc=f((hL,Mc)=>{"use strict";var Kv=ae(),Lc=Ne(),Cc=fn(),Jv=_r(),Xv=Sc(),Zv=Z(),ey=TypeError,ty=Zv("toPrimitive");Mc.exports=function(i,e){if(!Lc(i)||Cc(i))return i;var t=Jv(i,ty),r;if(t){if(e===void 0&&(e="default"),r=Kv(t,i,e),!Lc(r)||Cc(r))return r;throw ey("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xv(i,e)}});var ma=f((fL,Oc)=>{"use strict";var ry=Dc(),iy=fn();Oc.exports=function(i){var e=ry(i,"string");return iy(e)?e:e+""}});var wt=f(Vc=>{"use strict";var ay=Fe(),sy=nn(),ny=on(),ba=Re(),Bc=ma(),oy=TypeError,Tn=Object.defineProperty,uy=Object.getOwnPropertyDescriptor,In="enumerable",En="configurable",xn="writable";Vc.f=ay?ny?function(e,t,r){if(ba(e),t=Bc(t),ba(r),typeof e=="function"&&t==="prototype"&&"value"in r&&xn in r&&!r[xn]){var a=uy(e,t);a&&a[xn]&&(e[t]=r.value,r={configurable:En in r?r[En]:a[En],enumerable:In in r?r[In]:a[In],writable:!1})}return Tn(e,t,r)}:Tn:function(e,t,r){if(ba(e),t=Bc(t),ba(r),sy)try{return Tn(e,t,r)}catch(a){}if("get"in r||"set"in r)throw oy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Fr=f((bL,_c)=>{"use strict";_c.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var kt=f((SL,Nc)=>{"use strict";var ly=Fe(),cy=wt(),dy=Fr();Nc.exports=ly?function(i,e,t){return cy.f(i,e,dy(1,t))}:function(i,e,t){return i[e]=t,i}});var Sa=f((gL,qc)=>{"use strict";var py=gn(),hy=vn(),Fc=py("keys");qc.exports=function(i){return Fc[i]||(Fc[i]=hy(i))}});var ga=f((vL,Uc)=>{"use strict";Uc.exports={}});var kn=f((yL,Gc)=>{"use strict";var fy=ql(),jc=K(),my=Ne(),by=kt(),Pn=Ce(),An=fa(),Sy=Sa(),gy=ga(),Hc="Object already initialized",wn=jc.TypeError,vy=jc.WeakMap,va,qr,ya,yy=function(i){return ya(i)?qr(i):va(i,{})},Ty=function(i){return function(e){var t;if(!my(e)||(t=qr(e)).type!==i)throw wn("Incompatible receiver, "+i+" required");return t}};fy||An.state?(Me=An.state||(An.state=new vy),Me.get=Me.get,Me.has=Me.has,Me.set=Me.set,va=function(i,e){if(Me.has(i))throw wn(Hc);return e.facade=i,Me.set(i,e),e},qr=function(i){return Me.get(i)||{}},ya=function(i){return Me.has(i)}):(Rt=Sy("state"),gy[Rt]=!0,va=function(i,e){if(Pn(i,Rt))throw wn(Hc);return e.facade=i,by(i,Rt,e),e},qr=function(i){return Pn(i,Rt)?i[Rt]:{}},ya=function(i){return Pn(i,Rt)});var Me,Rt;Gc.exports={set:va,get:qr,has:ya,enforce:yy,getterFor:Ty}});var Rn=f((TL,zc)=>{"use strict";var Iy=Dr(),Qc=Function.prototype,Yc=Qc.apply,Wc=Qc.call;zc.exports=typeof Reflect=="object"&&Reflect.apply||(Iy?Wc.bind(Yc):function(){return Wc.apply(Yc,arguments)})});var $n=f((IL,Kc)=>{"use strict";var Ey=Zt(),xy=ie();Kc.exports=function(i){if(Ey(i)==="Function")return xy(i)}});var ed=f(Zc=>{"use strict";var Jc={}.propertyIsEnumerable,Xc=Object.getOwnPropertyDescriptor,Py=Xc&&!Jc.call({1:2},1);Zc.f=Py?function(e){var t=Xc(this,e);return!!t&&t.enumerable}:Jc});var Ln=f(rd=>{"use strict";var Ay=Fe(),wy=ae(),ky=ed(),Ry=Fr(),$y=tr(),Ly=ma(),Cy=Ce(),My=nn(),td=Object.getOwnPropertyDescriptor;rd.f=Ay?td:function(e,t){if(e=$y(e),t=Ly(t),My)try{return td(e,t)}catch(r){}if(Cy(e,t))return Ry(!wy(ky.f,e,t),e[t])}});var Cn=f((PL,id)=>{"use strict";var Dy=be(),Oy=j(),By=/#|\.prototype\./,Ur=function(i,e){var t=_y[Vy(i)];return t==Fy?!0:t==Ny?!1:Oy(e)?Dy(e):!!e},Vy=Ur.normalize=function(i){return String(i).replace(By,".").toLowerCase()},_y=Ur.data={},Ny=Ur.NATIVE="N",Fy=Ur.POLYFILL="P";id.exports=Ur});var Hr=f((AL,sd)=>{"use strict";var ad=$n(),qy=je(),Uy=Dr(),Hy=ad(ad.bind);sd.exports=function(i,e){return qy(i),e===void 0?i:Uy?Hy(i,e):function(){return i.apply(e,arguments)}}});var ye=f((wL,od)=>{"use strict";var Ta=K(),jy=Rn(),Gy=$n(),Yy=j(),Wy=Ln().f,Qy=Cn(),ir=pa(),zy=Hr(),ar=kt(),nd=Ce(),Ky=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 jy(i,this,arguments)};return e.prototype=i.prototype,e};od.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Ta:a?Ta[t]:(Ta[t]||{}).prototype,o=r?ir:ir[t]||ar(ir,t,{})[t],l=o.prototype,u,c,d,p,h,m,b,S,T;for(p in e)u=Qy(r?p:t+(a?".":"#")+p,i.forced),c=!u&&n&&nd(n,p),m=o[p],c&&(i.dontCallGetSet?(T=Wy(n,p),b=T&&T.value):b=n[p]),h=c&&b?b:e[p],!(c&&typeof m==typeof h)&&(i.bind&&c?S=zy(h,Ta):i.wrap&&c?S=Ky(h):s&&Yy(h)?S=Gy(h):S=h,(i.sham||h&&h.sham||m&&m.sham)&&ar(S,"sham",!0),ar(o,p,S),s&&(d=t+"Prototype",nd(ir,d)||ar(ir,d,{}),ar(ir[d],p,h),i.real&&l&&(u||!l[p])&&ar(l,p,h)))}});var cd=f((kL,ld)=>{"use strict";var Mn=Fe(),Jy=Ce(),ud=Function.prototype,Xy=Mn&&Object.getOwnPropertyDescriptor,Dn=Jy(ud,"name"),Zy=Dn&&function(){}.name==="something",eT=Dn&&(!Mn||Mn&&Xy(ud,"name").configurable);ld.exports={EXISTS:Dn,PROPER:Zy,CONFIGURABLE:eT}});var pd=f((RL,dd)=>{"use strict";var tT=Math.ceil,rT=Math.floor;dd.exports=Math.trunc||function(e){var t=+e;return(t>0?rT:tT)(t)}});var Ia=f(($L,hd)=>{"use strict";var iT=pd();hd.exports=function(i){var e=+i;return e!==e||e===0?0:iT(e)}});var md=f((LL,fd)=>{"use strict";var aT=Ia(),sT=Math.max,nT=Math.min;fd.exports=function(i,e){var t=aT(i);return t<0?sT(t+e,0):nT(t,e)}});var Sd=f((CL,bd)=>{"use strict";var oT=Ia(),uT=Math.min;bd.exports=function(i){return i>0?uT(oT(i),9007199254740991):0}});var Ea=f((ML,gd)=>{"use strict";var lT=Sd();gd.exports=function(i){return lT(i.length)}});var Td=f((DL,yd)=>{"use strict";var cT=tr(),dT=md(),pT=Ea(),vd=function(i){return function(e,t,r){var a=cT(e),s=pT(a),n=dT(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}};yd.exports={includes:vd(!0),indexOf:vd(!1)}});var xd=f((OL,Ed)=>{"use strict";var hT=ie(),On=Ce(),fT=tr(),mT=Td().indexOf,bT=ga(),Id=hT([].push);Ed.exports=function(i,e){var t=fT(i),r=0,a=[],s;for(s in t)!On(bT,s)&&On(t,s)&&Id(a,s);for(;e.length>r;)On(t,s=e[r++])&&(~mT(a,s)||Id(a,s));return a}});var Bn=f((BL,Pd)=>{"use strict";Pd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var wd=f((VL,Ad)=>{"use strict";var ST=xd(),gT=Bn();Ad.exports=Object.keys||function(e){return ST(e,gT)}});var Rd=f(kd=>{"use strict";var vT=Fe(),yT=on(),TT=wt(),IT=Re(),ET=tr(),xT=wd();kd.f=vT&&!yT?Object.defineProperties:function(e,t){IT(e);for(var r=ET(t),a=xT(t),s=a.length,n=0,o;s>n;)TT.f(e,o=a[n++],r[o]);return e}});var Vn=f((NL,$d)=>{"use strict";var PT=He();$d.exports=PT("document","documentElement")});var qn=f((FL,Vd)=>{"use strict";var AT=Re(),wT=Rd(),Ld=Bn(),kT=ga(),RT=Vn(),$T=ca(),LT=Sa(),Cd=">",Md="<",Nn="prototype",Fn="script",Od=LT("IE_PROTO"),_n=function(){},Bd=function(i){return Md+Fn+Cd+i+Md+"/"+Fn+Cd},Dd=function(i){i.write(Bd("")),i.close();var e=i.parentWindow.Object;return i=null,e},CT=function(){var i=$T("iframe"),e="java"+Fn+":",t;return i.style.display="none",RT.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Bd("document.F=Object")),t.close(),t.F},xa,Pa=function(){try{xa=new ActiveXObject("htmlfile")}catch(e){}Pa=typeof document!="undefined"?document.domain&&xa?Dd(xa):CT():Dd(xa);for(var i=Ld.length;i--;)delete Pa[Nn][Ld[i]];return Pa()};kT[Od]=!0;Vd.exports=Object.create||function(e,t){var r;return e!==null?(_n[Nn]=AT(e),r=new _n,_n[Nn]=null,r[Od]=e):r=Pa(),t===void 0?r:wT.f(r,t)}});var Nd=f((qL,_d)=>{"use strict";var MT=be();_d.exports=!MT(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Hn=f((UL,qd)=>{"use strict";var DT=Ce(),OT=j(),BT=Nr(),VT=Sa(),_T=Nd(),Fd=VT("IE_PROTO"),Un=Object,NT=Un.prototype;qd.exports=_T?Un.getPrototypeOf:function(i){var e=BT(i);if(DT(e,Fd))return e[Fd];var t=e.constructor;return OT(t)&&e instanceof t?t.prototype:e instanceof Un?NT:null}});var sr=f((HL,Ud)=>{"use strict";var FT=kt();Ud.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:FT(i,e,t),i}});var Wn=f((jL,Gd)=>{"use strict";var qT=be(),UT=j(),HT=Ne(),jT=qn(),Hd=Hn(),GT=sr(),YT=Z(),WT=Le(),Yn=YT("iterator"),jd=!1,Ge,jn,Gn;[].keys&&(Gn=[].keys(),"next"in Gn?(jn=Hd(Hd(Gn)),jn!==Object.prototype&&(Ge=jn)):jd=!0);var QT=!HT(Ge)||qT(function(){var i={};return Ge[Yn].call(i)!==i});QT?Ge={}:WT&&(Ge=jT(Ge));UT(Ge[Yn])||GT(Ge,Yn,function(){return this});Gd.exports={IteratorPrototype:Ge,BUGGY_SAFARI_ITERATORS:jd}});var Aa=f((GL,Wd)=>{"use strict";var zT=Z(),KT=zT("toStringTag"),Yd={};Yd[KT]="z";Wd.exports=String(Yd)==="[object z]"});var nr=f((YL,Qd)=>{"use strict";var JT=Aa(),XT=j(),wa=Zt(),ZT=Z(),eI=ZT("toStringTag"),tI=Object,rI=wa(function(){return arguments}())=="Arguments",iI=function(i,e){try{return i[e]}catch(t){}};Qd.exports=JT?wa:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=iI(e=tI(i),eI))=="string"?t:rI?wa(e):(r=wa(e))=="Object"&&XT(e.callee)?"Arguments":r}});var Kd=f((WL,zd)=>{"use strict";var aI=Aa(),sI=nr();zd.exports=aI?{}.toString:function(){return"[object "+sI(this)+"]"}});var ka=f((QL,Xd)=>{"use strict";var nI=Aa(),oI=wt().f,uI=kt(),lI=Ce(),cI=Kd(),dI=Z(),Jd=dI("toStringTag");Xd.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;lI(a,Jd)||oI(a,Jd,{configurable:!0,value:e}),r&&!nI&&uI(a,"toString",cI)}}});var ep=f((zL,Zd)=>{"use strict";var pI=Wn().IteratorPrototype,hI=qn(),fI=Fr(),mI=ka(),bI=At(),SI=function(){return this};Zd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=hI(pI,{next:fI(+!r,t)}),mI(i,a,!1,!0),bI[a]=SI,i}});var rp=f((KL,tp)=>{"use strict";var gI=ie(),vI=je();tp.exports=function(i,e,t){try{return gI(vI(Object.getOwnPropertyDescriptor(i,e)[t]))}catch(r){}}});var ap=f((JL,ip)=>{"use strict";var yI=j(),TI=String,II=TypeError;ip.exports=function(i){if(typeof i=="object"||yI(i))return i;throw II("Can't set "+TI(i)+" as a prototype")}});var Qn=f((XL,sp)=>{"use strict";var EI=rp(),xI=Re(),PI=ap();sp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=EI(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch(r){}return function(a,s){return xI(a),PI(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var bp=f((ZL,mp)=>{"use strict";var AI=ye(),wI=ae(),Ra=Le(),hp=cd(),kI=j(),RI=ep(),np=Hn(),op=Qn(),$I=ka(),LI=kt(),zn=sr(),CI=Z(),up=At(),fp=Wn(),MI=hp.PROPER,DI=hp.CONFIGURABLE,lp=fp.IteratorPrototype,$a=fp.BUGGY_SAFARI_ITERATORS,jr=CI("iterator"),cp="keys",Gr="values",dp="entries",pp=function(){return this};mp.exports=function(i,e,t,r,a,s,n){RI(t,e,r);var o=function(T){if(T===a&&p)return p;if(!$a&&T in c)return c[T];switch(T){case cp:return function(){return new t(this,T)};case Gr:return function(){return new t(this,T)};case dp:return function(){return new t(this,T)}}return function(){return new t(this)}},l=e+" Iterator",u=!1,c=i.prototype,d=c[jr]||c["@@iterator"]||a&&c[a],p=!$a&&d||o(a),h=e=="Array"&&c.entries||d,m,b,S;if(h&&(m=np(h.call(new i)),m!==Object.prototype&&m.next&&(!Ra&&np(m)!==lp&&(op?op(m,lp):kI(m[jr])||zn(m,jr,pp)),$I(m,l,!0,!0),Ra&&(up[l]=pp))),MI&&a==Gr&&d&&d.name!==Gr&&(!Ra&&DI?LI(c,"name",Gr):(u=!0,p=function(){return wI(d,this)})),a)if(b={values:o(Gr),keys:s?p:o(cp),entries:o(dp)},n)for(S in b)($a||u||!(S in c))&&zn(c,S,b[S]);else AI({target:e,proto:!0,forced:$a||u},b);return(!Ra||n)&&c[jr]!==p&&zn(c,jr,p,{name:a}),up[e]=p,b}});var gp=f((eC,Sp)=>{"use strict";Sp.exports=function(i,e){return{value:i,done:e}}});var Jn=f((tC,Ep)=>{"use strict";var OI=tr(),Kn=tn(),vp=At(),Tp=kn(),BI=wt().f,VI=bp(),La=gp(),_I=Le(),NI=Fe(),Ip="Array Iterator",FI=Tp.set,qI=Tp.getterFor(Ip);Ep.exports=VI(Array,"Array",function(i,e){FI(this,{type:Ip,target:OI(i),index:0,kind:e})},function(){var i=qI(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,La(void 0,!0)):t=="keys"?La(r,!1):t=="values"?La(e[r],!1):La([r,e[r]],!1)},"values");var yp=vp.Arguments=vp.Array;Kn("keys");Kn("values");Kn("entries");if(!_I&&NI&&yp.name!=="values")try{BI(yp,"name",{value:"values"})}catch(i){}});var Pp=f((rC,xp)=>{"use strict";var UI=Z(),HI=At(),jI=UI("iterator"),GI=Array.prototype;xp.exports=function(i){return i!==void 0&&(HI.Array===i||GI[jI]===i)}});var Xn=f((iC,wp)=>{"use strict";var YI=nr(),Ap=_r(),WI=er(),QI=At(),zI=Z(),KI=zI("iterator");wp.exports=function(i){if(!WI(i))return Ap(i,KI)||Ap(i,"@@iterator")||QI[YI(i)]}});var Rp=f((aC,kp)=>{"use strict";var JI=ae(),XI=je(),ZI=Re(),eE=Vr(),tE=Xn(),rE=TypeError;kp.exports=function(i,e){var t=arguments.length<2?tE(i):e;if(XI(t))return ZI(JI(t,i));throw rE(eE(i)+" is not iterable")}});var Cp=f((sC,Lp)=>{"use strict";var iE=ae(),$p=Re(),aE=_r();Lp.exports=function(i,e,t){var r,a;$p(i);try{if(r=aE(i,"return"),!r){if(e==="throw")throw t;return t}r=iE(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return $p(r),t}});var Ma=f((nC,Bp)=>{"use strict";var sE=Hr(),nE=ae(),oE=Re(),uE=Vr(),lE=Pp(),cE=Ea(),Mp=Or(),dE=Rp(),pE=Xn(),Dp=Cp(),hE=TypeError,Ca=function(i,e){this.stopped=i,this.result=e},Op=Ca.prototype;Bp.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),l=sE(e,r),u,c,d,p,h,m,b,S=function(v){return u&&Dp(u,"normal",v),new Ca(!0,v)},T=function(v){return a?(oE(v),o?l(v[0],v[1],S):l(v[0],v[1])):o?l(v,S):l(v)};if(s)u=i.iterator;else if(n)u=i;else{if(c=pE(i),!c)throw hE(uE(i)+" is not iterable");if(lE(c)){for(d=0,p=cE(i);p>d;d++)if(h=T(i[d]),h&&Mp(Op,h))return h;return new Ca(!1)}u=dE(i,c)}for(m=s?i.next:u.next;!(b=nE(m,u)).done;){try{h=T(b.value)}catch(v){Dp(u,"throw",v)}if(typeof h=="object"&&h&&Mp(Op,h))return h}return new Ca(!1)}});var _p=f((oC,Vp)=>{"use strict";var fE=ma(),mE=wt(),bE=Fr();Vp.exports=function(i,e,t){var r=fE(e);r in i?mE.f(i,r,bE(0,t)):i[r]=t}});var Np=f(()=>{"use strict";var SE=ye(),gE=Ma(),vE=_p();SE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return gE(e,function(r,a){vE(t,r,a)},{AS_ENTRIES:!0}),t}})});var qp=f((cC,Fp)=>{"use strict";Jn();Np();var yE=pa();Fp.exports=yE.Object.fromEntries});var Hp=f((dC,Up)=>{"use strict";Up.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 Yp=f(()=>{"use strict";Jn();var TE=Hp(),IE=K(),EE=nr(),xE=kt(),jp=At(),PE=Z(),Gp=PE("toStringTag");for(Da in TE)Zn=IE[Da],Oa=Zn&&Zn.prototype,Oa&&EE(Oa)!==Gp&&xE(Oa,Gp,Da),jp[Da]=jp.Array;var Zn,Oa,Da});var Qp=f((fC,Wp)=>{"use strict";var AE=qp();Yp();Wp.exports=AE});var eo=f((mC,zp)=>{"use strict";var wE=Qp();zp.exports=wE});var Kp=f(()=>{"use strict"});var Yr=f((gC,Jp)=>{"use strict";var kE=Zt();Jp.exports=typeof process!="undefined"&&kE(process)=="process"});var Zp=f((vC,Xp)=>{"use strict";var RE=wt();Xp.exports=function(i,e,t){return RE.f(i,e,t)}});var rh=f((yC,th)=>{"use strict";var $E=He(),LE=Zp(),CE=Z(),ME=Fe(),eh=CE("species");th.exports=function(i){var e=$E(i);ME&&e&&!e[eh]&&LE(e,eh,{configurable:!0,get:function(){return this}})}});var ah=f((TC,ih)=>{"use strict";var DE=Or(),OE=TypeError;ih.exports=function(i,e){if(DE(e,i))return i;throw OE("Incorrect invocation")}});var ro=f((IC,sh)=>{"use strict";var BE=ie(),VE=j(),to=fa(),_E=BE(Function.toString);VE(to.inspectSource)||(to.inspectSource=function(i){return _E(i)});sh.exports=to.inspectSource});var dh=f((EC,ch)=>{"use strict";var NE=ie(),FE=be(),nh=j(),qE=nr(),UE=He(),HE=ro(),oh=function(){},jE=[],uh=UE("Reflect","construct"),io=/^\s*(?:class|function)\b/,GE=NE(io.exec),YE=!io.exec(oh),Wr=function(e){if(!nh(e))return!1;try{return uh(oh,jE,e),!0}catch(t){return!1}},lh=function(e){if(!nh(e))return!1;switch(qE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return YE||!!GE(io,HE(e))}catch(t){return!0}};lh.sham=!0;ch.exports=!uh||FE(function(){var i;return Wr(Wr.call)||!Wr(Object)||!Wr(function(){i=!0})||i})?lh:Wr});var hh=f((xC,ph)=>{"use strict";var WE=dh(),QE=Vr(),zE=TypeError;ph.exports=function(i){if(WE(i))return i;throw zE(QE(i)+" is not a constructor")}});var ao=f((PC,mh)=>{"use strict";var fh=Re(),KE=hh(),JE=er(),XE=Z(),ZE=XE("species");mh.exports=function(i,e){var t=fh(i).constructor,r;return t===void 0||JE(r=fh(t)[ZE])?e:KE(r)}});var Sh=f((AC,bh)=>{"use strict";var ex=ie();bh.exports=ex([].slice)});var vh=f((wC,gh)=>{"use strict";var tx=TypeError;gh.exports=function(i,e){if(i<e)throw tx("Not enough arguments");return i}});var so=f((kC,yh)=>{"use strict";var rx=Br();yh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(rx)});var mo=f((RC,Rh)=>{"use strict";var Se=K(),ix=Rn(),ax=Hr(),Th=j(),sx=Ce(),kh=be(),Ih=Vn(),nx=Sh(),Eh=ca(),ox=vh(),ux=so(),lx=Yr(),po=Se.setImmediate,ho=Se.clearImmediate,cx=Se.process,no=Se.Dispatch,dx=Se.Function,xh=Se.MessageChannel,px=Se.String,oo=0,Qr={},Ph="onreadystatechange",zr,$t,uo,lo;kh(function(){zr=Se.location});var fo=function(i){if(sx(Qr,i)){var e=Qr[i];delete Qr[i],e()}},co=function(i){return function(){fo(i)}},Ah=function(i){fo(i.data)},wh=function(i){Se.postMessage(px(i),zr.protocol+"//"+zr.host)};(!po||!ho)&&(po=function(e){ox(arguments.length,1);var t=Th(e)?e:dx(e),r=nx(arguments,1);return Qr[++oo]=function(){ix(t,void 0,r)},$t(oo),oo},ho=function(e){delete Qr[e]},lx?$t=function(i){cx.nextTick(co(i))}:no&&no.now?$t=function(i){no.now(co(i))}:xh&&!ux?(uo=new xh,lo=uo.port2,uo.port1.onmessage=Ah,$t=ax(lo.postMessage,lo)):Se.addEventListener&&Th(Se.postMessage)&&!Se.importScripts&&zr&&zr.protocol!=="file:"&&!kh(wh)?($t=wh,Se.addEventListener("message",Ah,!1)):Ph in Eh("script")?$t=function(i){Ih.appendChild(Eh("script"))[Ph]=function(){Ih.removeChild(this),fo(i)}}:$t=function(i){setTimeout(co(i),0)});Rh.exports={set:po,clear:ho}});var bo=f(($C,Lh)=>{"use strict";var $h=function(){this.head=null,this.tail=null};$h.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}}};Lh.exports=$h});var Mh=f((LC,Ch)=>{"use strict";var hx=Br();Ch.exports=/ipad|iphone|ipod/i.test(hx)&&typeof Pebble!="undefined"});var Oh=f((CC,Dh)=>{"use strict";var fx=Br();Dh.exports=/web0s(?!.*chrome)/i.test(fx)});var Hh=f((MC,Uh)=>{"use strict";var Lt=K(),Bh=Hr(),mx=Ln().f,So=mo().set,bx=bo(),Sx=so(),gx=Mh(),vx=Oh(),go=Yr(),Vh=Lt.MutationObserver||Lt.WebKitMutationObserver,_h=Lt.document,Nh=Lt.process,Ba=Lt.Promise,Fh=mx(Lt,"queueMicrotask"),To=Fh&&Fh.value,or,vo,yo,Va,qh;To||(Kr=new bx,Jr=function(){var i,e;for(go&&(i=Nh.domain)&&i.exit();e=Kr.get();)try{e()}catch(t){throw Kr.head&&or(),t}i&&i.enter()},!Sx&&!go&&!vx&&Vh&&_h?(vo=!0,yo=_h.createTextNode(""),new Vh(Jr).observe(yo,{characterData:!0}),or=function(){yo.data=vo=!vo}):!gx&&Ba&&Ba.resolve?(Va=Ba.resolve(void 0),Va.constructor=Ba,qh=Bh(Va.then,Va),or=function(){qh(Jr)}):go?or=function(){Nh.nextTick(Jr)}:(So=Bh(So,Lt),or=function(){So(Jr)}),To=function(i){Kr.head||or(),Kr.add(i)});var Kr,Jr;Uh.exports=To});var Gh=f((DC,jh)=>{"use strict";jh.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}}});var _a=f((OC,Yh)=>{"use strict";Yh.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Ct=f((BC,Wh)=>{"use strict";var yx=K();Wh.exports=yx.Promise});var Io=f((VC,Qh)=>{"use strict";Qh.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var Kh=f((_C,zh)=>{"use strict";var Tx=Io(),Ix=Yr();zh.exports=!Tx&&!Ix&&typeof window=="object"&&typeof document=="object"});var ur=f((NC,Zh)=>{"use strict";var Ex=K(),Xr=Ct(),xx=j(),Px=Cn(),Ax=ro(),wx=Z(),kx=Kh(),Rx=Io(),$x=Le(),Eo=dn(),Jh=Xr&&Xr.prototype,Lx=wx("species"),xo=!1,Xh=xx(Ex.PromiseRejectionEvent),Cx=Px("Promise",function(){var i=Ax(Xr),e=i!==String(Xr);if(!e&&Eo===66||$x&&!(Jh.catch&&Jh.finally))return!0;if(!Eo||Eo<51||!/native code/.test(i)){var t=new Xr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Lx]=r,xo=t.then(function(){})instanceof r,!xo)return!0}return!e&&(kx||Rx)&&!Xh});Zh.exports={CONSTRUCTOR:Cx,REJECTION_EVENT:Xh,SUBCLASSING:xo}});var lr=f((FC,tf)=>{"use strict";var ef=je(),Mx=TypeError,Dx=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw Mx("Bad Promise constructor");e=r,t=a}),this.resolve=ef(e),this.reject=ef(t)};tf.exports.f=function(i){return new Dx(i)}});var Tf=f(()=>{"use strict";var Ox=ye(),Bx=Le(),Ua=Yr(),nt=K(),hr=ae(),rf=sr(),af=Qn(),Vx=ka(),_x=rh(),Nx=je(),qa=j(),Fx=Ne(),qx=ah(),Ux=ao(),lf=mo().set,Ro=Hh(),Hx=Gh(),jx=_a(),Gx=bo(),cf=kn(),Ha=Ct(),$o=ur(),df=lr(),ja="Promise",pf=$o.CONSTRUCTOR,Yx=$o.REJECTION_EVENT,Wx=$o.SUBCLASSING,Po=cf.getterFor(ja),Qx=cf.set,cr=Ha&&Ha.prototype,Mt=Ha,Na=cr,hf=nt.TypeError,Ao=nt.document,Lo=nt.process,wo=df.f,zx=wo,Kx=!!(Ao&&Ao.createEvent&&nt.dispatchEvent),ff="unhandledrejection",Jx="rejectionhandled",sf=0,mf=1,Xx=2,Co=1,bf=2,Fa,nf,Zx,of,Sf=function(i){var e;return Fx(i)&&qa(e=i.then)?e:!1},gf=function(i,e){var t=e.value,r=e.state==mf,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,l,u,c;try{a?(r||(e.rejection===bf&&tP(e),e.rejection=Co),a===!0?l=t:(o&&o.enter(),l=a(t),o&&(o.exit(),c=!0)),l===i.promise?n(hf("Promise-chain cycle")):(u=Sf(l))?hr(u,l,s,n):s(l)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},vf=function(i,e){i.notified||(i.notified=!0,Ro(function(){for(var t=i.reactions,r;r=t.get();)gf(r,i);i.notified=!1,e&&!i.rejection&&eP(i)}))},yf=function(i,e,t){var r,a;Kx?(r=Ao.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),nt.dispatchEvent(r)):r={promise:e,reason:t},!Yx&&(a=nt["on"+i])?a(r):i===ff&&Hx("Unhandled promise rejection",t)},eP=function(i){hr(lf,nt,function(){var e=i.facade,t=i.value,r=uf(i),a;if(r&&(a=jx(function(){Ua?Lo.emit("unhandledRejection",t,e):yf(ff,e,t)}),i.rejection=Ua||uf(i)?bf:Co,a.error))throw a.value})},uf=function(i){return i.rejection!==Co&&!i.parent},tP=function(i){hr(lf,nt,function(){var e=i.facade;Ua?Lo.emit("rejectionHandled",e):yf(Jx,e,i.value)})},dr=function(i,e,t){return function(r){i(e,r,t)}},pr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Xx,vf(i,!0))},ko=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw hf("Promise can't be resolved itself");var r=Sf(e);r?Ro(function(){var a={done:!1};try{hr(r,e,dr(ko,a,i),dr(pr,a,i))}catch(s){pr(a,s,i)}}):(i.value=e,i.state=mf,vf(i,!1))}catch(a){pr({done:!1},a,i)}}};if(pf&&(Mt=function(e){qx(this,Na),Nx(e),hr(Fa,this);var t=Po(this);try{e(dr(ko,t),dr(pr,t))}catch(r){pr(t,r)}},Na=Mt.prototype,Fa=function(e){Qx(this,{type:ja,done:!1,notified:!1,parent:!1,reactions:new Gx,rejection:!1,state:sf,value:void 0})},Fa.prototype=rf(Na,"then",function(e,t){var r=Po(this),a=wo(Ux(this,Mt));return r.parent=!0,a.ok=qa(e)?e:!0,a.fail=qa(t)&&t,a.domain=Ua?Lo.domain:void 0,r.state==sf?r.reactions.add(a):Ro(function(){gf(a,r)}),a.promise}),nf=function(){var i=new Fa,e=Po(i);this.promise=i,this.resolve=dr(ko,e),this.reject=dr(pr,e)},df.f=wo=function(i){return i===Mt||i===Zx?new nf(i):zx(i)},!Bx&&qa(Ha)&&cr!==Object.prototype)){of=cr.then,Wx||rf(cr,"then",function(e,t){var r=this;return new Mt(function(a,s){hr(of,r,a,s)}).then(e,t)},{unsafe:!0});try{delete cr.constructor}catch(i){}af&&af(cr,Na)}Ox({global:!0,constructor:!0,wrap:!0,forced:pf},{Promise:Mt});Vx(Mt,ja,!1,!0);_x(ja)});var Af=f((HC,Pf)=>{"use strict";var rP=Z(),Ef=rP("iterator"),xf=!1;try{If=0,Mo={next:function(){return{done:!!If++}},return:function(){xf=!0}},Mo[Ef]=function(){return this},Array.from(Mo,function(){throw 2})}catch(i){}var If,Mo;Pf.exports=function(i,e){if(!e&&!xf)return!1;var t=!1;try{var r={};r[Ef]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(a){}return t}});var Do=f((jC,wf)=>{"use strict";var iP=Ct(),aP=Af(),sP=ur().CONSTRUCTOR;wf.exports=sP||!aP(function(i){iP.all(i).then(void 0,function(){})})});var kf=f(()=>{"use strict";var nP=ye(),oP=ae(),uP=je(),lP=lr(),cP=_a(),dP=Ma(),pP=Do();nP({target:"Promise",stat:!0,forced:pP},{all:function(e){var t=this,r=lP.f(t),a=r.resolve,s=r.reject,n=cP(function(){var o=uP(t.resolve),l=[],u=0,c=1;dP(e,function(d){var p=u++,h=!1;c++,oP(o,t,d).then(function(m){h||(h=!0,l[p]=m,--c||a(l))},s)}),--c||a(l)});return n.error&&s(n.value),r.promise}})});var $f=f(()=>{"use strict";var hP=ye(),fP=Le(),mP=ur().CONSTRUCTOR,Bo=Ct(),bP=He(),SP=j(),gP=sr(),Rf=Bo&&Bo.prototype;hP({target:"Promise",proto:!0,forced:mP,real:!0},{catch:function(i){return this.then(void 0,i)}});!fP&&SP(Bo)&&(Oo=bP("Promise").prototype.catch,Rf.catch!==Oo&&gP(Rf,"catch",Oo,{unsafe:!0}));var Oo});var Lf=f(()=>{"use strict";var vP=ye(),yP=ae(),TP=je(),IP=lr(),EP=_a(),xP=Ma(),PP=Do();vP({target:"Promise",stat:!0,forced:PP},{race:function(e){var t=this,r=IP.f(t),a=r.reject,s=EP(function(){var n=TP(t.resolve);xP(e,function(o){yP(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Cf=f(()=>{"use strict";var AP=ye(),wP=ae(),kP=lr(),RP=ur().CONSTRUCTOR;AP({target:"Promise",stat:!0,forced:RP},{reject:function(e){var t=kP.f(this);return wP(t.reject,void 0,e),t.promise}})});var Vo=f((ZC,Mf)=>{"use strict";var $P=Re(),LP=Ne(),CP=lr();Mf.exports=function(i,e){if($P(i),LP(e)&&e.constructor===i)return e;var t=CP.f(i),r=t.resolve;return r(e),t.promise}});var Bf=f(()=>{"use strict";var MP=ye(),DP=He(),Df=Le(),OP=Ct(),Of=ur().CONSTRUCTOR,BP=Vo(),VP=DP("Promise"),_P=Df&&!Of;MP({target:"Promise",stat:!0,forced:Df||Of},{resolve:function(e){return BP(_P&&this===VP?OP:this,e)}})});var Vf=f(()=>{"use strict";Tf();kf();$f();Lf();Cf();Bf()});var qf=f(()=>{"use strict";var NP=ye(),FP=Le(),Ga=Ct(),qP=be(),Nf=He(),Ff=j(),UP=ao(),_f=Vo(),HP=sr(),No=Ga&&Ga.prototype,jP=!!Ga&&qP(function(){No.finally.call({then:function(){}},function(){})});NP({target:"Promise",proto:!0,real:!0,forced:jP},{finally:function(i){var e=UP(this,Nf("Promise")),t=Ff(i);return this.then(t?function(r){return _f(e,i()).then(function(){return r})}:i,t?function(r){return _f(e,i()).then(function(){throw r})}:i)}});!FP&&Ff(Ga)&&(_o=Nf("Promise").prototype.finally,No.finally!==_o&&HP(No,"finally",_o,{unsafe:!0}));var _o});var Ya=f((nM,Uf)=>{"use strict";var GP=He();Uf.exports=GP});var jf=f((oM,Hf)=>{"use strict";Kp();Vf();qf();var YP=Ya();Hf.exports=YP("Promise","finally")});var Yf=f((uM,Gf)=>{"use strict";var WP=jf();Gf.exports=WP});var Wa=f((lM,Wf)=>{"use strict";var QP=Yf();Wf.exports=QP});var Sm=f(()=>{"use strict";var yA=ye(),TA=Nr(),IA=Ea(),EA=Ia(),xA=tn();yA({target:"Array",proto:!0},{at:function(e){var t=TA(this),r=IA(t),a=EA(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});xA("at")});var vm=f((gD,gm)=>{"use strict";Sm();var PA=Ya();gm.exports=PA("Array","at")});var Tm=f((vD,ym)=>{"use strict";var AA=vm();ym.exports=AA});var ii=f((yD,Im)=>{"use strict";var wA=Tm();Im.exports=wA});var Eb=f(()=>{"use strict"});var xb=f(()=>{"use strict"});var Ab=f((vV,Pb)=>{"use strict";var Fw=Ne(),qw=Zt(),Uw=Z(),Hw=Uw("match");Pb.exports=function(i){var e;return Fw(i)&&((e=i[Hw])!==void 0?!!e:qw(i)=="RegExp")}});var kb=f((yV,wb)=>{"use strict";var jw=nr(),Gw=String;wb.exports=function(i){if(jw(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Gw(i)}});var $b=f((TV,Rb)=>{"use strict";var Yw=Re();Rb.exports=function(){var i=Yw(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 Mb=f((IV,Cb)=>{"use strict";var Ww=ae(),Qw=Ce(),zw=Or(),Kw=$b(),Lb=RegExp.prototype;Cb.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in Lb)&&!Qw(i,"flags")&&zw(Lb,i)?Ww(Kw,i):e}});var Ob=f((EV,Db)=>{"use strict";var fu=ie(),Jw=Nr(),Xw=Math.floor,pu=fu("".charAt),Zw=fu("".replace),hu=fu("".slice),ek=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,tk=/\$([$&'`]|\d{1,2})/g;Db.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,l=tk;return a!==void 0&&(a=Jw(a),l=ek),Zw(s,l,function(u,c){var d;switch(pu(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 u;if(p>o){var h=Xw(p/10);return h===0?u:h<=o?r[h-1]===void 0?pu(c,1):r[h-1]+pu(c,1):u}d=r[p-1]}return d===void 0?"":d})}});var Fb=f(()=>{"use strict";var rk=ye(),ik=ae(),mu=ie(),Bb=ua(),ak=j(),sk=er(),nk=Ab(),Ir=kb(),ok=_r(),uk=Mb(),lk=Ob(),ck=Z(),dk=Le(),pk=ck("replace"),hk=TypeError,Nb=mu("".indexOf),fk=mu("".replace),Vb=mu("".slice),mk=Math.max,_b=function(i,e,t){return t>i.length?-1:e===""?t:Nb(i,e,t)};rk({target:"String",proto:!0},{replaceAll:function(e,t){var r=Bb(this),a,s,n,o,l,u,c,d,p,h=0,m=0,b="";if(!sk(e)){if(a=nk(e),a&&(s=Ir(Bb(uk(e))),!~Nb(s,"g")))throw hk("`.replaceAll` does not allow non-global regexes");if(n=ok(e,pk),n)return ik(n,e,r,t);if(dk&&a)return fk(Ir(r),e,t)}for(o=Ir(r),l=Ir(e),u=ak(t),u||(t=Ir(t)),c=l.length,d=mk(1,c),h=_b(o,l,0);h!==-1;)p=u?Ir(t(l,h,o)):lk(l,o,h,[],void 0,t),b+=Vb(o,m,h)+p,m=h+c,h=_b(o,l,h+d);return m<o.length&&(b+=Vb(o,m)),b}})});var Ub=f((AV,qb)=>{"use strict";Eb();xb();Fb();var bk=Ya();qb.exports=bk("String","replaceAll")});var jb=f((wV,Hb)=>{"use strict";var Sk=Ub();Hb.exports=Sk});var Yb=f((kV,Gb)=>{"use strict";var gk=jb();Gb.exports=gk});var hl="__VERSION__";var me=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(me||{}),Pt=(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))(Pt||{});var sa=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(sa||{}),zs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(zs||{});var Ks=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Ks||{});import{assertNever as vl,assertNonNullable as $g,isNonNullable as na,ValueSubject as Js,Subject as Lg,Subscription as Cg,merge as Mg,observableFrom as Dg,fromEvent as ml,map as bl,tap as Sl,filterChanged as Og,isNullable as Xs,ErrorCategory as gl}from"@vkontakte/videoplayer-shared";var fl=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 oa=class{constructor(e){this.connection$=new Js(void 0);this.castState$=new Js("NOT_AVAILABLE");this.errorEvent$=new Lg;this.realCastState$=new Js("NOT_AVAILABLE");this.subscription=new Cg;var s;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=na((s=window.chrome)==null?void 0:s.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||fl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:gl.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,a,s;(s=(a=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:a.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){na(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Xs(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Xs(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(ml(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var s,n;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.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 vl(a.sessionState)}})).add(Mg(ml(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Sl(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),bl(a=>a.castState)),Dg([r.getCastState()])).pipe(Og(),bl(Bg),Sl(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var o;let s=a==="CONNECTED",n=na(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();$g(l);let u=l.getCastDevice(),c=(o=l.getMediaSession())==null?void 0:o.media.contentId;(Xs(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:u}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?na(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){var a;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(s){return}try{e.setOptions({receiverApplicationId:(a=this.params.receiverApplicationId)!=null?a:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:gl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Bg=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 vl(i)}};var FS=_e(eo(),1);var im=_e(Wa(),1);import{assertNever as Qf}from"@vkontakte/videoplayer-shared";var ee=(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:Qf(t)}return i},Fo=(i,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(i);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(i);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Qf(e)}};var I=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as zP,Subject as Qa,merge as zf}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new Qa;this.transitionEnded$=new Qa;this.transitionUpdated$=new Qa;this.forceChanged$=new Qa;this.stateChangeStarted$=zf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=zf(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||zP(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 KP}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 KP(i)}};import{assertNever as fr,assertNonNullable as Dt,debounce as Jf,ErrorCategory as Xf,fromEvent as Ot,isNonNullable as Zf,map as em,merge as tm,observableFrom as JP,Subject as XP,Subscription as qo,timeout as ZP,getHighestQuality as eA}from"@vkontakte/videoplayer-shared";var tA=5,rA=5,iA=500,rm=7e3,Zr=class{constructor(e){this.subscription=new qo;this.loadMediaTimeoutSubscription=new qo;this.videoState=new L("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((a==null?void 0: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:fr(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:fr(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:fr(e)}break}default:fr(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 qo;this.subscription.add(e),this.subscription.add(tm(this.videoState.stateChangeStarted$.pipe(em(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(em(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 XP;e.add(a.pipe(Jf(iA)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(Ot(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)>tA)&&a.next(o),s=o})),e.add(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(Ot(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(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<rA&&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:fr(n)}}),t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(Ot(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=tm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,JP(["init"])).pipe(Jf(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(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),I(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&I(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var a,s;let t=this.params.output.volume$.getValue(),r={volume:(a=e.volume)!=null?a:t.volume,muted:(s=e.muted)!=null?s: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){var u;let t=this.params.source,r,a,s;switch(e){case"MPEG":{let c=t[e];Dt(c);let d=eA(Object.keys(c));Dt(d);let p=c[d];Dt(p),r=p,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Dt(c),r=c.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 c=t[e];Dt(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Dt(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];Dt(c),r=ee(c.url),a="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Xf.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return fr(e)}let n=new chrome.cast.media.MediaInfo((u=this.params.meta.videoId)!=null?u:r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:l}=this.params.meta;return Zf(o)&&(n.metadata.title=o),Zf(l)&&(n.metadata.subtitle=l),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(ZP(rm).subscribe(()=>s(`timeout(${rm})`)))});(0,im.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:Xf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ei=i=>{i.removeAttribute("src"),i.load()};var am=i=>{try{i.pause(),i.playbackRate=0,ei(i),i.remove()}catch(e){console.error(e)}};var Uo=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)}},Ho=window.WeakMap?new WeakMap:new Uo,se=i=>{let e=i.querySelector("video"),t=!!e;return e?ei(e):(e=document.createElement("video"),i.appendChild(e)),Ho.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ne=i=>{let e=Ho.get(i);Ho.delete(i),e?ei(i):am(i)};import{assertNonNullable as ti,isNonNullable as Ue,isNullable as nA,fromEvent as mr,merge as sm,observableFrom as nm,filterChanged as om,map as ri,Subject as um,Subscription as oA,ValueSubject as uA,ErrorCategory as lA}from"@vkontakte/videoplayer-shared";import{isNonNullable as jo,isNullable as aA,Subscription as sA}from"@vkontakte/videoplayer-shared";var za=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),l=aA(a),u=new sA;return a&&u.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),l&&i.setState(n)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),l&&i.setState(c.to)},s)),u},qe=(i,e,t)=>za(e,()=>i.loop,r=>{jo(r)&&(i.loop=r)},{onError:t}),oe=(i,e,t,r)=>za(e,()=>({muted:i.muted,volume:i.volume}),a=>{jo(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,s)=>a===s||(a==null?void 0:a.muted)===(s==null?void 0:s.muted)&&(a==null?void 0:a.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Te=(i,e,t,r)=>za(e,()=>i.playbackRate,a=>{jo(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),ot=za;var cA=i=>["__",i.language,i.label].join("|"),dA=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Go=class i{constructor(){this.available$=new um;this.current$=new uA(void 0);this.error$=new um;this.subscription=new oA;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:lA.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(ot(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{Ue(s)&&this.setInternal(s)},{equal:(s,n)=>Ue(s)&&Ue(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(ri(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(ot(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{Ue(s)&&this.setExternal(s)},{equal:(s,n)=>Ue(s)&&Ue(n)&&s.length===n.length&&s.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(ri(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(ot(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(ot(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(mr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(sm(mr(e,"addtrack"),mr(e,"removetrack"),nm(["init"])).pipe(ri(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),om((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(sm(mr(e,"change"),nm(["init"])).pipe(ri(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),ri(r=>r&&this.htmlTextTrackToITextTrack(r).id),om()).subscribe(this.current$));let t=r=>{var a,s;return this.applyCueSettings((s=(a=r.target)==null?void 0:a.activeCues)!=null?s:null)};this.subscription.add(mr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let a=o=>{var u,c,d,p,h;let l=(c=(u=o.target)==null?void 0:u.cues)!=null?c:null;l&&l.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",a))};(n=r.track)==null||n.addEventListener("cuechange",a)})),this.subscription.add(mr(e,"removetrack").subscribe(r=>{var a;(a=r.track)==null||a.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;Ue(t.align)&&(a.align=t.align),Ue(t.position)&&(a.position=t.position),Ue(t.size)&&(a.size=t.size),Ue(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){var o,l;let{language:t,label:r}=e,a=e.id?e.id:cA(e),s=this.externalTracks.has(a),n=a.includes("auto");return s?{id:a,type:"external",isAuto:n,language:t,label:r,url:(o=this.externalTracks.get(a))==null?void 0:o.url}:{id:a,type:"internal",isAuto:n,language:t,label:r,url:(l=this.internalTracks.get(a))==null?void 0:l.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))(nA(e)||!dA(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){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)}},Ie=Go;var We=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 lm=i=>{let e=i;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Yo=i=>{let e=lm(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},cm=i=>{let e=lm(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as Ee,map as ut,merge as pm,filterChanged as hA,isNonNullable as hm,Subject as fA,filter as fm,mapTo as mm,combine as mA,once as bA,ErrorCategory as SA,ValueSubject as bm,getCurrentBrowser as gA,CurrentClientBrowser as vA}from"@vkontakte/videoplayer-shared";var pA=3,dm=(i,e,t=pA)=>{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 l=s-1;l>=0;l--)i.end(l)+t>=r&&(r=i.start(l));for(let l=s+1;l<i.length;l++)i.start(l)-t<=a&&(a=i.end(l))}}return{from:r,to:a}};var ue=i=>{let e=g=>Ee(i,g).pipe(mm(void 0)),r=pm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>Ee(i,g))).pipe(ut(g=>g.type==="ended"?i.readyState<2:i.readyState<3),hA()),a=pm(Ee(i,"progress"),Ee(i,"timeupdate")).pipe(ut(()=>dm(i.buffered,i.currentTime))),n=gA().browser===vA.Safari?mA({play:e("play").pipe(bA()),playing:e("playing")}).pipe(mm(void 0)):e("playing"),o=Ee(i,"volumechange").pipe(ut(()=>({muted:i.muted,volume:i.volume}))),l=Ee(i,"ratechange").pipe(ut(()=>i.playbackRate)),u=Ee(i,"error").pipe(fm(()=>!!(i.error||i.played.length)),ut(()=>{var y;let g=i.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:SA.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:(y=i.error)!=null?y:void 0}})),c=Ee(i,"timeupdate").pipe(ut(()=>i.currentTime)),d=new fA,p=.3,h;c.subscribe(g=>{i.loop&&hm(h)&&hm(g)&&h>=i.duration-p&&g<=p&&d.next(h),h=g});let m=e("pause").pipe(fm(()=>!i.error&&h!==i.duration)),b=Ee(i,"enterpictureinpicture"),S=Ee(i,"leavepictureinpicture"),T=new bm(cm(i));b.subscribe(()=>T.next(!0)),S.subscribe(()=>T.next(!1));let v=new bm(Yo(i));return Ee(i,"fullscreenchange").pipe(ut(()=>Yo(i))).subscribe(v),{playing$:n,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$:c,durationChange$:Ee(i,"durationchange").pipe(ut(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:l,inPiP$:T,inFullscreen$:v}};import{VideoQuality as lt}from"@vkontakte/videoplayer-shared";var ct=i=>{switch(i){case"mobile":return lt.Q_144P;case"lowest":return lt.Q_240P;case"low":return lt.Q_360P;case"sd":case"medium":return lt.Q_480P;case"hd":case"high":return lt.Q_720P;case"fullhd":case"full":return lt.Q_1080P;case"quadhd":case"quad":return lt.Q_1440P;case"ultrahd":case"ultra":return lt.Q_2160P}};var Jo=_e(ii(),1);import{isNonNullable as dt,isNullable as Qo,now as km,isHigher as zo,isHigherOrEqual as Am,isInvariantQuality as wm,isLower as Ko,isLowerOrEqual as kA,videoSizeToQuality as RA,assertNotEmptyArray as $A}from"@vkontakte/videoplayer-shared";var Wo=!1,Qe={},Em=i=>{Wo=i},xm=()=>{Qe={}},Pm=i=>{i(Qe)},ai=(i,e)=>{var t;Wo&&(Qe.meta=(t=Qe.meta)!=null?t:{},Qe.meta[i]=e)},te=class{constructor(e){this.name=e}next(e){var r,a;if(!Wo)return;Qe.series=(r=Qe.series)!=null?r:{};let t=(a=Qe.series[this.name])!=null?a:[];t.push([Date.now(),e]),Qe.series[this.name]=t}};var LA=new te("best_bitrate"),CA=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,Ka=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=km()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},MA='Assertion "ABR Tracks is empty array" failed',DA=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:l,history:u,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var R,M,w,q,Q;$A(i,MA);let p=r.usePixelRatio&&(R=window.devicePixelRatio)!=null?R:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},m=h&&RA(h),b=r.considerPlaybackRate&&dt(o)?o:1,S=i.filter(A=>!wm(A.quality)).sort((A,E)=>zo(A.quality,E.quality)?-1:1),T=(M=(0,Jo.default)(S,-1))==null?void 0:M.quality,v=(w=(0,Jo.default)(S,0))==null?void 0:w.quality,P=Qo(a)||dt(a.min)&&dt(a.max)&&Ko(a.max,a.min)||dt(a.min)&&v&&zo(a.min,v)||dt(a.max)&&T&&Ko(a.max,T),g=b*CA(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),y={},O=S.filter(A=>(m?Ko(A.quality,m):!0)?(dt(t)&&isFinite(t)&&dt(A.bitrate)?t-s>=A.bitrate*g:!0)?r.lazyQualitySwitch&&dt(r.minBufferToSwitchUp)&&l&&!wm(l.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&zo(A.quality,l.quality)?(y[A.quality]="Buffer",!1):!!c&&Am(A.quality,c)?(y[A.quality]="DroppedFramesLimit",!1):P||(Qo(a.max)||kA(A.quality,a.max))&&(Qo(a.min)||Am(A.quality,a.min))?!0:(y[A.quality]="FitsQualityLimits",!1):(y[A.quality]="FitsThroughput",!1):(y[A.quality]="FitsContainer",!1))[0];O&&O.bitrate&&LA.next(O.bitrate);let k=(q=O!=null?O:S[Math.ceil((S.length-1)/2)])!=null?q:i[0];k.quality!==((Q=u==null?void 0:u.last)==null?void 0:Q.quality)&&d({message:`
6
+ var os="2.0.105-dev.498f6d5a.0";var X=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(X||{}),Ne=(b=>(b.MPEG="MPEG",b.DASH="DASH_SEP",b.DASH_SEP="DASH_SEP",b.DASH_SEP_VK="DASH_SEP",b.DASH_WEBM="DASH_WEBM",b.DASH_WEBM_AV1="DASH_WEBM_AV1",b.DASH_WEBM_VK="DASH_WEBM",b.DASH_ONDEMAND="DASH_ONDEMAND",b.DASH_ONDEMAND_VK="DASH_ONDEMAND",b.DASH_LIVE="DASH_LIVE",b.DASH_LIVE_CMAF="DASH_LIVE_CMAF",b.DASH_LIVE_WEBM="DASH_LIVE_WEBM",b.HLS="HLS",b.HLS_ONDEMAND="HLS_ONDEMAND",b.HLS_JS="HLS",b.HLS_LIVE="HLS_LIVE",b.HLS_LIVE_CMAF="HLS_LIVE_CMAF",b.WEB_RTC_LIVE="WEB_RTC_LIVE",b))(Ne||{});var Gi=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(Gi||{}),jr=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(jr||{});var Yr=(s=>(s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip",s.INVISIBLE="invisible",s))(Yr||{});import{assertNever as hs,assertNonNullable as uu,isNonNullable as Wi,ValueSubject as qr,Subject as du,Subscription as lu,merge as cu,observableFrom as pu,fromEvent as ds,map as ls,tap as cs,filterChanged as hu,isNullable as zr,ErrorCategory as ps}from"@vkontakte/videoplayer-shared";var us=n=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",n),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});var Qi=class{constructor(e){this.connection$=new qr(void 0);this.castState$=new qr("NOT_AVAILABLE");this.errorEvent$=new du;this.realCastState$=new qr("NOT_AVAILABLE");this.subscription=new lu;var a;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Wi((a=window.chrome)==null?void 0:a.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=s=>{delete window.__onGCastApiAvailable,s&&this.initializeCastApi()},r||us("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ps.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Wi(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();zr(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();zr(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(ds(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,s;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(s=(a=i.getCurrentSession())==null?void 0:a.getMediaSession())==null?void 0:s.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 hs(r.sessionState)}})).add(cu(ds(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(cs(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),ls(r=>r.castState)),pu([i.getCastState()])).pipe(hu(),ls(mu),cs(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o;let a=r==="CONNECTED",s=Wi(this.connection$.getValue());if(a&&!s){let u=i.getCurrentSession();uu(u);let d=u.getCastDevice(),l=(o=u.getMediaSession())==null?void 0:o.media.contentId;(zr(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!a&&s&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r==="CONNECTED"?Wi(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:ps.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}},mu=n=>{switch(n){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 hs(n)}};import{assertNever as ms}from"@vkontakte/videoplayer-shared";var q=(n,e=0,t=0)=>{switch(t){case 0:return n.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return n;let i=new URL(n);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(n);return!i.searchParams.get("offset_p")&&e===0?n:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:ms(t)}return n},Kr=(n,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(n);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(n);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:ms(e)}};var T=(n,e,t=!1)=>{let i=n.getTransition();(t||!i||i.to===e)&&n.setState(e)};import{isNonNullable as fu,Subject as ji,merge as fs}from"@vkontakte/videoplayer-shared";var L=class{constructor(e){this.transitionStarted$=new ji;this.transitionEnded$=new ji;this.transitionUpdated$=new ji;this.forceChanged$=new ji;this.stateChangeStarted$=fs(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=fs(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||fu(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as bu}from"@vkontakte/videoplayer-shared";var bs=n=>{switch(n){case"MPEG":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":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 bu(n)}};import{assertNever as vt,assertNonNullable as tt,debounce as gs,ErrorCategory as Ss,fromEvent as it,isNonNullable as vs,map as ys,merge as Ts,observableFrom as gu,Subject as Su,Subscription as Jr,timeout as vu,getHighestQuality as yu}from"@vkontakte/videoplayer-shared";var Tu=5,Iu=5,Eu=500,Is=7e3,Bt=class{constructor(e){this.subscription=new Jr;this.loadMediaTimeoutSubscription=new Jr;this.videoState=new L("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&e!=="stopped"){this.seek(a.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:vt(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:vt(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:vt(e)}break}default:vt(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(bs(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 Jr;this.subscription.add(e),this.subscription.add(Ts(this.videoState.stateChangeStarted$.pipe(ys(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(ys(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new Su;e.add(r.pipe(gs(Eu)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(it(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(s=>{this.logRemoteEvent(s);let o=s.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-a)>Tu)&&r.next(o),a=o})),e.add(it(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(s=>{this.logRemoteEvent(s),this.params.output.duration$.next(s.value)}))}t(it(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(it(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(it(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:a}=this.params.connection,s=r.value,o=this.params.output.isBuffering$.getValue(),u=s===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Iu&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),T(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:vt(s)}}),t(it(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(it(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Ts(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,gu(["init"])).pipe(gs(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),T(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&T(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,a;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(a=e.muted)!=null?a:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var d;let t=this.params.source,i,r,a;switch(e){case"MPEG":{let l=t[e];tt(l);let c=yu(Object.keys(l));tt(c);let p=l[c];tt(p),i=p,r="video/mp4",a=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let l=t[e];tt(l),i=l.url,r="application/x-mpegurl",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":{let l=t[e];tt(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let l=t[e];tt(l),i=l.url,r="application/dash+xml",a=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let l=t[e];tt(l),i=q(l.url),r="application/x-mpegurl",a=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:Ss.VIDEO_PIPELINE,message:l,thrown:c}),c}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return vt(e)}let s=new chrome.cast.media.MediaInfo((d=this.params.meta.videoId)!=null?d:i,r);s.contentUrl=i,s.streamType=a,s.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return vs(o)&&(s.metadata.title=o),vs(u)&&(s.metadata.subtitle=u),s}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(vu(Is).subscribe(()=>a(`timeout(${Is})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Ss.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Vt=n=>{n.removeAttribute("src"),n.load()};var Es=n=>{try{n.pause(),n.playbackRate=0,Vt(n),n.remove()}catch(e){console.error(e)}};import{fromEvent as xu,Subscription as Pu}from"@vkontakte/videoplayer-shared";var Xr=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)}},Zr=window.WeakMap?new WeakMap:new Xr,ea=window.WeakMap?new WeakMap:new Map,ku=(n,e)=>{let t=0;return xu(n,"ratechange").subscribe(i=>{t++,t>=e&&(n.currentTime=n.currentTime,t=0)})},Z=(n,e=20)=>{let t=n.querySelector("video"),i=!!t;t?Vt(t):(t=document.createElement("video"),n.appendChild(t)),Zr.set(t,i);let r=new Pu;return r.add(ku(t,e)),ea.set(t,r),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ee=n=>{let e=ea.get(n);e==null||e.unsubscribe(),ea.delete(n);let t=Zr.get(n);Zr.delete(n),t?Vt(n):Es(n)};import{assertNonNullable as Ot,isNonNullable as Ee,isNullable as Lu,fromEvent as yt,merge as xs,observableFrom as Ps,filterChanged as ks,map as Nt,Subject as As,Subscription as $u,ValueSubject as Ru,ErrorCategory as Du}from"@vkontakte/videoplayer-shared";import{isNonNullable as ta,isNullable as Au,Subscription as wu}from"@vkontakte/videoplayer-shared";var Yi=(n,e,t,{equal:i=(s,o)=>s===o,changed$:r,onError:a}={})=>{let s=n.getState(),o=e(),u=Au(r),d=new wu;return r&&d.add(r.subscribe(l=>{let c=n.getState();i(l,c)&&n.setState(l)},a)),i(o,s)||(t(s),u&&n.setState(s)),d.add(n.stateChangeStarted$.subscribe(l=>{t(l.to),u&&n.setState(l.to)},a)),d},Ie=(n,e,t)=>Yi(e,()=>n.loop,i=>{ta(i)&&(n.loop=i)},{onError:t}),te=(n,e,t,i)=>Yi(e,()=>({muted:n.muted,volume:n.volume}),r=>{ta(r)&&(n.muted=r.muted,n.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),de=(n,e,t,i)=>Yi(e,()=>n.playbackRate,r=>{ta(r)&&(n.playbackRate=r)},{changed$:t,onError:i}),_e=Yi;var Mu=n=>["__",n.language,n.label].join("|"),Cu=(n,e)=>{if(n.id===e)return!0;let[t,i,r]=e.split("|");return n.language===i&&n.label===r},ia=class n{constructor(){this.available$=new As;this.current$=new Ru(void 0);this.error$=new As;this.subscription=new $u;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=a=>{this.error$.next({id:"TextTracksManager",category:Du.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(_e(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{Ee(a)&&this.setInternal(a)},{equal:(a,s)=>Ee(a)&&Ee(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Nt(a=>a.filter(({type:s})=>s==="internal"))),onError:r})),this.subscription.add(_e(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{Ee(a)&&this.setExternal(a)},{equal:(a,s)=>Ee(a)&&Ee(s)&&a.length===s.length&&a.every(({id:o},u)=>o===s[u].id),changed$:this.available$.pipe(Nt(a=>a.filter(({type:s})=>s==="external"))),onError:r})),this.subscription.add(_e(t.currentTextTrack,()=>{if(this.video)return;let a=this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(_e(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){Ot(this.video);let{textTracks:e}=this.video;this.subscription.add(yt(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(xs(yt(e,"addtrack"),yt(e,"removetrack"),Ps(["init"])).pipe(Nt(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ks((i,r)=>i.length===r.length&&i.every(({id:a},s)=>a===r[s].id))).subscribe(this.available$)),this.subscription.add(xs(yt(e,"change"),Ps(["init"])).pipe(Nt(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Nt(i=>i&&this.htmlTextTrackToITextTrack(i).id),ks()).subscribe(this.current$));let t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)==null?void 0:r.activeCues)!=null?a:null)};this.subscription.add(yt(e,"addtrack").subscribe(i=>{var a,s;(a=i.track)==null||a.addEventListener("cuechange",t);let r=o=>{var d,l,c,p,m;let u=(l=(d=o.target)==null?void 0:d.cues)!=null?l:null;u&&u.length&&(this.applyCueSettings((p=(c=o.target)==null?void 0:c.cues)!=null?p:null),(m=o.target)==null||m.removeEventListener("cuechange",r))};(s=i.track)==null||s.addEventListener("cuechange",r)})),this.subscription.add(yt(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;Ee(t.align)&&(r.align=t.align),Ee(t.position)&&(r.position=t.position),Ee(t.size)&&(r.size=t.size),Ee(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){Ot(this.video);let t=[...this.video.textTracks];return e?t:t.filter(n.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:i}=e,r=e.id?e.id:Mu(e),a=this.externalTracks.has(r),s=r.includes("auto");return a?{id:r,type:"external",isAuto:s,language:t,label:i,url:(o=this.externalTracks.get(r))==null?void 0:o.url}:{id:r,type:"internal",isAuto:s,language:t,label:i,url:(u=this.internalTracks.get(r))==null?void 0:u.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,s])=>s.language===r&&s.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){Ot(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(Lu(e)||!Cu(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){Ot(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){Ot(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},le=ia;var we=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 ws=n=>{let e=n;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},ra=n=>{let e=ws(n);return!!(e&&e.fullscreenElement&&e.fullscreenElement===n)},Ls=n=>{let e=ws(n);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===n)};import{fromEvent as ce,map as Fe,merge as Rs,filterChanged as Vu,isNonNullable as Ds,Subject as Ou,filter as Ms,mapTo as Cs,combine as Nu,once as _u,ErrorCategory as Fu,ValueSubject as Bs,getCurrentBrowser as Uu,CurrentClientBrowser as Hu,debounce as Gu}from"@vkontakte/videoplayer-shared";var Bu=3,$s=(n,e,t=Bu)=>{let i=0,r=0;for(let a=0;a<n.length;a++){let s=n.start(a),o=n.end(a);if(s<=e&&e<=o){if(i=s,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)n.end(u)+t>=i&&(i=n.start(u));for(let u=a+1;u<n.length;u++)n.start(u)-t<=r&&(r=n.end(u))}}return{from:i,to:r}};var ie=n=>{let e=S=>ce(n,S).pipe(Cs(void 0)),i=Rs(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(S=>ce(n,S))).pipe(Fe(S=>S.type==="ended"?n.readyState<2:n.readyState<3),Gu(100),Vu()),r=Rs(ce(n,"progress"),ce(n,"timeupdate")).pipe(Fe(()=>$s(n.buffered,n.currentTime))),s=Uu().browser===Hu.Safari?Nu({play:e("play").pipe(_u()),playing:e("playing")}).pipe(Cs(void 0)):e("playing"),o=ce(n,"volumechange").pipe(Fe(()=>({muted:n.muted,volume:n.volume}))),u=ce(n,"ratechange").pipe(Fe(()=>n.playbackRate)),d=ce(n,"error").pipe(Ms(()=>!!(n.error||n.played.length)),Fe(()=>{var y;let S=n.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:Fu.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(y=n.error)!=null?y:void 0}})),l=ce(n,"timeupdate").pipe(Fe(()=>n.currentTime)),c=new Ou,p=.3,m;l.subscribe(S=>{n.loop&&Ds(m)&&Ds(S)&&m>=n.duration-p&&S<=p&&c.next(m),m=S});let h=e("pause").pipe(Ms(()=>!n.error&&m!==n.duration)),f=ce(n,"enterpictureinpicture"),g=ce(n,"leavepictureinpicture"),v=new Bs(Ls(n));f.subscribe(()=>v.next(!0)),g.subscribe(()=>v.next(!1));let b=new Bs(ra(n));return ce(n,"fullscreenchange").pipe(Fe(()=>ra(n))).subscribe(b),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:ce(n,"durationchange").pipe(Fe(()=>n.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:v,inFullscreen$:b}};import{VideoQuality as Ue}from"@vkontakte/videoplayer-shared";var He=n=>{switch(n){case"mobile":return Ue.Q_144P;case"lowest":return Ue.Q_240P;case"low":return Ue.Q_360P;case"sd":case"medium":return Ue.Q_480P;case"hd":case"high":return Ue.Q_720P;case"fullhd":case"full":return Ue.Q_1080P;case"quadhd":case"quad":return Ue.Q_1440P;case"ultrahd":case"ultra":return Ue.Q_2160P}};import{isNonNullable as Ge,isNullable as sa,now as Us,isHigher as na,isHigherOrEqual as _s,isInvariantQuality as Fs,isLower as oa,isLowerOrEqual as Wu,videoSizeToQuality as Qu,assertNotEmptyArray as ju}from"@vkontakte/videoplayer-shared";var aa=!1,Le={},Vs=n=>{aa=n},Os=()=>{Le={}},Ns=n=>{n(Le)},_t=(n,e)=>{var t;aa&&(Le.meta=(t=Le.meta)!=null?t:{},Le.meta[n]=e)},K=class{constructor(e){this.name=e}next(e){var i,r;if(!aa)return;Le.series=(i=Le.series)!=null?i:{};let t=(r=Le.series[this.name])!=null?r:[];t.push([Date.now(),e]),Le.series[this.name]=t}};var Yu=new K("best_bitrate"),qu=(n,e,t)=>(e-t)*Math.pow(2,-10*n)+t,qi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Us()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},zu='Assertion "ABR Tracks is empty array" failed',Ku=(n,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:s,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var A,w,x,_,G;ju(n,zu);let p=i.usePixelRatio&&(A=window.devicePixelRatio)!=null?A:1,m=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*i.containerSizeFactor,height:e.height*p*i.containerSizeFactor},h=m&&Qu(m),f=i.considerPlaybackRate&&Ge(o)?o:1,g=n.filter(P=>!Fs(P.quality)).sort((P,I)=>na(P.quality,I.quality)?-1:1),v=(w=g.at(-1))==null?void 0:w.quality,b=(x=g.at(0))==null?void 0:x.quality,k=sa(r)||Ge(r.min)&&Ge(r.max)&&oa(r.max,r.min)||Ge(r.min)&&b&&na(r.min,b)||Ge(r.max)&&v&&oa(r.max,v),S=f*qu(s!=null?s:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),y={},$=g.filter(P=>(h?oa(P.quality,h):!0)?(Ge(t)&&isFinite(t)&&Ge(P.bitrate)?t-a>=P.bitrate*S:!0)?i.lazyQualitySwitch&&Ge(i.minBufferToSwitchUp)&&u&&!Fs(u.quality)&&(s!=null?s:0)<i.minBufferToSwitchUp&&na(P.quality,u.quality)?(y[P.quality]="Buffer",!1):!!l&&_s(P.quality,l)?(y[P.quality]="DroppedFramesLimit",!1):k||(sa(r.max)||Wu(P.quality,r.max))&&(sa(r.min)||_s(P.quality,r.min))?!0:(y[P.quality]="FitsQualityLimits",!1):(y[P.quality]="FitsThroughput",!1):(y[P.quality]="FitsContainer",!1))[0];$&&$.bitrate&&Yu.next($.bitrate);let R=(_=$!=null?$:g[Math.ceil((g.length-1)/2)])!=null?_:n[0];R.quality!==((G=d==null?void 0:d.last)==null?void 0:G.quality)&&c({message:`
7
7
  [available tracks]
8
- ${i.map(A=>`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate} }`).join(`
8
+ ${n.map(P=>`{ id: ${P.id}, quality: ${P.quality}, bitrate: ${P.bitrate} }`).join(`
9
9
  `)}
10
10
 
11
11
  [tuning]
12
- ${Object.entries(r!=null?r:{}).map(([A,E])=>`${A}: ${E}`).join(`
12
+ ${Object.entries(i!=null?i:{}).map(([P,I])=>`${P}: ${I}`).join(`
13
13
  `)}
14
14
 
15
15
  [limit params]
16
- containerQualityLimit: ${m},
16
+ containerQualityLimit: ${h},
17
17
  throughput: ${t},
18
- reserve: ${s},
18
+ reserve: ${a},
19
19
  playbackRate: ${o},
20
- playbackRateFactor: ${b},
21
- forwardBufferHealth: ${n},
22
- bitrateFactor: ${g},
23
- minBufferToSwitchUp: ${r.minBufferToSwitchUp},
24
- droppedVideoMaxQualityLimit: ${c},
25
- limitsAreInvalid: ${P},
26
- maxQualityLimit: ${a==null?void 0:a.max},
27
- minQualityLimit: ${a==null?void 0:a.min},
20
+ playbackRateFactor: ${f},
21
+ forwardBufferHealth: ${s},
22
+ bitrateFactor: ${S},
23
+ minBufferToSwitchUp: ${i.minBufferToSwitchUp},
24
+ droppedVideoMaxQualityLimit: ${l},
25
+ limitsAreInvalid: ${k},
26
+ maxQualityLimit: ${r==null?void 0:r.max},
27
+ minQualityLimit: ${r==null?void 0:r.min},
28
28
 
29
29
  [limited tracks]
30
- ${Object.entries(y).map(([A,E])=>`${A}: ${E}`).join(`
30
+ ${Object.entries(y).map(([P,I])=>`${P}: ${I}`).join(`
31
31
  `)||"All tracks are available"}
32
32
 
33
- [best track] ${O==null?void 0:O.quality}
34
- [selected track] ${k==null?void 0:k.quality}
35
- `});let F=k&&u&&u.history[k.id]&&km()-u.history[k.id]<=r.trackCooldown&&(!u.last||k.id!==u.last.id);if(k!=null&&k.id&&u&&!F&&u.recordSelection(k),F&&(u!=null&&u.last)){let A=u.last;return u==null||u.recordSwitch(A),d({message:`
36
- [last selected] ${A==null?void 0:A.quality}
37
- `}),A}return u==null||u.recordSwitch(k),k},pt=DA;var J=i=>new URL(i).hostname;import{assertNever as Dm,assertNonNullable as Om,combine as ew,debounce as tw,ErrorCategory as Bm,filter as Vm,filterChanged as rw,isNonNullable as ru,map as ts,merge as _m,observableFrom as iw,once as aw,Subscription as sw,ValueSubject as iu,videoQualityToHeight as nw,videoSizeToQuality as ow}from"@vkontakte/videoplayer-shared";var Rm=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))},le=async i=>{let e=i.muted;try{await i.play()}catch(t){if(!Rm(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(r){return Rm(r)&&(i.muted=!1,console.warn(r)),!1}}return!0};import{isNonNullable as Xa,isNullable as VA,assertNonNullable as oi}from"@vkontakte/videoplayer-shared";import{isNonNullable as $m,assertNonNullable as Ja,now as OA}from"@vkontakte/videoplayer-shared";function X(){return OA()}function Xo(i){return X()-i}function Zo(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,l=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let u=n.indexOf("?")>-1?"&":"?";return l&&(n+=u+"lowLat=1",u="&"),o&&(n+=u+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Lm(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function br(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,l=!1,u=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,S=()=>{if(l)return;Ja(c);let w=Xo(c),q;if(w<b){q=b-w,setTimeout(S,q);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new a,$()},T=w=>(s=w,M),v=w=>(d=w,M),P=()=>(h="json",M),g=()=>{if(!l){if(--u>=0){S(),r&&r();return}l=!0,d&&d(),t&&t()}},y=w=>(p=w,M),$=()=>{c=X(),n=new a,n.open("get",i);let w=0,q,Q=0,A=()=>(Ja(c),Math.max(c,Math.max(q||0,Q||0)));if(s&&n.addEventListener("progress",E=>{let V=X();s.updateChunk&&E.loaded>w&&(s.updateChunk(A(),E.loaded-w),w=E.loaded,q=V)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>g())),n.addEventListener("load",()=>{if(l)return;Ja(n);let E=n.status;if(E>=200&&E<300){if(n.response.byteLength&&s){let V=n.response.byteLength-w;V&&s.updateChunk&&s.updateChunk(A(),V)}n.responseType==="json"&&!Object.values(n.response).length?g():(d&&d(),e(n.response))}else g()}),n.addEventListener("error",()=>{g()}),p){let E=()=>{Ja(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=X(),n.removeEventListener("readystatechange",E))};n.addEventListener("readystatechange",E)}return n.responseType=h,n.send(),M},M={withBitrateReporting:T,withParallel:y,withJSONResponse:P,withRetryCount:w=>(u=w,M),withRetryInterval:(w,q)=>($m(w)&&(b=w),$m(q)&&(m=q),M),withTimeout:w=>(o=w,M),withFinally:v,send:$,abort:()=>{n&&(n.abort(),n=void 0),l=!0,d&&d()}};return M}var si=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 l=s.bytes*n/o;a+=l,s.start=t,s.bytes-=l}}}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 ni=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=X(),a=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=l=>{e._complete=1,e._responseData=l,e._downloadTime=X()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=br(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=X()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=X();if(Object.keys(this.activeRequests).length>=e)return!1;let 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(){Object.values(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}};var Za=1e4,eu=3;var _A=6e4,NA=10,FA=1,qA=500,ui=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.chunkRateEstimator=new si(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Zo(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=Zo(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",()=>{var a;!!e.error&&!this.destroyed&&(t(`Video element error: ${(a=e.error)==null?void 0:a.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||Xa(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=()=>{Lm(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 ni(eu,Za,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,l=null,u=null,c=!1,d=()=>{let g=s&&(!c||c===this.rep);return g||t("Not running!"),g},p=(g,y,$)=>{l&&l.abort(),l=br(this.urlResolver.resolve(g,!1),y,$,()=>this._retryCallback()).withTimeout(Za).withBitrateReporting(this.bitrateSwitcher).withRetryCount(eu).withFinally(()=>{l=null}).send()},h=(g,y,$)=>{oi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),y,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=g=>{let y=r.playbackRate;r.playbackRate!==g&&(t(`Playback rate switch: ${y}=>${g}`),r.playbackRate=g)},b=g=>{this.lowLatency=g,t(`lowLatency changed to ${g}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let g=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let $=X()-1e4,O=0;for(let F=0;F<this.bufferStates.length;F++){let R=this.bufferStates[F];g=Math.min(g,R.buf),R.ts<$&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${g} drop=${O} jitter=${this.sourceJitter}`);let k=g-FA;this.sourceJitter>=0?k-=this.sourceJitter/2:this.sourceJitter-=1,k>3?m(1.15):k>1?m(1.1):k>.3?m(1.05):m(1)}},T=g=>{let y,$=()=>y&&y.start?y.start.length:0,O=E=>y.start[E]/1e3,k=E=>y.dur[E]/1e3,F=E=>y.fragIndex+E,R=(E,V)=>({chunkIdx:F(E),startTS:O(E),dur:k(E),discontinuity:V}),M=()=>{let E=0;if(y&&y.dur){let V=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,U=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,G=V;this.sourceJitter>1&&(G+=this.sourceJitter-1);let C=y.dur.length-1;for(;C>=0&&(G-=y.dur[C],!(G<=0));--C);E=Math.min(C,y.dur.length-1-U),E=Math.max(E,0)}return R(E,!0)},w=E=>{let V=$();if(!(V<=0)){if(Xa(E)){for(let U=0;U<V;U++)if(O(U)>E)return R(U)}return M()}},q=E=>{let V=$(),U=E?E.chunkIdx+1:0,G=U-y.fragIndex;if(!(V<=0)){if(!E||G<0||G-V>NA)return t(`Resync: offset=${G} bChunks=${V} chunk=`+JSON.stringify(E)),M();if(!(G>=V))return R(U-y.fragIndex,!1)}},Q=(E,V,U)=>{u&&u.abort(),u=br(this.urlResolver.resolve(E,!0,this.lowLatency),V,U,()=>this._retryCallback()).withTimeout(Za).withRetryCount(eu).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(E,V)=>{Q(g,U=>{if(!d())return;y=U;let G=!!y.lowLatency;G!==this.lowLatency&&b(G);let C=0;for(let we=0;we<y.dur.length;++we)C+=y.dur[we];C>0&&(oi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(C/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,E(w(V))},()=>this._handleNetworkError())},nextChunk:q}},v=()=>{s=!1,o&&o.abort(),l&&l.abort(),u&&u.abort(),oi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:g=>{let{videoElement:y,logger:$}=this.params,O=T(e.jidxUrl),k,F,R,M,w=0,q,Q,A,E=()=>{q&&(clearTimeout(q),q=void 0);let _=Math.max(qA,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),re=w+_,he=X(),ve=Math.min(1e4,re-he);w=he;let it=()=>{u||d()&&O.seek(()=>{d()&&(w=X(),V(),E())})};ve>0?q=window.setTimeout(()=>{this.paused?E():it()},ve):it()},V=()=>{let _;for(;_=O.nextChunk(M);)M=_,gt(_);let re=O.nextChunk(R);if(re){if(R&&re.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?E():(v(),this._initPlayerWith(e));return}we(re)}else E()},U=(_,re)=>{if(!d()||!this.sourceBuffer)return;let he,ve,it,Qt=at=>{window.setTimeout(()=>{d()&&U(_,re)},at)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),Qt(100);else{let at=X(),vt=y.currentTime;!this.paused&&y.buffered.length>1&&Q===vt&&at-A>500&&($("Stall suspected; trying to fix"),this._fixupStall()),Q!==vt&&(Q=vt,A=at);let zt=this._getBufferSizeSec();if(zt>30)$(`Buffered ${zt} seconds; delaying appendBuffer`),Qt(2e3);else try{this.sourceBuffer.appendBuffer(_),this.videoPlayStarted?(this.bufferStates.push({ts:at,buf:zt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),re&&re()}catch(Rr){if(Rr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),it=this.sourceBuffer.buffered.length,it!==0&&(he=this.sourceBuffer.buffered.start(0),ve=vt,ve-he>4&&this.sourceBuffer.remove(he,ve-3)),Qt(1e3);else throw Rr}}},G=()=>{F&&k&&($([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(R)]),U(F,function(){F=null,V()}))},C=_=>e.fragUrlTemplate.replace("%%id%%",_.chunkIdx),we=_=>{d()&&h(C(_),(re,he)=>{if(d()){if(he/=1e3,F=re,R=_,n=_.startTS,he){let ve=Math.min(10,_.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ve:ve}G()}},()=>this._handleNetworkError())},gt=_=>{d()&&(oi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(C(_),!1)))},rt=_=>{d()&&(e.cachedHeader=_,U(_,()=>{k=!0,G()}))};s=!0,O.seek(_=>{if(d()){if(w=X(),!_){E();return}M=_,!VA(g)||_.startTS>g?we(_):(R=_,V())}},g),e.cachedHeader?rt(e.cachedHeader):p(e.headerUrl,rt,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),Xa(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,oi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Xa(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(p,h)=>{let m=X();if(this.chunkRateEstimator.addInterval(p,m,h)){let S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:S}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),n=-1/0,o,l=!0,u=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(l&&d>o&&Xo(n)<3e4)return;r(d)}l=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&u(),h},notifySwitch:d=>{let p=X();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=br(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Za).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;le(e).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!=null&&n.length?(n.forEach((l,u)=>{l.video&&a.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=u,o.push(l))}),o.sort(function(l,u){return l.video&&u.video?u.video.height-l.video.height:u.bitrate-l.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))},_A))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as UA,filter as Cm,fromEvent as HA,interval as jA,isHigher as GA,isInvariantQuality as YA,isLower as WA,merge as QA,Subject as Mm,Subscription as zA}from"@vkontakte/videoplayer-shared";var tu=class{constructor(){this.onDroopedVideoFramesLimit$=new Mm;this.subscription=new zA;this.playing=!1;this.tracks=[];this.forceChecker$=new Mm;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!YA(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;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&&GA(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n: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(HA(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=jA(this.droppedFramesChecker.checkTime).pipe(Cm(()=>this.playing),Cm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(UA(this.droppedFramesChecker.checkTime)),r=QA(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){var r,a;let t=(a=(r=Object.entries(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>WA(s,n)?-1:1))==null?void 0:r[0])==null?void 0:a[0];return e!=null?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}},es=tu;import{map as KA,Observable as JA}from"@vkontakte/videoplayer-shared";import{fromEvent as XA}from"@vkontakte/videoplayer-shared";var li=()=>{var i;return!!((i=window.documentPictureInPicture)!=null&&i.window)||!!document.pictureInPictureElement};var ZA=(i,e)=>new JA(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(l=>t.next(l.isIntersecting||li()))},{...r,...e});a.observe(i);let s=XA(document,"visibilitychange").pipe(KA(n=>!document.hidden||li())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),xe=ZA;var uw=["paused","playing","ready"],lw=["paused","playing","ready"],ci=class{constructor(e){this.subscription=new sw;this.videoState=new L("stopped");this.representations$=new iu([]);this.textTracksManager=new Ie;this.droppedFramesManager=new es;this.maxSeekBackTime$=new iu(1/0);this.zeroTime$=new iu(void 0);this.liveOffset=new We;this._dashCb=e=>{var t,r,a,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Bm.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let l of n){let u=(t=l.name)!=null?t:l.index.toString(10),c=(r=ct(l.name))!=null?r:ow(l.video),d=l.bitrate/1e3,p={...l.video};if(!c)continue;let h={id:u,quality:c,bitrate:d,size:p};o.push({track:h,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),((a=this.videoState.getTransition())==null?void 0:a.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:l})=>l===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),ru(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);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(lw.includes(e)&&(n||o)){this.prepare();return}if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&uw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ee(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 l=a==null?void 0:a.from;l&&l==="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 l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.dash.reinit(ee(this.params.source.url,l))}return;default:return Dm(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Bm.WTF,message:"DashLiveProvider internal logic error",thrown:a})};_m(this.videoState.stateChangeStarted$.pipe(ts(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ts(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=se(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),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(J(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.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=ue(this.video);this.subscription.add(this.representations$.pipe(ts(a=>a.map(({track:s})=>s)),Vm(a=>!!a.length),aw()).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(()=>{var a;((a=this.videoState.getTransition())==null?void 0:a.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(rw(),ts(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(ew({zeroTime:this.zeroTime$.pipe(Vm(ru)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(qe(this.video,this.params.desiredState.isLooped,t)).add(oe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Te(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).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(xe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&nw(a);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var s;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":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.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 Dm(a.to)}},t)).add(_m(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,iw(["init"])).pipe(tw(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),ne(this.video)}createLiveDashPlayer(){let e=new ui({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(){var u,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(u=this.params.desiredState.videoTrack.getTransition())==null?void 0:u.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),a=!r&&ru(t)?t:pt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput: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==null?void 0:a.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),l&&this.setAutoQuality(r),n||l||s!==o){let b=(m=e.find(({track:S})=>S.id===s))==null?void 0:m.representation;Om(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:a})=>a.id===e.id))==null?void 0:r.representation;Om(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(ee(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Nm=ci;var ht=(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 Dk,assertNonNullable as Ok,debounce as Bk,ErrorCategory as ku,filter as SS,filterChanged as Ru,fromEvent as Vk,isLowerOrEqual as gS,isNonNullable as _k,isInvariantQuality as Nk,map as Fk,merge as Is,observableFrom as qk,observeElementSize as Uk,once as vS,Subscription as Hk,ValueSubject as jk}from"@vkontakte/videoplayer-shared";var rs=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}},Sr=class extends rs{constructor(){super(),this.listeners||rs.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}},di=class{constructor(){Object.defineProperty(this,"signal",{value:new Sr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?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=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(a){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(di.prototype[Symbol.toStringTag]="AbortController",Sr.prototype[Symbol.toStringTag]="AbortSignal");function is(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 au(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!is({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(u,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(u,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:(l,u)=>{let c=s&&s.prototype.isPrototypeOf(l)?l.signal:u?u.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,n(l,u)])}return n(l,u)},Request:s}}var pi=is({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Fm=pi?au({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ze=pi?Fm.fetch:window.fetch,U0=pi?Fm.Request:window.Request,Ke=pi?di:window.AbortController,H0=pi?Sr:window.AbortSignal;var Zm=_e(ii(),1);var Je=()=>window.ManagedMediaSource||window.MediaSource,as=()=>{var i,e;return!!(window.ManagedMediaSource&&((e=(i=window.ManagedSourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},qm=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(i=window.SourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Um=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as ds,isAndroid as pw}from"@vkontakte/videoplayer-shared";var eb=pw(),Pe=document.createElement("video"),hw='video/mp4; codecs="avc1.42000a,mp4a.40.2"',fw='video/mp4; codecs="hev1.1.6.L93.B0"',tb='video/webm; codecs="vp09.00.10.08"',rb='video/webm; codecs="av01.0.00M.08"',mw='audio/mp4; codecs="mp4a.40.2"',bw='audio/webm; codecs="opus"',Hm,jm,Bt={mms:as(),mse:qm(),hls:!!((Hm=Pe.canPlayType)!=null&&Hm.call(Pe,"application/x-mpegurl")||(jm=Pe.canPlayType)!=null&&jm.call(Pe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Gm,Ym,ce={mp4:!!((Gm=Pe.canPlayType)!=null&&Gm.call(Pe,"video/mp4")),webm:!!((Ym=Pe.canPlayType)!=null&&Ym.call(Pe,"video/webm")),cmaf:!0},ss,Wm,ns,Qm,os,zm,us,Km,ls,Jm,cs,Xm,de={h264:!!((Wm=(ss=Je())==null?void 0:ss.isTypeSupported)!=null&&Wm.call(ss,hw)),h265:!!((Qm=(ns=Je())==null?void 0:ns.isTypeSupported)!=null&&Qm.call(ns,fw)),vp9:!!((zm=(os=Je())==null?void 0:os.isTypeSupported)!=null&&zm.call(os,tb)),av1:!!((Km=(us=Je())==null?void 0:us.isTypeSupported)!=null&&Km.call(us,rb)),aac:!!((Jm=(ls=Je())==null?void 0:ls.isTypeSupported)!=null&&Jm.call(ls,mw)),opus:!!((Xm=(cs=Je())==null?void 0:cs.isTypeSupported)!=null&&Xm.call(cs,bw))},gr=(de.h264||de.h265)&&de.aac,Vt,Sw=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:rb}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:tb}})]);Vt={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{Sw()}catch(i){console.error(i)}var vr=Bt.hls&&ce.mp4,ib=()=>Object.keys(de).filter(i=>de[i]),ab=(i,e=!1,t=!1)=>{let r=Bt.mse||Bt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&ce.mp4&&gr;case"DASH_WEBM":return r&&ce.webm&&de.vp9&&de.opus;case"DASH_WEBM_AV1":return r&&ce.webm&&de.av1&&de.opus;case"DASH_STREAMS":return r&&(ce.mp4&&gr||ce.webm&&(de.vp9||de.av1)&&(de.opus||de.aac));case"DASH_LIVE":return Bt.mse&&ce.mp4&&gr;case"DASH_LIVE_CMAF":return r&&ce.mp4&&gr&&ce.cmaf;case"DASH_ONDEMAND":return r&&ce.mp4&&gr;case"HLS":case"HLS_ONDEMAND":return vr||e&&Bt.mse&&ce.mp4&&gr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return vr;case"MPEG":return ce.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Bt.webrtc&&Bt.ws&&de.h264&&(ce.mp4||ce.webm);default:return ds(a)}})},hi=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 Vt?Vt[t].smooth?[t,e]:Vt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Vt?Vt[t].powerEfficient?[t,e]:Vt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:ds(i)}return[e,t]},sb=({webmCodec:i,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...hi(i),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(eb)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...hi(i),"DASH_SEP","DASH_ONDEMAND","DASH_STREAMS","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...hi(i),"DASH_STREAMS","HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...hi(i),"MPEG","DASH_SEP","DASH_ONDEMAND","DASH_STREAMS","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...hi(i),"DASH_ONDEMAND","DASH_STREAMS","HLS","HLS_ONDEMAND"];default:ds(e)}return vr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},nb=({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;if(eb)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 vr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},su=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],ob=i=>{if(i.size!==0){if(i.size===1)return i.values().next().value.split(".").at(0);for(let e of i){let t=(0,Zm.default)(e.split("."),0);if(t==="opus"||t==="vp09"||t==="av01")return t}return i.values().next().value.split(".").at(0)}};var fi=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};var ub=()=>window.matchMedia("(dynamic-range: high)").matches,nu=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["6E","7A","F4"].includes(o)}}return!1};import{abortable as Pu,assertNonNullable as Gt,combine as cS,ErrorCategory as mt,filter as Ss,filterChanged as wk,fromEvent as Ar,interval as Au,isNonNullable as dS,map as wu,merge as wr,Subject as pS,Subscription as hS,tap as kk,throttle as Rk,ValueSubject as pe}from"@vkontakte/videoplayer-shared";var Pr=_e(ii(),1);var gw=(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)},vw=i=>window.clearTimeout(i),lb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ou=lb?gw:window.requestIdleCallback,rO=lb?vw:window.cancelIdleCallback;var iS=_e(Wa(),1);import{assertNever as yw,CurrentClientBrowser as Tw,ErrorCategory as cb,getCurrentBrowser as Iw,Subject as db}from"@vkontakte/videoplayer-shared";var Ew=16,fb=!1,pb,hb;try{fb=Iw().browser===Tw.Safari&&parseInt((hb=(pb=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:pb[1])!=null?hb:"",10)<=Ew}catch(i){console.error(i)}var uu=class{constructor(e){this.bufferFull$=new db;this.error$=new db;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:cb.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};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;fb&&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(){var a;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((a=e.signal)!=null&&a.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:cb.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),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:yw(t)}}},mb=uu;var lu=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 Er,assertNonNullable as Xe,ErrorCategory as xr,fromEvent as yu,getExponentialDelay as Tu,once as yk,isNonNullable as rS,isNullable as Ze,Subject as Tk,Subscription as Ik,ValueSubject as Vi}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 yr=class extends N{};var mi=class extends N{};var bi=class extends N{constructor(t,r){super(t,r);this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let a=this.size-this.cursor;for(;a;){let s=this.readString(4);this.compatibleBrands.push(s),a-=4}}};var Si=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var vi=class extends N{constructor(t,r){super(t,r);this.data=this.content}};var Y=class extends N{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var _t=class extends Y{constructor(t,r){super(t,r);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 a=0;a<this.referenceCount;a++){let s=this.readUint32(),n=s>>>31,o=s<<1>>>1,l=this.readUint32();s=this.readUint32();let u=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:l,SAPType:u,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var yi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ii=class extends Y{constructor(t,r){super(t,r);switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var Ei=class extends Y{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var xi=class extends Y{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var Pi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends Y{constructor(t,r){super(t,r);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 wi=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends Y{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var $i=class extends N{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Li=class extends Y{constructor(t,r){super(t,r);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 Ci=class extends Y{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 Mi=class extends Y{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 Pw={ftyp:bi,moov:Si,moof:gi,mdat:vi,sidx:_t,trak:yi,mdia:Pi,mfhd:Ri,tkhd:Ai,traf:$i,tfhd:Li,tfdt:Ci,trun:Mi,minf:wi,sv3d:Ti,st3d:Ii,prhd:Ei,proj:ki,equi:xi,uuid:mi,unknown:yr},Nt=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(a){break}return t}createBox(e,t){let r=Pw[e];return r?new r(t,new i):new yr(t,new i)}};var Tr=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,a,s;(s=(r=this.index)[a=t.type])!=null||(r[a]=[]),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 ww=new TextDecoder("ascii"),kw=i=>ww.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Rw=i=>{let e=new _t(i,new Nt),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})},$w=(i,e)=>{let r=new Nt().parse(i),a=new Tr(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],l=n[n.length-1],u=o.source.byteOffset,d=l.source.byteOffset-o.source.byteOffset+l.size;return new DataView(i.buffer,u,d)},Lw=(i,e)=>{let r=new Nt().parse(i),s=new Tr(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"),l=s[s.length-1].children.find(d=>d.type==="trun"),u=0;return l.sampleDuration.length?u=l.sampleDuration.reduce((d,p)=>d+p,0):u=n.defaultSampleDuration*l.sampleCount,(Number(o.baseMediaDecodeTime)+u)/e*1e3},Cw=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 Nt().parse(i),a=new Tr(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 l=a.find("equi");l&&(e.projectionData.bounds.top=l.projectionBoundsTop,e.projectionData.bounds.right=l.projectionBoundsRight,e.projectionData.bounds.bottom=l.projectionBoundsBottom,e.projectionData.bounds.left=l.projectionBoundsLeft)}return e},bb={validateData:kw,parseInit:Cw,getIndexRange:()=>{},parseSegments:Rw,parseFeedableSegmentChunk:$w,getSegmentEndTime:Lw};import{assertNonNullable as du,isNonNullable as yb,isNullable as Dw}from"@vkontakte/videoplayer-shared";import{assertNever as Mw}from"@vkontakte/videoplayer-shared";var Sb={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"}},gb=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=Di(i,t),a=r in Sb,s=a?Sb[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 l=new DataView(i.buffer,i.byteOffset+t+1,o-1),u=n&255>>o,c=Di(l),d=u*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}},Di=(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},De=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Di(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:Mw(e)}},Ft=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=gb(r);if(!e(a))return;a.type==="master"&&Ft(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},vb=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=gb(i);return Ft(a.value,({tag:s,type:n,value:o})=>(s===17143?e=De(o,n):s===17026?t=De(o,n):s===17029&&(r=De(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Tb=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Ow=[231,22612,22743,167,171,163,160,175],Bw=i=>{let e,t,r,a,s=!1,n=!1,o=!1,l,u,c=!1,d=0;return Ft(i,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let S=De(m,h);u=Di(S)}else p!==21420&&(u=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=De(m,h):p===17545?a=De(m,h):p===21420&&u===475249515?l=De(m,h):p===374648427?Ft(m,({tag:S,type:T,value:v})=>S===30321?(c=De(v,T)===1,!1):!0):s&&n&&Tb.includes(p)&&(o=!0),!o}),du(e,"Failed to parse webm Segment start"),du(t,"Failed to parse webm Segment end"),du(a,"Failed to parse webm Segment duration"),r=r!=null?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:l,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Vw=i=>{if(Dw(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},_w=(i,e)=>{let t=!1,r=!1,a=o=>yb(o.time)&&yb(o.position),s=[],n;return Ft(i,({tag:o,type:l,value:u})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=De(u,l));break;case 183:break;case 241:n&&(n.position=De(u,l));break;default:t&&Tb.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,l)=>{let{time:u,position:c}=o,d=s[l+1];return{status:"none",time:{from:u,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Nw=i=>{let e=0,t=!1;try{Ft(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Ow.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[163,160,175].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Ib={validateData:vb,parseInit:Bw,getIndexRange:Vw,parseSegments:_w,parseFeedableSegmentChunk:Nw};var Oi=i=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(i);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return Ib;case"mp4":return bb}}throw new ReferenceError(`Unsupported mime type ${i}`)};var bu=_e(Yb(),1);import{isNonNullable as Qb,isNullable as zb}from"@vkontakte/videoplayer-shared";var Wb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Kb=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*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==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],a),hours:e(r==null?void 0:r[6],a),minutes:e(r==null?void 0:r[7],a),seconds:e(r==null?void 0:r[8],a)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},qt=(i,e)=>{let t=i;t=(0,bu.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[a,s]of Object.entries(r)){let n=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=(0,bu.default)(t,n,(o,l)=>zb(s)?o:zb(l)?s:s.padStart(parseInt(l,10),"0"))}return t},Xb=(i,e)=>{var g,y,$,O,k,F,R,M,w,q,Q,A,E,V,U,G,C,we,gt,rt,_,re,he,ve,it,Qt,at,vt,zt,Rr,ju,Gu,Yu,Wu,Qu,zu,Ku,Ju,Xu,Zu,el,tl,rl,il,al,sl,nl,ol;let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=($=(y=(g=s.querySelector("BaseURL"))==null?void 0:g.textContent)==null?void 0:y.trim())!=null?$:"",l=n.children,u=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),m=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],S=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=Kb(h);else if(m){let fe=Kb(m);Qb(fe)&&(p=fe)}else S&&(p=parseInt(S,10));let T=0,v=(k=(O=s.getAttribute("profiles"))==null?void 0:O.split(","))!=null?k:[];for(let fe of l){let ag=(F=fe.getAttribute("id"))!=null?F:"id"+(T++).toString(10),$r=(R=fe.getAttribute("mimeType"))!=null?R:"",Bs=(M=fe.getAttribute("codecs"))!=null?M:"",Vs=(w=fe.getAttribute("contentType"))!=null?w:$r==null?void 0:$r.split("/")[0],sg=(Q=(q=fe.getAttribute("profiles"))==null?void 0:q.split(","))!=null?Q:[],ng=(A=fe.getAttribute("lang"))!=null?A:void 0,og=(U=(V=(E=fe.querySelector("Label"))==null?void 0:E.textContent)==null?void 0:V.trim())!=null?U:void 0,ug=fe.querySelectorAll("Representation"),lg=fe.querySelector("SegmentTemplate"),Lr=Vs,z={id:ag,language:ng,label:og,codecs:Bs,hdr:Lr==="video"&&nu(Bs),mime:$r,representations:[]};for(let W of ug){let cg=(G=W.getAttribute("lang"))!=null?G:void 0,dg=(C=W.getAttribute("label"))!=null?C:void 0,pg=(rt=(gt=(we=W.querySelector("BaseURL"))==null?void 0:we.textContent)==null?void 0:gt.trim())!=null?rt:"",_s=new URL(pg||o,e).toString(),Kt=(_=W.getAttribute("mimeType"))!=null?_:$r,ea=(he=(re=W.getAttribute("codecs"))!=null?re:Bs)!=null?he:"",Ns;if(Vs==="text"){let yt=W.getAttribute("id")||"",Fs=yt.includes("_auto");Ns={id:yt,isAuto:Fs,kind:"text",url:_s}}else{let yt=(it=(ve=W.getAttribute("contentType"))!=null?ve:Kt==null?void 0:Kt.split("/")[0])!=null?it:Vs,Fs=(at=(Qt=fe.getAttribute("profiles"))==null?void 0:Qt.split(","))!=null?at:[],hg=parseInt((vt=W.getAttribute("width"))!=null?vt:"",10),ul=parseInt((zt=W.getAttribute("height"))!=null?zt:"",10),ll=parseInt((Rr=W.getAttribute("bandwidth"))!=null?Rr:"",10)/1e3,cl=(ju=W.getAttribute("frameRate"))!=null?ju:"",fg=(Gu=W.getAttribute("quality"))!=null?Gu:void 0,mg=cl?Wb(cl):void 0,bg=(Yu=W.getAttribute("id"))!=null?Yu:"id"+(T++).toString(10),Sg=yt==="video"?`${ul}p`:yt==="audio"?`${ll}Kbps`:ea,gg=`${bg}@${Sg}`,vg=[...v,...sg,...Fs],qs,yg=W.querySelector("SegmentBase"),Tt=(Wu=W.querySelector("SegmentTemplate"))!=null?Wu:lg;if(yg){let It=(zu=(Qu=W.querySelector("SegmentBase Initialization"))==null?void 0:Qu.getAttribute("range"))!=null?zu:"",[Et,Hs]=It.split("-").map(Jt=>parseInt(Jt,10)),st={from:Et,to:Hs},Cr=(Ku=W.querySelector("SegmentBase"))==null?void 0:Ku.getAttribute("indexRange"),[js,ta]=Cr?Cr.split("-").map(Jt=>parseInt(Jt,10)):[],Mr=Cr?{from:js,to:ta}:void 0;qs={type:"byteRange",url:_s,initRange:st,indexRange:Mr}}else if(Tt){let It={representationId:(Ju=W.getAttribute("id"))!=null?Ju:void 0,bandwidth:(Xu=W.getAttribute("bandwidth"))!=null?Xu:void 0},Et=parseInt((Zu=Tt.getAttribute("timescale"))!=null?Zu:"",10),Hs=(el=Tt.getAttribute("initialization"))!=null?el:"",st=Tt.getAttribute("media"),Cr=(rl=parseInt((tl=Tt.getAttribute("startNumber"))!=null?tl:"",10))!=null?rl:1,js=qt(Hs,It);if(!st)throw new ReferenceError("No media attribute in SegmentTemplate");let ta=(il=Tt.querySelectorAll("SegmentTimeline S"))!=null?il:[],Mr=[],Jt=0,Gs="",Ys=0;if(ta.length){let ra=Cr,ke=0;for(let Xt of ta){let Ve=parseInt((al=Xt.getAttribute("d"))!=null?al:"",10),xt=parseInt((sl=Xt.getAttribute("r"))!=null?sl:"",10)||0,ia=parseInt((nl=Xt.getAttribute("t"))!=null?nl:"",10);ke=Number.isFinite(ia)?ia:ke;let Ws=Ve/Et*1e3,Qs=ke/Et*1e3;for(let aa=0;aa<xt+1;aa++){let Ig=qt(st,{...It,segmentNumber:ra.toString(10),segmentTime:(ke+aa*Ve).toString(10)}),dl=(Qs!=null?Qs:0)+aa*Ws,Eg=dl+Ws;ra++,Mr.push({time:{from:dl,to:Eg},url:Ig})}ke+=(xt+1)*Ve,Jt+=(xt+1)*Ws}Ys=ke/Et*1e3,Gs=qt(st,{...It,segmentNumber:ra.toString(10),segmentTime:ke.toString(10)})}else if(Qb(p)){let ke=parseInt((ol=Tt.getAttribute("duration"))!=null?ol:"",10)/Et*1e3,Xt=Math.ceil(p/ke),Ve=0;for(let xt=1;xt<Xt;xt++){let ia=qt(st,{...It,segmentNumber:xt.toString(10),segmentTime:Ve.toString(10)});Mr.push({time:{from:Ve,to:Ve+ke},url:ia}),Ve+=ke}Ys=Ve,Gs=qt(st,{...It,segmentNumber:Xt.toString(10),segmentTime:Ve.toString(10)})}let Tg={time:{from:Ys,to:1/0},url:Gs};qs={type:"template",baseUrl:_s,segmentTemplateUrl:st,initUrl:js,totalSegmentsDurationMs:Jt,segments:Mr,nextSegmentBeyondManifest:Tg,timescale:Et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!yt||!Kt)continue;let Us={video:"video",audio:"audio",text:"text"}[yt];if(!Us)continue;Lr||(Lr=Us),Ns={id:gg,kind:Us,segmentReference:qs,profiles:vg,duration:p,bitrate:ll,mime:Kt,codecs:ea,width:hg,height:ul,fps:mg,quality:fg}}z.language||(z.language=cg),z.label||(z.label=dg),z.mime||(z.mime=Kt),z.codecs||(z.codecs=ea),z.hdr||(z.hdr=Lr==="video"&&nu(ea)),z.representations.push(Ns)}Lr&&a[Lr].push(z)}return{dynamic:u,liveAvailabilityStartTime:d,duration:p,streams:a}};var gu=_e(ii(),1);import{videoSizeToQuality as vk}from"@vkontakte/videoplayer-shared";var Zb=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{var o;let n=(o=s?ct(s):void 0)!=null?o:vk({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},eS=({id:i,bitrate:e})=>({id:i,bitrate:e}),ps=(i,e,t)=>{var a;let r=e.indexOf(i);return(a=(0,gu.default)(t,Math.round(t.length*r/e.length)))!=null?a:(0,gu.default)(t,-1)},tS=({language:i,label:e},{id:t,url:r,isAuto:a})=>({id:t,url:r,isAuto:a,type:"internal",language:i,label:e}),vu=i=>"url"in i,Ut=i=>i.type==="template",Bi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var _i=class{constructor(e,t,r,{fetcher:a,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:l=!1,manifest:u}){this.currentSegmentLength$=new Vi(0);this.onLastSegment$=new Vi(!1);this.fullyBuffered$=new Vi(!1);this.playingRepresentation$=new Vi(void 0);this.playingRepresentationInit$=new Vi(void 0);this.error$=new Tk;this.gaps=[];this.subscription=new Ik;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Ke;this.destroyAbortController=new Ke;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=Er(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);Xe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new mb(this.sourceBuffer),this.subscription.add(yu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:xr.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(yu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:xr.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{if(!this.sourceBuffer)return;let o=Math.min(this.bufferLimit,lu(this.sourceBuffer.buffered)*.8);this.bufferLimit=o,this.pruneBuffer(this.getCurrentPosition(),n)})),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);Xe(r,"No init buffer for starting representation"),Xe(a,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(a,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))}.bind(this));this.switchTo=Er(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);Xe(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(Ze(a)||Ze(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),Xe(r,"No segments for starting representation"),a=this.initData.get(e),!a||!(a instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield this.sourceBufferTaskQueue.append(a,this.downloadAbortController.signal);let s=this.getCurrentPosition();rS(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))}.bind(this));this.seekLive=Er(this.destroyAbortController.signal,async function*(e){var l,u;let t=(l=e==null?void 0:e.flatMap(c=>c.representations))!=null?l:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!Ut(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(u=this.switchingToRepresentationId)!=null?u:this.downloadingRepresentationId,a=this.representations.get(r);Xe(a);let s=this.segments.get(r);Xe(s,"No segments for starting representation");let n=this.initData.get(r);if(Xe(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=l,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(u!=null&&u.dynamic),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}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()){var u,c;if(Ze(e)||Ze(this.downloadingRepresentationId)||Ze(this.playingRepresentationId)||Ze(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(Xe(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((u=a==null?void 0:a.time.to)!=null?u:0)-((c=a==null?void 0:a.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=ht(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=a.time.to-e+100&&(s=h)}if(isFinite(this.bufferLimit)&&lu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=ht(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(o.includes(a))d="high";else{let p=(0,Pr.default)(o,0);p&&p.time.from-a.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status==="fed"&&!o.length&&ht(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,Pr.default)(r,-1);l&&l.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===l))}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;rS(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=e==null?void 0:e.streams[this.kind].find(a=>a.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,a,s,n;let t=(r=e==null?void 0:e.streams[this.kind].flatMap(o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Ut(o.segmentReference))return;let l=o.segmentReference.segments.map(p=>({...p,status:"none",size:void 0})),u=(a=this.segments.get(o.id))!=null?a:[],c=(n=(s=(0,Pr.default)(u,-1))==null?void 0:s.time.to)!=null?n:0,d=l==null?void 0:l.findIndex(p=>Math.floor(c)>=Math.floor(p.time.from)&&Math.floor(c)<=Math.floor(p.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=l.slice(d+1);this.segments.set(o.id,[...u,...p])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(let r of this.representations.values()){let a=r.segmentReference;if(!Ut(a))return;let s=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),n=qt(a.segmentTemplateUrl,{segmentTime:s}),o=(t=this.segments.get(r.id))!=null?t:[],l=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));l&&(l.time.to=e.segment.time.to),!!o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||o.push({status:"none",time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let a=r.find(l=>l.time.from<=e&&l.time.to>=e);return(o=a==null?void 0:a.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.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}},m)=>{let b=p<=r&&h>=r,S=p>r||b||m===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=r+T||h<=r+T;return(d==="none"||d==="partially_ejected"&&S&&v&&this.sourceBuffer&&!fi(this.sourceBuffer.buffered,r))&&S&&v});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,l=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=u||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")l.push(p);else break}return l}async loadSegments(e,t,r="auto"){t.segmentReference.type==="template"?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:l,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await Er(o,async function*(){let c=Tu(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:l,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(this.isActiveLowLatency()){let p=t.segmentReference.timescale,h=Oi(t.mime);a.segment.time.to=h.getSegmentEndTime(d,p)}l&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Bi(c)||this.failedDownloads++}}async loadByteRangeSegments(e,t,r="auto"){if(!e.length)return;for(let l of e)l.status="downloading",this.activeSegments.add({segment:l,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 Er(n,async function*(){let l=Tu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(u,l),yu(window,"online").pipe(yk()).subscribe(()=>{u(),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.failedDownloads=0}catch(l){this.abortActiveSegments(e),Bi(l)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(Ut(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,Pr.default)(e,0).byte.from,to:(0,Pr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,l)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:l,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:xr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ut(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=[],l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:xr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:l,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded: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:l}=o;if(o.representationId===t){if(s.aborted){a();continue}if(o.loadedBytes=r,o.loadedBytes>o.feedingBytes){let u=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),c=Oi(n.mime).parseFeedableSegmentChunk(u,this.isLive);c!=null&&c.byteLength&&(l.status="partially_fed",o.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),o.fedBytes+=c.byteLength)}}}}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)return;let l=o.segmentReference.type,u=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=l==="byteRange",h=p?d.byte.to-d.byte.from+1:u;if(c.representationId!==t||!(!p||d.byte.from>=r&&d.byte.to<r+e.byteLength))continue;if(s.aborted){n();continue}let b=p?d.byte.from-r:0,S=p?d.byte.to-r:e.byteLength,T=b<a,v=S<=a;if(d.status==="downloading"&&T&&v){d.status="downloaded";let P=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(P,s).then(g=>g&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(h,a-b),c.loadedBytes>c.feedingBytes)){let P=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),g=c.loadedBytes===h?P:Oi(o.mime).parseFeedableSegmentChunk(P);g!=null&&g.byteLength&&(d.status="partially_fed",c.feedingBytes+=g.byteLength,this.sourceBufferTaskQueue.append(g,s).then(y=>{if(s.aborted)n();else if(y)c.fedBytes+=g.byteLength,c.fedBytes===h&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<h)return;n()}}))}}}onSegmentFullyAppended(e,t){var r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",vu(e.segment)&&(e.segment.size=e.fedBytes);for(let a of this.representations.values())if(a.id!==t)for(let s of(r=this.segments.get(a.id))!=null?r:[])s.status==="fed"&&s.time.from===e.segment.time.from&&s.time.to===e.segment.time.to&&(s.status="none");this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);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||(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,iS.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?Er(this.destroyAbortController.signal,async function*(){let o=Tu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Oi(e.mime),a)).then(async o=>{if(!o)return;let{init:l,dataView:u,segments:c}=o,d=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ut(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:xr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,r=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Ze(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,l=u=>{var d;s=Math.min(s,u.time.from),n=Math.max(n,u.time.to);let c=vu(u)?(d=u.size)!=null?d:0:u.byte.to-u.byte.from;a+=c};for(let u of this.segments.values())for(let c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&l(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let u of this.segments.values())for(let c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&l(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let u=0;u<this.sourceBuffer.buffered.length;u++){let c=this.sourceBuffer.buffered.start(u)*1e3,d=this.sourceBuffer.buffered.end(u)*1e3;for(let p of this.segments.values())for(let h of p)if(h.status==="none"&&Math.round(h.time.from)<=Math.round(c)&&Math.round(h.time.to)>=Math.round(d)){s=c,n=d;break}}if(o=isFinite(s)&&isFinite(n),!o&&r){a=0,s=1/0,n=-1/0;let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let c of this.segments.values())for(let d of c)d.time.from>e+u&&d.status==="fed"&&l(d)}return o=isFinite(s)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(s,n):!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)}}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){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ou(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:xr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Ze(this.sourceBuffer)||Ze(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let a=Math.round(this.sourceBuffer.buffered.start(r)*1e3),s=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:a,to:s})}let t=1;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),l=e.some(c=>c.from-t<=n&&c.to+t>=o),u=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);l||(u.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 Ni=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var aS=i=>{var s;let e=i.get("X-Delivery-Type"),t=i.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,a=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:a}};import{abortable as Fi,assertNever as sS,fromEvent as nS,merge as Ek,now as Iu,Subscription as xk,ValueSubject as Eu}from"@vkontakte/videoplayer-shared";var hs=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Eu(void 0);this.lastConnectionReused$=new Eu(void 0);this.lastRequestFirstBytes$=new Eu(void 0);this.abortAllController=new Ke;this.subscription=new xk;this.fetchManifest=Fi(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=Ni(t));let r=yield ze(t,{signal:this.abortAllController.signal}).catch(qi);return r?(this.onHeadersReceived(r.headers),r.text()):null}.bind(this));this.fetch=Fi(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:l=!1}={}){var k,F;let u=e,c=new Headers;if(r)switch(t){case 0:{c.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let R=new URL(u,location.href);R.searchParams.append("bytes",`${r.from}-${r.to}`),u=R.toString();break}default:sS(t)}this.requestQuic&&(u=Ni(u));let d=this.abortAllController.signal,p;if(n){let R=new Ke;if(p=Ek(nS(this.abortAllController.signal,"abort"),nS(n,"abort")).subscribe(()=>{try{R.abort()}catch(M){qi(M)}}),this.abortAllController.signal.aborted||n.aborted)try{R.abort()}catch(M){qi(M)}d=R.signal}let h=Iu(),m=yield ze(u,{priority:s,headers:c,signal:d}).catch(qi),b=Iu();if(!m)return p==null||p.unsubscribe(),null;if((k=this.throughputEstimator)==null||k.addRawRtt(b-h),!m.ok||!m.body)return p==null||p.unsubscribe(),Promise.reject(new Error(`Fetch error ${m.status}: ${m.statusText}`));if(this.onHeadersReceived(m.headers),!a&&!o)return p==null||p.unsubscribe(),m.arrayBuffer();let[S,T]=m.body.tee(),v=S.getReader();o&&((F=this.throughputEstimator)==null||F.trackStream(T,l));let P=0,g=new Uint8Array(0),y=!1,$=R=>{p==null||p.unsubscribe(),y=!0,qi(R)},O=Fi(d,async function*({done:R,value:M}){if(P===0&&this.lastRequestFirstBytes$.next(Iu()-h),d.aborted){p==null||p.unsubscribe();return}if(!R&&M){let w=new Uint8Array(g.length+M.length);w.set(g),w.set(M,g.length),g=w,P+=M.byteLength,a==null||a(new DataView(g.buffer),P),yield v==null?void 0:v.read().then(O,$)}}.bind(this));return yield v==null?void 0:v.read().then(O,$),p==null||p.unsubscribe(),y?null:g.buffer}.bind(this));this.fetchByteRangeRepresentation=Fi(this.abortAllController.signal,async function*(e,t,r){var T;if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,l=!1,u,c;e.indexRange&&(u=e.indexRange.from,c=e.indexRange.to,l=s+1===u,l&&(n=Math.min(u,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),m=(T=e.indexRange)!=null?T:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(l)b=new DataView(d,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let S=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:S}}.bind(this));this.fetchTemplateRepresentation=Fi(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=r}onHeadersReceived(e){let{type:t,reused:r}=aS(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}async fetchRepresentation(e,t,r="auto"){var s,n;let{type:a}=e;switch(a){case"byteRange":return(s=await this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=await this.fetchTemplateRepresentation(e,r))!=null?n:null;default:sS(a)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},qi=i=>{if(!Bi(i))throw i};var Ht=(i,e,t)=>t*e+(1-t)*i,xu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,oS=(i,e,t,r)=>{let a=0,s=t,n=xu(i,e),o=e<r?e:r;for(let l=0;l<o;l++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as Pk,ValueSubject as uS}from"@vkontakte/videoplayer-shared";var ft=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new uS(e.initial),this.debounced$=new uS(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new te(`raw_${t}`),this.smoothedSeries$=new te(`smoothed_${t}`),this.reportedSeries$=new te(`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)&&(Pk(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 fs=class extends ft{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=Ht(this.slow,t,this.params.emaAlphaSlow),this.fast=Ht(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var ms=class extends ft{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=xu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ht(this.emaSmoothed,t,this.params.emaAlpha);let a=oS(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var bs=class extends ft{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?Ht(this.smoothed,t,this.params.emaAlpha):t}};var jt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new fs({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ms({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new bs({initial:e,label:"liveEdgeDelay",...t})}};var lS=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var fS=["timeupdate","progress","play","seeked","stalled","waiting"];var gs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new hS;this.representationSubscription=new hS;this.state$=new L("none");this.currentVideoRepresentation$=new pe(void 0);this.currentVideoRepresentationInit$=new pe(void 0);this.currentAudioRepresentation$=new pe(void 0);this.currentVideoSegmentLength$=new pe(0);this.currentAudioSegmentLength$=new pe(0);this.error$=new pS;this.lastConnectionType$=new pe(void 0);this.lastConnectionReused$=new pe(void 0);this.lastRequestFirstBytes$=new pe(void 0);this.isLive$=new pe(!1);this.liveDuration$=new pe(0);this.liveAvailabilityStartTime$=new pe(void 0);this.bufferLength$=new pe(0);this.liveLoadBufferLength$=new pe(0);this.livePositionFromPlayer$=new pe(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new pS;this.gapWatchdogActive=!1;this.destroyController=new Ke;this.initManifest=Pu(this.destroyController.signal,async function*(e,t,r){var a;this.element=e,this.manifestUrlString=ee(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(a=this.manifest)!=null&&a.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:mt.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Pu(this.destroyController.signal,async function*(){var s;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:mt.NETWORK,message:"Failed to load manifest",thrown:n})});if(!e)return null;let t;try{t=Xb(e!=null?e:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:mt.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!t)return null;let r=(n,o,l)=>{var u,c,d,p;return!!((c=(u=this.element)==null?void 0:u.canPlayType)!=null&&c.call(u,o)&&((p=(d=Je())==null?void 0:d.isTypeSupported)!=null&&p.call(d,`${o}; codecs="${l}"`))||n==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((s=t.duration)!=null?s: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 l=t.streams[n].filter(({mime:d,codecs:p})=>r(n,d,p)),u=new Set(l.map(({codecs:d})=>d)),c=ob(u);if(c&&(a[n]=l.filter(({codecs:d})=>d.startsWith(c))),n==="video"){let d=ub(),p=this.tuning.preferHDR,h=a.video.some(b=>b.hdr),m=a.video.some(b=>!b.hdr);d&&p&&h?a.video=a.video.filter(b=>b.hdr):m&&(a.video=a.video.filter(b=>!b.hdr))}}return{...t,streams:a}}.bind(this));this.initRepresentations=Pu(this.destroyController.signal,async function*(e,t,r){var d;Gt(this.manifest),Gt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=p=>{this.representationSubscription.add(Ar(p,"error").pipe(Ss(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:mt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Um():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&as())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=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new _i("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],dS(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new _i("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}if(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(Au(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=Fo(this.manifestUrlString,2);this.manifestUrlString=ee(this.manifestUrlString,m+1e3,2)}})),this.representationSubscription.add(wr(...fS.filter(p=>p!=="waiting").map(p=>Ar(this.element,p))).pipe(wu(p=>this.element?ht(this.element.buffered,this.element.currentTime*1e3):0),wk(),Ss(p=>!!p),kk(p=>{var h;(h=this.stallWatchdogSubscription)==null||h.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(Ss(h=>this.isActiveLowLatency&&!!h)).subscribe(h=>this.liveEstimatedDelay.next(h))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(h=>{if(!this.isActiveLowLatency||!h)return;let m=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=h-m,v=1;Math.abs(T)>b&&(v=1+Math.sign(T)*S),lS(this.element,v)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,S;let m=0;if(h){let T=((S=(b=this.element)==null?void 0:b.currentTime)!=null?S:0)*1e3;m=Math.min(...this.bufferManagers.map(P=>{var g,y;return(y=(g=P.getLiveSegmentsToLoadState(this.manifest))==null?void 0:g.to)!=null?y:T}))-T}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(cS({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Rk(1e3)).subscribe(async({liveLoadBufferLength:h,bufferLength:m})=>{if(Gt(this.element),this.isUpdatingLive)return;let b=this.element.playbackRate,S=Fo(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,v=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*b),P=this.tuning.dashCmafLive.normalizedActualBufferOffset*b,g=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*b,y=this.isActiveLowLatency?m:h,$=3;if(this.isActiveLowLatency?$=0:y<v+g&&y>=v?$=1:S!==0&&y<v&&($=2),isFinite(h)&&(p=h>p?h:p),$===2||$===1){let O=p-(v+P),k=this.normolizeLiveOffset(Math.trunc(S+O/b)),F=Math.abs(k-S),R;!h||F<=this.tuning.dashCmafLive.offsetCalculationError?R=S:k>0&&F>this.tuning.dashCmafLive.offsetCalculationError?R=k:R=0,this.manifestUrlString=ee(this.manifestUrlString,R,2)}$!==3&&$!==0&&(p=0,this.updateLive())}))}let l=wr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(wu(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),u=wr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(wu(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(wr(this.forceEnded$,cS({allBuffersFull:l,someBufferEnded:u}).pipe(Ss(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream()}catch(h){this.error$.next({id:"EndOfStream",category:mt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(wr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)}));let c=[(d=this.manifest.duration)!=null?d:0,...[...this.manifest.streams.audio,...this.manifest.streams.video].flatMap(p=>p.representations).flatMap(p=>{var h;return(h=p.duration)!=null?h:0})];this.source.duration=Math.max(...c)/1e3,this.audioBufferManager&&dS(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(r=this.audioBufferManager)!=null&&r.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Au(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:mt.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new hs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=jt.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var r,a,s,n;Gt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=ee(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((a=this.videoBufferManager)==null?void 0:a.seekLive((r=this.manifest)==null?void 0:r.streams.video)),await((n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.streams.audio)))}initBuffer(){Gt(this.element),this.state$.setState("running"),this.subscription.add(wr(...fS.map(e=>Ar(this.element,e)),Ar(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:mt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Ar(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Ar(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&fi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);this.isLive$.getValue()&&this.seekLive(this.liveLastSeekOffset)}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Au(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:mt.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return r==null?void 0:r.switchTo(t)}seek(e,t){var a,s,n,o,l;Gt(this.element),Gt(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((a=this.videoBufferManager.findSegmentStartTime(e))!=null?a:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),fi(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(l=this.audioBufferManager)==null||l.maintain(r),this.element.currentTime=r/1e3}stop(){var e,t,r;(e=this.element)==null||e.querySelectorAll("source").forEach(a=>a.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,r=[],a=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let s of this.bufferManagers)for(let n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from-a<=t&&n.to+a>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){let s=Math.max(...r)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,s===1/0?this.forceEnded$.next():this.element.currentTime=s/1e3}}};var vs=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!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?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 mS=`attribute vec2 a_vertex;
33
+ [best track] ${$==null?void 0:$.quality}
34
+ [selected track] ${R==null?void 0:R.quality}
35
+ `});let N=R&&d&&d.history[R.id]&&Us()-d.history[R.id]<=i.trackCooldown&&(!d.last||R.id!==d.last.id);if(R!=null&&R.id&&d&&!N&&d.recordSelection(R),N&&(d!=null&&d.last)){let P=d.last;return d==null||d.recordSwitch(P),c({message:`
36
+ [last selected] ${P==null?void 0:P.quality}
37
+ `}),P}return d==null||d.recordSwitch(R),R},We=Ku;var j=n=>new URL(n).hostname;import{assertNever as Ys,assertNonNullable as qs,combine as bd,debounce as gd,ErrorCategory as zs,filter as Sd,filterChanged as vd,isNonNullable as pa,map as Zi,merge as Ks,observableFrom as yd,Subscription as Td,ValueSubject as ha,videoQualityToHeight as Id,videoSizeToQuality as Ed}from"@vkontakte/videoplayer-shared";var Hs=n=>{if(n instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(n.message))throw n;return!(n instanceof DOMException&&(n.code===20||n.name==="AbortError"))},re=async n=>{let e=n.muted;try{await n.play()}catch(t){if(!Hs(t))return!1;if(e)return console.warn(t),!1;n.muted=!0;try{await n.play()}catch(i){return Hs(i)&&(n.muted=!1,console.warn(i)),!1}}return!0};import{isNonNullable as Ki,isNullable as Zu,assertNonNullable as Ht}from"@vkontakte/videoplayer-shared";import{isNonNullable as Gs,assertNonNullable as zi,now as Ju}from"@vkontakte/videoplayer-shared";function Y(){return Ju()}function ua(n){return Y()-n}function da(n){let e=n.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=s=>i.test(s);return{resolve:(s,o,u=!1)=>{r(s)||(s.startsWith("/")||(s="/"+s),s=t+s);let d=s.indexOf("?")>-1?"&":"?";return u&&(s+=d+"lowLat=1",d="&"),o&&(s+=d+"_rnd="+Math.floor(999999999*Math.random())),s}}}function Ws(n,e,t){let i=(...r)=>{t.apply(null,r),n.removeEventListener(e,i)};n.addEventListener(e,i)}function Tt(n,e,t,i){let r=window.XMLHttpRequest,a,s,o,u=!1,d=0,l,c,p=!1,m="arraybuffer",h=7e3,f=2e3,g=()=>{if(u)return;zi(l);let x=ua(l),_;if(x<f){_=f-x,setTimeout(g,_);return}f*=2,f>h&&(f=h),s&&s.abort(),s=new r,C()},v=x=>(a=x,w),b=x=>(c=x,w),k=()=>(m="json",w),S=()=>{if(!u){if(--d>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},y=x=>(p=x,w),C=()=>{l=Y(),s=new r,s.open("get",n);let x=0,_,G=0,P=()=>(zi(l),Math.max(l,Math.max(_||0,G||0)));if(a&&s.addEventListener("progress",I=>{let O=Y();a.updateChunk&&I.loaded>x&&(a.updateChunk(P(),I.loaded-x),x=I.loaded,_=O)}),o&&(s.timeout=o,s.addEventListener("timeout",()=>S())),s.addEventListener("load",()=>{if(u)return;zi(s);let I=s.status;if(I>=200&&I<300){if(s.response.byteLength&&a){let O=s.response.byteLength-x;O&&a.updateChunk&&a.updateChunk(P(),O)}s.responseType==="json"&&!Object.values(s.response).length?S():(c&&c(),e(s.response))}else S()}),s.addEventListener("error",()=>{S()}),p){let I=()=>{zi(s),s.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(G=Y(),s.removeEventListener("readystatechange",I))};s.addEventListener("readystatechange",I)}return s.responseType=m,s.send(),w},w={withBitrateReporting:v,withParallel:y,withJSONResponse:k,withRetryCount:x=>(d=x,w),withRetryInterval:(x,_)=>(Gs(x)&&(f=x),Gs(_)&&(h=_),w),withTimeout:x=>(o=x,w),withFinally:b,send:C,abort:()=>{s&&(s.abort(),s=void 0),u=!0,c&&c()}};return w}var Ft=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{let s=t-a.start,o=a.end-a.start;i+=s;let u=a.bytes*s/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){let a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Ut=class{constructor(e,t,i,r,a){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let i=Y(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Y()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Tt(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(s),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Y()}_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=Y();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let a={};return a.send=()=>{let s=this.activeRequests[e]||this.completeRequests[e];if(s)s._cb=t,s._errorCB=i,s._retryCB=r,s._finallyCB=a._finallyCB,s._error||s._complete?(this._removeFromActive(e),setTimeout(()=>{s._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(s._responseData,s._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(s._errorMsg)),a._finallyCB&&a._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(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=s=>(a._finallyCB=s,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};var Ji=1e4,la=3;var ed=6e4,td=10,id=1,rd=500,Gt=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.chunkRateEstimator=new Ft(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=da(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=da(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,a,s=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&s>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ki(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let s=()=>{Ws(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):s()})};s()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Ut(la,Ji,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,a=!1,s=null,o=null,u=null,d=null,l=!1,c=()=>{let S=a&&(!l||l===this.rep);return S||t("Not running!"),S},p=(S,y,C)=>{u&&u.abort(),u=Tt(this.urlResolver.resolve(S,!1),y,C,()=>this._retryCallback()).withTimeout(Ji).withBitrateReporting(this.bitrateSwitcher).withRetryCount(la).withFinally(()=>{u=null}).send()},m=(S,y,C)=>{Ht(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(S,!1),y,C,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},h=S=>{let y=i.playbackRate;i.playbackRate!==S&&(t(`Playback rate switch: ${y}=>${S}`),i.playbackRate=S)},f=S=>{this.lowLatency=S,t(`lowLatency changed to ${S}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)h(1);else{let S=this._getBufferSizeSec();if(this.bufferStates.length<5){h(1);return}let C=Y()-1e4,$=0;for(let N=0;N<this.bufferStates.length;N++){let A=this.bufferStates[N];S=Math.min(S,A.buf),A.ts<C&&$++}this.bufferStates.splice(0,$),t(`update playback rate; minBuffer=${S} drop=${$} jitter=${this.sourceJitter}`);let R=S-id;this.sourceJitter>=0?R-=this.sourceJitter/2:this.sourceJitter-=1,R>3?h(1.15):R>1?h(1.1):R>.3?h(1.05):h(1)}},v=S=>{let y,C=()=>y&&y.start?y.start.length:0,$=I=>y.start[I]/1e3,R=I=>y.dur[I]/1e3,N=I=>y.fragIndex+I,A=(I,O)=>({chunkIdx:N(I),startTS:$(I),dur:R(I),discontinuity:O}),w=()=>{let I=0;if(y&&y.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,U=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=O;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let z=y.dur.length-1;for(;z>=0&&(Q-=y.dur[z],!(Q<=0));--z);I=Math.min(z,y.dur.length-1-U),I=Math.max(I,0)}return A(I,!0)},x=I=>{let O=C();if(!(O<=0)){if(Ki(I)){for(let U=0;U<O;U++)if($(U)>I)return A(U)}return w()}},_=I=>{let O=C(),U=I?I.chunkIdx+1:0,Q=U-y.fragIndex;if(!(O<=0)){if(!I||Q<0||Q-O>td)return t(`Resync: offset=${Q} bChunks=${O} chunk=`+JSON.stringify(I)),w();if(!(Q>=O))return A(U-y.fragIndex,!1)}},G=(I,O,U)=>{d&&d.abort(),d=Tt(this.urlResolver.resolve(I,!0,this.lowLatency),O,U,()=>this._retryCallback()).withTimeout(Ji).withRetryCount(la).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,O)=>{G(S,U=>{if(!c())return;y=U;let Q=!!y.lowLatency;Q!==this.lowLatency&&f(Q);let z=0;for(let ke=0;ke<y.dur.length;++ke)z+=y.dur[ke];z>0&&(Ht(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(z/y.dur.length)),r({name:"index",zeroTime:y.zeroTime,shiftDuration:y.shiftDuration}),this.sourceJitter=y.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,y.jitter/1e3)):1,I(x(O))},()=>this._handleNetworkError())},nextChunk:_}},b=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),Ht(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:S=>{let{videoElement:y,logger:C}=this.params,$=v(e.jidxUrl),R,N,A,w,x=0,_,G,P,I=()=>{_&&(clearTimeout(_),_=void 0);let B=Math.max(rd,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),J=x+B,se=Y(),oe=Math.min(1e4,J-se);x=se;let Ce=()=>{d||c()&&$.seek(()=>{c()&&(x=Y(),O(),I())})};oe>0?_=window.setTimeout(()=>{this.paused?I():Ce()},oe):Ce()},O=()=>{let B;for(;B=$.nextChunk(w);)w=B,Bi(B);let J=$.nextChunk(A);if(J){if(A&&J.discontinuity){C("Detected discontinuity; restarting playback"),this.paused?I():(b(),this._initPlayerWith(e));return}ke(J)}else I()},U=(B,J)=>{if(!c()||!this.sourceBuffer)return;let se,oe,Ce,mt=Be=>{window.setTimeout(()=>{c()&&U(B,J)},Be)};if(this.sourceBuffer.updating)C("Source buffer is updating; delaying appendBuffer"),mt(100);else{let Be=Y(),Ke=y.currentTime;!this.paused&&y.buffered.length>1&&G===Ke&&Be-P>500&&(C("Stall suspected; trying to fix"),this._fixupStall()),G!==Ke&&(G=Ke,P=Be);let ft=this._getBufferSizeSec();if(ft>30)C(`Buffered ${ft} seconds; delaying appendBuffer`),mt(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:Be,buf:ft}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),J&&J()}catch(Dt){if(Dt.name==="QuotaExceededError")C("QuotaExceededError; delaying appendBuffer"),Ce=this.sourceBuffer.buffered.length,Ce!==0&&(se=this.sourceBuffer.buffered.start(0),oe=Ke,oe-se>4&&this.sourceBuffer.remove(se,oe-3)),mt(1e3);else throw Dt}}},Q=()=>{N&&R&&(C([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(A)]),U(N,function(){N=null,O()}))},z=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),ke=B=>{c()&&m(z(B),(J,se)=>{if(c()){if(se/=1e3,N=J,A=B,s=B.startTS,se){let oe=Math.min(10,B.dur/se);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*oe:oe}Q()}},()=>this._handleNetworkError())},Bi=B=>{c()&&(Ht(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(z(B),!1)))},Rt=B=>{c()&&(e.cachedHeader=B,U(B,()=>{R=!0,Q()}))};a=!0,$.seek(B=>{if(c()){if(x=Y(),!B){I();return}w=B,!Zu(S)||B.startTS>S?ke(B):(A=B,O())}},S),e.cachedHeader?Rt(e.cachedHeader):p(e.headerUrl,Rt,()=>this._handleNetworkError())},stop:b,getTimestampSec:()=>s},l}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),Ki(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ht(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ki(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let p,m,h;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(m=this._getBufferSizeSec(),h=c/this.bitrate,m>10&&h>.8||m>15&&h>.5||m>20&&h>.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}`)},a=(()=>({updateChunk:(p,m)=>{let h=Y();if(this.chunkRateEstimator.addInterval(p,h,m)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:h-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),s=-1/0,o,u=!0,d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&ua(s)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,p)=>{let m=a.updateChunk(c,p);return m&&d(),m},notifySwitch:c=>{let p=Y();c<o&&(s=p),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Tt(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ji).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;re(e).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,a=s=>{let o=[];return s!=null&&s.length?(s.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ed))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as ad,filter as Qs,fromEvent as sd,interval as nd,isHigher as od,isInvariantQuality as ud,isLower as dd,merge as ld,Subject as js,Subscription as cd}from"@vkontakte/videoplayer-shared";var ca=class{constructor(){this.onDroopedVideoFramesLimit$=new js;this.subscription=new cd;this.playing=!1;this.tracks=[];this.forceChecker$=new js;this.isForceCheckCounter=0;this.prevTotalVideoFrames=0;this.prevDroppedVideoFrames=0;this.limitCounts={};this.handleChangeVideoQuality=()=>{let e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!ud(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var s;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,a=1-(i-r)/i;!isNaN(a)&&a>0&&this.log({message:`[dropped]. current dropped percent: ${a}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(a)&&a>=this.droppedFramesChecker.percentLimit&&od(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((s=this.limitCounts[this.currentQuality])!=null?s: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.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(sd(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=nd(this.droppedFramesChecker.checkTime).pipe(Qs(()=>this.playing),Qs(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(ad(this.droppedFramesChecker.checkTime)),i=ld(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[s])=>dd(a,s)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?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}},Xi=ca;import{map as pd,Observable as hd}from"@vkontakte/videoplayer-shared";import{fromEvent as md}from"@vkontakte/videoplayer-shared";var Wt=()=>{var n;return!!((n=window.documentPictureInPicture)!=null&&n.window)||!!document.pictureInPictureElement};var fd=(n,e)=>new hd(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((s,o)=>{s.forEach(u=>t.next(u.isIntersecting||Wt()))},{...i,...e});r.observe(n);let a=md(document,"visibilitychange").pipe(pd(s=>!document.hidden||Wt())).subscribe(s=>t.next(s));return()=>{r.unobserve(n),a.unsubscribe}}),pe=fd;var xd=["paused","playing","ready"],Pd=["paused","playing","ready"],Qt=class{constructor(e){this.subscription=new Td;this.videoState=new L("stopped");this.representations$=new ha([]);this.textTracksManager=new le;this.droppedFramesManager=new Xi;this.maxSeekBackTime$=new ha(1/0);this.zeroTime$=new ha(void 0);this.liveOffset=new we;this._dashCb=e=>{var t,i,r,a;switch(e.name){case"buffering":{let s=e.isBuffering;this.params.output.isBuffering$.next(s);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:zs.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let s=e.manifest,o=[];for(let u of s){let d=(t=u.name)!=null?t:u.index.toString(10),l=(i=He(u.name))!=null?i:Ed(u.video),c=u.bitrate/1e3,p={...u.video};if(!l)continue;let m={id:d,quality:l,bitrate:c,size:p};o.push({track:m,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let s=e.quality,o=(a=this.representations$.getValue().find(({representation:u})=>u===s))==null?void 0:a.track;this.params.output.hostname$.next(new URL(s.headerUrl,this.params.source.url).hostname),pa(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:s,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(s,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(a)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Pd.includes(e)&&(s||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&a.state==="requested"&&xd.includes(e)){this.seek(a.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(q(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(q(this.params.source.url,u))}return;default:return Ys(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:zs.WTF,message:"DashLiveProvider internal logic error",thrown:r})};Ks(this.videoState.stateChangeStarted$.pipe(Zi(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Zi(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Z(e.container,e.tuning.audioVideoSyncRate),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),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(j(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.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let i=ie(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(Zi(r=>r.map(({track:a})=>a)))}),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(vd(),Zi(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(bd({zeroTime:this.zeroTime$.pipe(Sd(pa)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ie(this.video,this.params.desiredState.isLooped,t)).add(te(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(de(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(pe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{let a=r&&Id(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((a=this.params.desiredState.playbackState.getTransition())==null?void 0:a.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 Ys(r.to)}},t)).add(Ks(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,yd(["init"])).pipe(gd(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),ee(this.video)}createLiveDashPlayer(){let e=new Gt({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(){var d,l,c,p,m,h;let e=this.representations$.getValue(),t=(l=(d=this.params.desiredState.videoTrack.getTransition())==null?void 0:d.to)!=null?l:this.params.desiredState.videoTrack.getState(),i=(p=(c=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:c.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&pa(t)?t:We(e.map(({track:f})=>f),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput: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}),a=r==null?void 0:r.id,s=this.params.desiredState.videoTrack.getTransition(),o=(m=this.params.desiredState.videoTrack.getState())==null?void 0:m.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(s||a!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),s||u||a!==o){let f=(h=e.find(({track:g})=>g.id===a))==null?void 0:h.representation;qs(f,"Representations missing"),this.dash.startPlay(f,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;qs(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(q(this.params.source.url,s)),r&&this.dash.pause(),this.liveOffset.resetTo(s,r)}};var Js=Qt;var $e=(n,e)=>{let t=0;for(let i=0;i<n.length;i++){let r=n.start(i)*1e3,a=n.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};import{assertNever as dl,assertNonNullable as Nn,debounce as ll,ErrorCategory as wa,filter as cl,filterChanged as _n,fromEvent as pl,isLowerOrEqual as Fn,isNonNullable as hl,videoSizeToQuality as Un,map as pr,merge as hr,observableFrom as ml,observeElementSize as fl,once as bl,Subscription as gl,ValueSubject as Hn}from"@vkontakte/videoplayer-shared";var jt=(n,e)=>{for(let t=0;t<n.length;t++)if(n.start(t)*1e3<=e&&n.end(t)*1e3>e)return!0;return!1};import{abortable as Pa,assertNonNullable as lt,combine as nr,ErrorCategory as je,filter as or,filterChanged as Rn,fromEvent as kt,interval as ka,isNonNullable as Dn,map as Aa,merge as At,Subject as Mn,Subscription as Cn,tap as rl,throttle as al,ValueSubject as ae}from"@vkontakte/videoplayer-shared";import{assertNever as kd,CurrentClientBrowser as Ad,ErrorCategory as Xs,getCurrentBrowser as wd,Subject as Zs}from"@vkontakte/videoplayer-shared";var Ld=16,rn=!1,en,tn;try{rn=wd().browser===Ad.Safari&&parseInt((tn=(en=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:en[1])!=null?tn:"",10)<=Ld}catch(n){console.error(n)}var ma=class{constructor(e){this.bufferFull$=new Zs;this.error$=new Zs;this.queue=[];this.currentTask=null;this.destroyed=!1;this.completeTask=()=>{var e;try{if(this.currentTask){let t=(e=this.currentTask.signal)==null?void 0:e.aborted;this.currentTask.callback(!t),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:"BufferTaskQueueUnknown",category:Xs.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{let a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;rn&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(let{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.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:Xs.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:kd(t)}}},an=ma;var fa=n=>{let e=0;for(let t=0;t<n.length;t++)e+=n.end(t)-n.start(t);return e*1e3};import{abortable as xt,assertNever as qd,assertNonNullable as xe,ErrorCategory as Pt,fromEvent as va,getExponentialDelay as ya,isNonNullable as In,isNullable as ve,once as zd,Subject as Kd,Subscription as Jd,ValueSubject as mi}from"@vkontakte/videoplayer-shared";var V=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,a=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,a,r),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 r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var It=class extends V{};var Yt=class extends V{};var qt=class extends V{constructor(t,i){super(t,i);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 zt=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Kt=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Jt=class extends V{constructor(t,i){super(t,i);this.data=this.content}};var H=class extends V{constructor(t,i){super(t,i);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var rt=class extends H{constructor(t,i){super(t,i);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,o=a<<1>>>1,u=this.readUint32();a=this.readUint32();let d=a>>>28,l=a<<3>>>3;this.segments.push({referenceType:s,referencedSize:o,subsegmentDuration:u,SAPType:d,SAPDeltaTime:l})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var Xt=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Zt=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ei=class extends H{constructor(t,i){super(t,i);switch(this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ti=class extends H{constructor(t,i){super(t,i);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ii=class extends H{constructor(t,i){super(t,i);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ri=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ai=class extends H{constructor(t,i){super(t,i);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 si=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ni=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oi=class extends H{constructor(t,i){super(t,i);this.sequenceNumber=this.readUint32()}};var ui=class extends V{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var di=class extends H{constructor(t,i){super(t,i);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 li=class extends H{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var ci=class extends H{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Rd={ftyp:qt,moov:zt,moof:Kt,mdat:Jt,sidx:rt,trak:Xt,mdia:ri,mfhd:oi,tkhd:ai,traf:ui,tfhd:di,tfdt:li,trun:ci,minf:si,sv3d:Zt,st3d:ei,prhd:ti,proj:ni,equi:ii,uuid:Yt,unknown:It},at=class n{constructor(e={}){this.options={offset:0,...e}}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let a=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),s=this.createBox(a,new DataView(e.buffer,e.byteOffset+i));if(!s.size)break;t.push(s),i+=s.size}catch(r){break}return t}createBox(e,t){let i=Rd[e];return i?new i(t,new n):new It(t,new n)}};var Et=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,a;(a=(i=this.index)[r=t.type])!=null||(i[r]=[]),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 Md=new TextDecoder("ascii"),Cd=n=>Md.decode(new DataView(n.buffer,n.byteOffset+4,4))==="ftyp",Bd=n=>{let e=new rt(n,new at),t=e.earliestPresentationTime/e.timescale*1e3,i=n.byteOffset+n.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");let s=a.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+s},byte:{from:i,to:i+a.referencedSize-1}};return t+=s,i+=a.referencedSize,o})},Vd=(n,e)=>{let i=new at().parse(n),r=new Et(i),a=r.findAll("moof"),s=e?r.findAll("uuid"):r.findAll("mdat");if(!(s.length&&a.length))return null;let o=a[0],u=s[s.length-1],d=o.source.byteOffset,c=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(n.buffer,d,c)},Od=(n,e)=>{let i=new at().parse(n),a=new Et(i).findAll("traf"),s=a[a.length-1].children.find(c=>c.type==="tfhd"),o=a[a.length-1].children.find(c=>c.type==="tfdt"),u=a[a.length-1].children.find(c=>c.type==="trun"),d=0;return u.sampleDuration.length?d=u.sampleDuration.reduce((c,p)=>c+p,0):d=s.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+d)/e*1e3},Nd=n=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},i=new at().parse(n),r=new Et(i);if(r.find("sv3d")){e.is3dVideo=!0;let s=r.find("st3d");s&&(e.stereoMode=s.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},sn={validateData:Cd,parseInit:Nd,getIndexRange:()=>{},parseSegments:Bd,parseFeedableSegmentChunk:Vd,getSegmentEndTime:Od};import{assertNonNullable as ga,isNonNullable as dn,isNullable as Fd}from"@vkontakte/videoplayer-shared";import{assertNever as _d}from"@vkontakte/videoplayer-shared";var nn={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"}},on=n=>{let e=n.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let i=pi(n,t),r=i in nn,a=r?nn[i].type:"binary",s=n.getUint8(t),o=0;s&128?o=1:s&64?o=2:s&32?o=3:s&16?o=4:s&8?o=5:s&4?o=6:s&2?o=7:s&1&&(o=8);let u=new DataView(n.buffer,n.byteOffset+t+1,o-1),d=s&255>>o,l=pi(u),c=d*2**((o-1)*8)+l,p=t+o,m;return p+c>n.byteLength?m=new DataView(n.buffer,n.byteOffset+p):m=new DataView(n.buffer,n.byteOffset+p,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:p,tagSize:p+c,value:m,valueSize:c}},pi=(n,e=n.byteLength)=>{switch(e){case 1:return n.getUint8(0);case 2:return n.getUint16(0);case 3:return n.getUint8(0)*2**16+n.getUint16(1);case 4:return n.getUint32(0);case 5:return n.getUint8(0)*2**32+n.getUint32(1);case 6:return n.getUint16(0)*2**32+n.getUint32(2);case 7:{let t=n.getUint8(0)*281474976710656+n.getUint16(1)*4294967296+n.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Se=(n,e)=>{switch(e){case"int":return n.getInt8(0);case"uint":return pi(n);case"float":return n.byteLength===4?n.getFloat32(0):n.getFloat64(0);case"string":return new TextDecoder("ascii").decode(n);case"utf8":return new TextDecoder("utf-8").decode(n);case"date":return new Date(Date.UTC(2001,0)+n.getInt8(0)).getTime();case"master":return n;case"binary":return n;default:_d(e)}},st=(n,e)=>{let t=0;for(;t<n.byteLength;){let i=new DataView(n.buffer,n.byteOffset+t),r=on(i);if(!e(r))return;r.type==="master"&&st(r.value,e),t=r.value.byteOffset-n.byteOffset+r.valueSize}},un=n=>{if(n.getUint32(0)!==440786851)return!1;let e,t,i,r=on(n);return st(r.value,({tag:a,type:s,value:o})=>(a===17143?e=Se(o,s):a===17026?t=Se(o,s):a===17029&&(i=Se(o,s)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var ln=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Ud=[231,22612,22743,167,171,163,160,175],Hd=n=>{let e,t,i,r,a=!1,s=!1,o=!1,u,d,l=!1,c=0;return st(n,({tag:p,type:m,value:h,valueSize:f})=>{if(p===21419){let g=Se(h,m);d=pi(g)}else p!==21420&&(d=void 0);return p===408125543?(e=h.byteOffset,t=h.byteOffset+f):p===357149030?a=!0:p===290298740?s=!0:p===2807729?i=Se(h,m):p===17545?r=Se(h,m):p===21420&&d===475249515?u=Se(h,m):p===374648427?st(h,({tag:g,type:v,value:b})=>g===30321?(l=Se(b,v)===1,!1):!0):a&&s&&ln.includes(p)&&(o=!0),!o}),ga(e,"Failed to parse webm Segment start"),ga(t,"Failed to parse webm Segment end"),ga(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Gd=n=>{if(Fd(n.cuesSeekPosition))return;let e=n.segmentStart+n.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Wd=(n,e)=>{let t=!1,i=!1,r=o=>dn(o.time)&&dn(o.position),a=[],s;return st(n,({tag:o,type:u,value:d})=>{switch(o){case 475249515:t=!0;break;case 187:s&&r(s)&&a.push(s),s={};break;case 179:s&&(s.time=Se(d,u));break;case 183:break;case 241:s&&(s.position=Se(d,u));break;default:t&&ln.includes(o)&&(i=!0)}return!(t&&i)}),s&&r(s)&&a.push(s),a.map((o,u)=>{let{time:d,position:l}=o,c=a[u+1];return{status:"none",time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Qd=n=>{let e=0,t=!1;try{st(n,i=>i.tag===524531317?i.tagSize<=n.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Ud.includes(i.tag)?(e+i.tagSize<=n.byteLength&&(e+=i.tagSize,t||(t=[163,160,175].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=n.byteLength&&t?new DataView(n.buffer,n.byteOffset,e):null},cn={validateData:un,parseInit:Hd,getIndexRange:Gd,parseSegments:Wd,parseFeedableSegmentChunk:Qd};import{isNonNullable as hn,isNullable as mn}from"@vkontakte/videoplayer-shared";var pn=n=>{if(n.includes("/")){let e=n.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(n)};var fn=n=>{if(!n.startsWith("P"))return;let e=(s,o)=>{let u=s?parseFloat(s.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(n),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},nt=(n,e)=>{let t=n;t=t.replaceAll("$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,a]of Object.entries(i)){let s=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(s,(o,u)=>mn(a)?o:mn(u)?a:a.padStart(parseInt(u,10),"0"))}return t},gn=(n,e)=>{var S,y,C,$,R,N,A,w,x,_,G,P,I,O,U,Q,z,ke,Bi,Rt,B,J,se,oe,Ce,mt,Be,Ke,ft,Dt,Ga,Wa,Qa,ja,Ya,qa,za,Ka,Ja,Xa,Za,es;let i=new DOMParser().parseFromString(n,"application/xml"),r={video:[],audio:[],text:[]},a=i.children[0],s=a.getElementsByTagName("Period")[0],o=(C=(y=(S=a.querySelector("BaseURL"))==null?void 0:S.textContent)==null?void 0:y.trim())!=null?C:"",u=s.children,d=a.getAttribute("type")==="dynamic",l=a.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,p,m=a.getAttribute("mediaPresentationDuration"),h=s.getAttribute("duration"),f=a.getElementsByTagName("vk:Attrs")[0],g=f==null?void 0:f.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)p=fn(m);else if(h){let ue=fn(h);hn(ue)&&(p=ue)}else g&&(p=parseInt(g,10));let v=0,b=(R=($=a.getAttribute("profiles"))==null?void 0:$.split(","))!=null?R:[],k=b.includes("urn:webm:dash:profile:webm-on-demand:2012")||b.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let ue of u){let Vi=ue.getAttribute("mimeType"),qo=ue.getAttribute("codecs"),ts=(N=ue.getAttribute("contentType"))!=null?N:Vi==null?void 0:Vi.split("/")[0],zo=(w=(A=ue.getAttribute("profiles"))==null?void 0:A.split(","))!=null?w:[],is=ue.querySelectorAll("Representation"),Ko=ue.querySelector("SegmentTemplate");if(ts==="text"){for(let W of is){let Ve=W.getAttribute("id")||"",Oi=ue.getAttribute("lang"),bt=ue.getAttribute("label"),Vr=(G=(_=(x=W.querySelector("BaseURL"))==null?void 0:x.textContent)==null?void 0:_.trim())!=null?G:"",Or=new URL(Vr||o,e).toString(),Ni=Ve.includes("_auto");r.text.push({id:Ve,lang:Oi,label:bt,isAuto:Ni,kind:"text",url:Or})}continue}for(let W of is){let Ve=(P=W.getAttribute("mimeType"))!=null?P:Vi,Oi=(O=(I=W.getAttribute("codecs"))!=null?I:qo)!=null?O:"",bt=(Q=(U=W.getAttribute("contentType"))!=null?U:Ve==null?void 0:Ve.split("/")[0])!=null?Q:ts,Vr=(ke=(z=ue.getAttribute("profiles"))==null?void 0:z.split(","))!=null?ke:[],Or=parseInt((Bi=W.getAttribute("width"))!=null?Bi:"",10),Ni=parseInt((Rt=W.getAttribute("height"))!=null?Rt:"",10),rs=parseInt((B=W.getAttribute("bandwidth"))!=null?B:"",10)/1e3,as=(J=W.getAttribute("frameRate"))!=null?J:"",Jo=(se=W.getAttribute("quality"))!=null?se:void 0,Xo=as?pn(as):void 0,Zo=(oe=W.getAttribute("id"))!=null?oe:(v++).toString(10),eu=bt==="video"?`${Ni}p`:bt==="audio"?`${rs}Kbps`:Oi,tu=`${Zo}@${eu}`,iu=(Be=(mt=(Ce=W.querySelector("BaseURL"))==null?void 0:Ce.textContent)==null?void 0:mt.trim())!=null?Be:"",ss=new URL(iu||o,e).toString(),ru=[...b,...zo,...Vr],Nr,au=W.querySelector("SegmentBase"),Je=(Ke=W.querySelector("SegmentTemplate"))!=null?Ke:Ko;if(au){let Xe=(Dt=(ft=W.querySelector("SegmentBase Initialization"))==null?void 0:ft.getAttribute("range"))!=null?Dt:"",[Ze,Fr]=Xe.split("-").map(gt=>parseInt(gt,10)),Oe={from:Ze,to:Fr},Mt=(Ga=W.querySelector("SegmentBase"))==null?void 0:Ga.getAttribute("indexRange"),[Ur,_i]=Mt?Mt.split("-").map(gt=>parseInt(gt,10)):[],Ct=Mt?{from:Ur,to:_i}:void 0;Nr={type:"byteRange",url:ss,initRange:Oe,indexRange:Ct}}else if(Je){let Xe={representationId:(Wa=W.getAttribute("id"))!=null?Wa:void 0,bandwidth:(Qa=W.getAttribute("bandwidth"))!=null?Qa:void 0},Ze=parseInt((ja=Je.getAttribute("timescale"))!=null?ja:"",10),Fr=(Ya=Je.getAttribute("initialization"))!=null?Ya:"",Oe=Je.getAttribute("media"),Mt=(za=parseInt((qa=Je.getAttribute("startNumber"))!=null?qa:"",10))!=null?za:1,Ur=nt(Fr,Xe);if(!Oe)throw new ReferenceError("No media attribute in SegmentTemplate");let _i=(Ka=Je.querySelectorAll("SegmentTimeline S"))!=null?Ka:[],Ct=[],gt=0,Hr="",Gr=0;if(_i.length){let Fi=Mt,ge=0;for(let St of _i){let Te=parseInt((Ja=St.getAttribute("d"))!=null?Ja:"",10),et=parseInt((Xa=St.getAttribute("r"))!=null?Xa:"",10)||0,Ui=parseInt((Za=St.getAttribute("t"))!=null?Za:"",10);ge=Number.isFinite(Ui)?Ui:ge;let Wr=Te/Ze*1e3,Qr=ge/Ze*1e3;for(let Hi=0;Hi<et+1;Hi++){let nu=nt(Oe,{...Xe,segmentNumber:Fi.toString(10),segmentTime:(ge+Hi*Te).toString(10)}),ns=(Qr!=null?Qr:0)+Hi*Wr,ou=ns+Wr;Fi++,Ct.push({time:{from:ns,to:ou},url:nu})}ge+=(et+1)*Te,gt+=(et+1)*Wr}Gr=ge/Ze*1e3,Hr=nt(Oe,{...Xe,segmentNumber:Fi.toString(10),segmentTime:ge.toString(10)})}else if(hn(p)){let ge=parseInt((es=Je.getAttribute("duration"))!=null?es:"",10)/Ze*1e3,St=Math.ceil(p/ge),Te=0;for(let et=1;et<St;et++){let Ui=nt(Oe,{...Xe,segmentNumber:et.toString(10),segmentTime:Te.toString(10)});Ct.push({time:{from:Te,to:Te+ge},url:Ui}),Te+=ge}Gr=Te,Hr=nt(Oe,{...Xe,segmentNumber:St.toString(10),segmentTime:Te.toString(10)})}let su={time:{from:Gr,to:1/0},url:Hr};Nr={type:"template",baseUrl:ss,segmentTemplateUrl:Oe,initUrl:Ur,totalSegmentsDurationMs:gt,segments:Ct,nextSegmentBeyondManifest:su,timescale:Ze}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!bt||!Ve)continue;let _r={video:"video",audio:"audio",text:"text"}[bt];_r&&r[_r].push({id:tu,kind:_r,segmentReference:Nr,profiles:ru,duration:p,bitrate:rs,mime:Ve,codecs:Oi,width:Or,height:Ni,fps:Xo,quality:Jo})}}return{dynamic:d,liveAvailabilityStartTime:c,duration:p,container:k,representations:r}};import{videoSizeToQuality as Yd}from"@vkontakte/videoplayer-shared";var Sn=({id:n,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var o;let s=(o=a?He(a):void 0)!=null?o:Yd({width:e,height:t});return s&&{id:n,quality:s,bitrate:i,size:{width:e,height:t},fps:r}},vn=({id:n,bitrate:e})=>({id:n,bitrate:e}),yn=(n,e,t)=>{var r;let i=e.indexOf(t);return(r=n.at(Math.round(n.length*i/e.length)))!=null?r:n.at(-1)},Tn=({id:n,lang:e,label:t,url:i,isAuto:r})=>({id:n,url:i,isAuto:r,type:"internal",language:e,label:t}),er=n=>"url"in n,ot=n=>n.type==="template",hi=n=>n instanceof DOMException&&(n.name==="AbortError"||n.code===20);var fi=class{constructor(e,t,i,r,{fetcher:a,tuning:s,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:l}){this.currentSegmentLength$=new mi(0);this.onLastSegment$=new mi(!1);this.fullyBuffered$=new mi(!1);this.playingRepresentation$=new mi(void 0);this.playingRepresentationInit$=new mi(void 0);this.error$=new Kd;this.gaps=[];this.subscription=new Jd;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new AbortController;this.destroyAbortController=new AbortController;this.bufferLimit=1/0;this.failedDownloads=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=xt(this.destroyAbortController.signal,async function*(e){let t=this.representations.get(e);xe(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new an(this.sourceBuffer),this.subscription.add(va(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},s=>this.error$.next({id:"SegmentEjection",category:Pt.WTF,message:"Error when trying to clear segments ejected by browser",thrown:s}))),this.subscription.add(va(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Pt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(s=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,fa(this.sourceBuffer.buffered)*.8);if(this.bufferLimit=u,this.tuning.useNewPruneBufferStrategy){let d=$e(this.sourceBuffer.buffered,o),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBufferNew(o,s*2,d<l)}else this.pruneBufferOld(o,s)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(s=>this.error$.next(s))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),a=this.parsedInitData.get(t.id);xe(i,"No init buffer for starting representation"),xe(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(a))}.bind(this));this.switchTo=xt(this.destroyAbortController.signal,async function*(e){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);xe(t,`No such representation ${e}`);let i=this.segments.get(e),r=this.initData.get(e);if(ve(r)||ve(i)?yield this.loadInit(t,"high",!1):r instanceof Promise&&(yield r),i=this.segments.get(e),xe(i,"No segments for starting representation"),r=this.initData.get(e),!r||!(r instanceof ArrayBuffer)||!this.sourceBuffer)return;this.abort(),yield this.sourceBufferTaskQueue.append(r,this.downloadAbortController.signal);let a=this.getCurrentPosition();In(a)&&(this.isLive||(i.forEach(s=>s.status="none"),this.tuning.useNewPruneBufferStrategy&&(this.bufferLimit=1/0),this.pruneBuffer(a,1/0,!0)),this.maintain(a)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}.bind(this));this.seekLive=xt(this.destroyAbortController.signal,async function*(e){var o;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let u of this.representations.keys()){let d=e.find(p=>p.id===u);d&&this.representations.set(u,d);let l=this.representations.get(u);if(!l||!ot(l.segmentReference))return;let c=this.getActualLiveStartingSegments(l.segmentReference);this.segments.set(l.id,c)}let t=(o=this.switchingToRepresentationId)!=null?o:this.downloadingRepresentationId,i=this.representations.get(t);xe(i);let r=this.segments.get(t);xe(r,"No segments for starting representation");let a=this.initData.get(t);if(xe(a,"No init buffer for starting representation"),!(a instanceof ArrayBuffer))return;let s=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),s&&(yield this.sourceBufferTaskQueue.remove(s.from*1e3,s.to*1e3,this.destroyAbortController.signal)),this.searchGaps(r,i),yield this.sourceBufferTaskQueue.append(a,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this));switch(this.fetcher=a,this.tuning=s,this.compatibilityMode=d,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(l!=null&&l.dynamic),this.container=i,i){case"mp4":this.containerParser=sn;break;case"webm":this.containerParser=cn;break;default:qd(i)}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}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new AbortController,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var d,l;if(ve(e)||ve(this.downloadingRepresentationId)||ve(this.playingRepresentationId)||ve(this.sourceBuffer)||!ve(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(xe(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);this.currentSegmentLength$.next(((d=r==null?void 0:r.time.to)!=null?d:0)-((l=r==null?void 0:r.time.from)!=null?l:0));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=$e(this.sourceBuffer.buffered,e),m=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&p>=r.time.to-e+100&&(a=m)}if(isFinite(this.bufferLimit)&&fa(this.sourceBuffer.buffered)>=this.bufferLimit){let c=$e(this.sourceBuffer.buffered,e),p=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<p);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))c="high";else{let p=o.at(0);p&&p.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(o,t,c)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!o.length&&$e(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=i.at(-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;In(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],a=0,s=t.length-1;do r.unshift(t[s]),a+=t[s].time.to-t[s].time.from,s--;while(a<i&&s>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(let s of(t=e==null?void 0:e.representations[this.kind].values())!=null?t:[]){if(!s||!ot(s.segmentReference))return;let o=s.segmentReference.segments.map(c=>({...c,status:"none",size:void 0})),u=(i=this.segments.get(s.id))!=null?i:[],d=(a=(r=u.at(-1))==null?void 0:r.time.to)!=null?a:0,l=o==null?void 0:o.findIndex(c=>Math.floor(d)>=Math.floor(c.time.from)&&Math.floor(d)<=Math.floor(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;let c=this.getActualLiveStartingSegments(s.segmentReference);this.segments.set(s.id,c)}else{let c=o.slice(l+1);this.segments.set(s.id,[...u,...c])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;xe(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var t;for(let i of this.representations.values()){let r=i.segmentReference;if(!ot(r))return;let a=(t=this.segments.get(i.id))!=null?t:[],s=a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(s&&!isFinite(s.time.to)&&(s.time.to=e.time.to),!!!a.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*r.timescale/1e3).toString(10),d=nt(r.segmentTemplateUrl,{segmentTime:u});a.push({status:"none",time:{from:e.time.to,to:1/0},url:d})}}}findSegmentStartTime(e){var a,s,o;let t=(s=(a=this.switchingToRepresentationId)!=null?a:this.downloadingRepresentationId)!=null?s:this.playingRepresentationId;if(!t)return;let i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:c,time:{from:p,to:m}},h)=>{let f=p<=i&&m>=i,g=p>i||f||h===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),b=this.preloadOnly&&p<=i+v||m<=i+v;return(c==="none"||c==="partially_ejected"&&g&&b&&this.sourceBuffer&&!jt(this.sourceBuffer.buffered,i))&&g&&b});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+1);let a=e,s=0,o=0,u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(s<=d||o<=l);c++){let p=a[c];if(s+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}async loadSegments(e,t,i="auto"){t.segmentReference.type==="template"?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:a,url:s,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await xt(o,async function*(){let l=ya(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let l=await this.fetcher.fetch(s,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!l)return;let c=new DataView(l);if(!isFinite(r.segment.time.to)){let p=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,p)}u&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,o),r.segment.status="downloaded",this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){this.abortActiveSegments([e]),hi(l)||this.failedDownloads++}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:r,url:a,signal:s,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&s&&(await xt(s,async function*(){let u=ya(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(d,u),va(window,"online").pipe(zd()).subscribe(()=>{d(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})}.bind(this))(),s.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:s,priority:i}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),hi(u)||this.failedDownloads++}}prepareByteRangeFetchSegmentParams(e,t){if(ot(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:e.at(0).byte.from,to:e.at(-1).byte.to},{signal:a}=this.downloadAbortController;return{url:i,range:r,signal:a,onProgress:(o,u)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:a,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:Pt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ot(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:a}=this.downloadAbortController,s=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,l)=>{if(!a.aborted)try{let c=this.onSomeTemplateDataLoaded({dataView:d,loaded:l,signal:a,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});s.push(c)}catch(c){this.error$.next({id:"SegmentFeeding",category:Pt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:r,signal:a,onProgress:u,onProgressTasks:s}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let o of this.activeSegments){let{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){let d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=this.containerParser.parseFeedableSegmentChunk(d,this.isLive);l!=null&&l.byteLength&&(u.status="partially_fed",o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){let o={dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s};return this.tuning.useNewPartialSegmentFeeding?this.onSomeByteRangesDataLoadedNew(o):this.onSomeByteRangesDataLoadedOld(o)}onSomeByteRangesDataLoadedOld({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(!o)return;let u=o.segmentReference.type,d=e.byteLength;for(let l of this.activeSegments){let{segment:c}=l,p=u==="byteRange",m=p?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!p||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(a.aborted){s();continue}let f=p?c.byte.from-i:0,g=p?c.byte.to-i:e.byteLength,v=f<r,b=g<=r;if(c.status==="downloading"&&v&&b){c.status="downloaded";let k=new DataView(e.buffer,e.byteOffset+f,m);this.sourceBufferTaskQueue.append(k,a).then(S=>S&&!a.aborted?this.onSegmentFullyAppended(l,t):s())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(l.loadedBytes=Math.min(m,r-f),l.loadedBytes>l.feedingBytes)){let k=new DataView(e.buffer,e.byteOffset+f+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===m?k:this.containerParser.parseFeedableSegmentChunk(k);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,this.sourceBufferTaskQueue.append(S,a).then(y=>{if(a.aborted)s();else if(y)l.fedBytes+=S.byteLength,l.fedBytes===m&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<m)return;s()}}))}}}async onSomeByteRangesDataLoadedNew({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let u of this.activeSegments){let{segment:d}=u;if(u.representationId!==t)continue;if(a.aborted){s();continue}let l=d.byte.from-i,c=d.byte.to-i,p=c-l+1,m=l<r,h=c<=r;if(m){if(d.status==="downloading"&&h){d.status="downloaded";let f=new DataView(e.buffer,e.byteOffset+l,p);await this.sourceBufferTaskQueue.append(f,a)&&!a.aborted?this.onSegmentFullyAppended(u,t):s()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(d.status==="downloading"||d.status==="partially_fed")&&(u.loadedBytes=Math.min(p,r-l),u.loadedBytes>u.feedingBytes)){let f=new DataView(e.buffer,e.byteOffset+l+u.feedingBytes,u.loadedBytes-u.feedingBytes),g=u.loadedBytes===p?f:this.containerParser.parseFeedableSegmentChunk(f);g!=null&&g.byteLength&&(d.status="partially_fed",u.feedingBytes+=g.byteLength,await this.sourceBufferTaskQueue.append(g,a)&&!a.aborted?(u.fedBytes+=g.byteLength,u.fedBytes===p&&this.onSegmentFullyAppended(u,t)):s())}}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",er(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let a of(i=this.segments.get(r.id))!=null?i:[])a.status==="fed"&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){(this.tuning.useDashAbortPartiallyFedSegment?e.status==="partially_fed"||e.status==="partially_ejected":e.status==="partially_ejected")?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status="none"),e.status="partially_ejected"):e.status="none";for(let i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[r,a]of this.initData.entries()){let s=a instanceof Promise;t||(t=s),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=requestIdleCallback(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",s=(!i&&this.failedDownloads>0?xt(this.destroyAbortController.signal,async function*(){let o=ya(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{if(!o)return;let{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let p=l;this.isLive&&ot(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Pt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,s),s}async pruneBuffer(e,t,i=!1){return this.tuning.useNewPruneBufferStrategy?this.pruneBufferNew(e,t,i):this.pruneBufferOld(e,t,i)}async pruneBufferNew(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||ve(e)||this.sourceBuffer.updating)return!1;let r=[],a=0,s=u=>{u.sort((l,c)=>l.from-c.from);let d=[u[0]];for(let l=1;l<u.length;l++){let{from:c,to:p}=u[l],m=d[d.length-1];m.to>=c?m.to=Math.max(m.to,p):d.push(u[l])}return d},o=u=>{var l;if(a>=t)return r;r.push(u.time),r=s(r);let d=er(u)?(l=u.size)!=null?l:0:u.byte.to-u.byte.from;a+=d};for(let u of this.segments.values())for(let d of u){let l=d.time.to<=e-this.tuning.dash.bufferPruningSafeZone,c=d.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(l||c)&&d.status==="fed"&&o(d)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let d=this.sourceBuffer.buffered.start(u)*1e3,l=this.sourceBuffer.buffered.end(u)*1e3,c=0;for(let p of this.segments.values())for(let m of p)m.status==="none"&&Math.round(m.time.from)<=Math.round(d)&&Math.round(m.time.to)>=Math.round(l)&&c++;if(c===this.segments.size){let p={time:{from:d,to:l},url:"",status:"none"};o(p)}}if(r.length&&i){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let d of this.segments.values())for(let l of d)l.time.from>=e+u&&l.status==="fed"&&o(l)}return r.length?(await Promise.all(r.map(d=>this.sourceBufferTaskQueue.remove(d.from,d.to)))).reduce((d,l)=>d||l,!1):!1}async pruneBufferOld(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||ve(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,s=-1/0,o=!1,u=d=>{var c;a=Math.min(a,d.time.from),s=Math.max(s,d.time.to);let l=er(d)?(c=d.size)!=null?c:0:d.byte.to-d.byte.from;r+=l};for(let d of this.segments.values())for(let l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status==="fed"&&u(l)}if(o=isFinite(a)&&isFinite(s),!o){r=0,a=1/0,s=-1/0;for(let d of this.segments.values())for(let l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status==="fed"&&u(l)}}if(o=isFinite(a)&&isFinite(s),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){let l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(let p of this.segments.values())for(let m of p)if(m.status==="none"&&Math.round(m.time.from)<=Math.round(l)&&Math.round(m.time.to)>=Math.round(c)){a=l,s=c;break}}if(o=isFinite(a)&&isFinite(s),!o&&i){r=0,a=1/0,s=-1/0;let d=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+d&&c.status==="fed"&&u(c)}return o=isFinite(a)&&isFinite(s),o?this.sourceBufferTaskQueue.remove(a,s):!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)}}detectGaps(e,t){if(this.sourceBuffer)for(let i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){let s=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),s<i.time.to&&s>i.time.from&&(r.to=s)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=requestIdleCallback(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Pt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(ve(this.sourceBuffer)||ve(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}let t=1;for(let i of this.segments.values())for(let r of i){let{status:a}=r;if(a!=="fed"&&a!=="partially_ejected")continue;let s=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=s&&l.to+t>=o),d=e.filter(l=>s>=l.from-t&&s<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status="partially_ejected":this.gaps.some(l=>l.from===r.time.from||l.to===r.time.to)?r.status="partially_ejected":r.status="none")}}};var bi=n=>{let e=new URL(n);return e.searchParams.set("quic","1"),e.toString()};var En=n=>{var a;let e=n.get("X-Delivery-Type"),t=n.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(a={1:!0,0:!1}[t])!=null?a:void 0;return{type:i,reused:r}};import{abortable as gi,assertNever as xn,fromEvent as Pn,merge as Xd,now as Ta,Subscription as Zd,ValueSubject as Ia}from"@vkontakte/videoplayer-shared";var tr=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new Ia(void 0);this.lastConnectionReused$=new Ia(void 0);this.lastRequestFirstBytes$=new Ia(void 0);this.abortAllController=new AbortController;this.subscription=new Zd;this.fetchManifest=gi(this.abortAllController.signal,async function*(e){let t=e;this.requestQuic&&(t=bi(t));let i=yield fetch(t,{signal:this.abortAllController.signal}).catch(Si);return i?(this.onHeadersReceived(i.headers),i.text()):null}.bind(this));this.fetch=gi(this.abortAllController.signal,async function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:a="auto",signal:s,measureThroughput:o=!0,isLowLatency:u=!1}={}){var R,N;let d=e,l=new Headers;if(i)switch(t){case 0:{l.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let A=new URL(d,location.href);A.searchParams.append("bytes",`${i.from}-${i.to}`),d=A.toString();break}default:xn(t)}this.requestQuic&&(d=bi(d));let c=this.abortAllController.signal,p;if(s){let A=new AbortController;if(p=Xd(Pn(this.abortAllController.signal,"abort"),Pn(s,"abort")).subscribe(()=>{try{A.abort()}catch(w){Si(w)}}),this.abortAllController.signal.aborted||s.aborted)try{A.abort()}catch(w){Si(w)}c=A.signal}let m=Ta(),h=yield fetch(d,{priority:a,headers:l,signal:c}).catch(Si),f=Ta();if(!h)return p==null||p.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(f-m),!h.ok||!h.body)return p==null||p.unsubscribe(),Promise.reject(new Error(`Fetch error ${h.status}: ${h.statusText}`));if(this.onHeadersReceived(h.headers),!r&&!o)return p==null||p.unsubscribe(),h.arrayBuffer();let[g,v]=h.body.tee(),b=g.getReader();o&&((N=this.throughputEstimator)==null||N.trackStream(v,u));let k=0,S=new Uint8Array(0),y=!1,C=A=>{p==null||p.unsubscribe(),y=!0,Si(A)},$=gi(c,async function*({done:A,value:w}){if(k===0&&this.lastRequestFirstBytes$.next(Ta()-m),c.aborted){p==null||p.unsubscribe();return}if(!A&&w){let x=new Uint8Array(S.length+w.length);x.set(S),x.set(w,S.length),S=x,k+=w.byteLength,r==null||r(new DataView(S.buffer),k),yield b==null?void 0:b.read().then($,C)}}.bind(this));return yield b==null?void 0:b.read().then($,C),p==null||p.unsubscribe(),y?null:S.buffer}.bind(this));this.fetchByteRangeRepresentation=gi(this.abortAllController.signal,async function*(e,t,i){var v;if(e.type!=="byteRange")return null;let{from:r,to:a}=e.initRange,s=r,o=a,u=!1,d,l;e.indexRange&&(d=e.indexRange.from,l=e.indexRange.to,u=a+1===d,u&&(s=Math.min(d,r),o=Math.max(l,a))),s=Math.min(s,0);let c=yield this.fetch(e.url,{range:{from:s,to:o},priority:i,measureThroughput:!1});if(!c)return null;let p=new DataView(c,r-s,a-s+1);if(!t.validateData(p))throw new Error("Invalid media file");let m=t.parseInit(p),h=(v=e.indexRange)!=null?v:t.getIndexRange(m);if(!h)throw new ReferenceError("No way to load representation index");let f;if(u)f=new DataView(c,h.from-s,h.to-h.from+1);else{let b=yield this.fetch(e.url,{range:h,priority:i,measureThroughput:!1});if(!b)return null;f=new DataView(b)}let g=t.parseSegments(f,m,h);return{init:m,dataView:new DataView(c),segments:g}}.bind(this));this.fetchTemplateRepresentation=gi(this.abortAllController.signal,async function*(e,t){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(s=>({...s,status:"none",size:void 0})),dataView:new DataView(r)}:null}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){let{type:t,reused:i}=En(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,s;let{type:r}=e;switch(r){case"byteRange":return(a=await this.fetchByteRangeRepresentation(e,t,i))!=null?a:null;case"template":return(s=await this.fetchTemplateRepresentation(e,i))!=null?s:null;default:xn(r)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Si=n=>{if(!hi(n))throw n};var ut=(n,e,t)=>t*e+(1-t)*n,Ea=(n,e)=>n.reduce((t,i)=>t+i,0)/e,kn=(n,e,t,i)=>{let r=0,a=t,s=Ea(n,e),o=e<i?e:i;for(let u=0;u<o;u++)n[a]>s?r++:r--,a=(n.length+a-1)%n.length;return Math.abs(r)===o};import{isNullable as el,ValueSubject as An}from"@vkontakte/videoplayer-shared";var Qe=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new An(e.initial),this.debounced$=new An(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new K(`raw_${t}`),this.smoothedSeries$=new K(`smoothed_${t}`),this.reportedSeries$=new K(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,s=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<s)&&(el(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 ir=class extends Qe{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=ut(this.slow,t,this.params.emaAlphaSlow),this.fast=ut(this.fast,t,this.params.emaAlphaFast);let i=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=i(this.slow,this.fast)}};var rr=class extends Qe{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let i=Ea(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ut(this.emaSmoothed,t,this.params.emaAlpha);let r=kn(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:i}};var ar=class extends Qe{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?ut(this.smoothed,t,this.params.emaAlpha):t}};var dt=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new ir({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new rr({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ar({initial:e,label:"liveEdgeDelay",...t})}};var xa=(n,e)=>{n&&n.playbackRate!==e&&(n.playbackRate=e)};var Re=()=>window.ManagedMediaSource||window.MediaSource,sr=()=>{var n,e;return!!(window.ManagedMediaSource&&((e=(n=window.ManagedSourceBuffer)==null?void 0:n.prototype)!=null&&e.appendBuffer))},wn=()=>{var n,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(n=window.SourceBuffer)==null?void 0:n.prototype)!=null&&e.appendBuffer))},Ln=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Bn=["timeupdate","progress","play","seeked","stalled","waiting"];var ur=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Cn;this.representationSubscription=new Cn;this.state$=new L("none");this.currentVideoRepresentation$=new ae(void 0);this.currentVideoRepresentationInit$=new ae(void 0);this.currentVideoSegmentLength$=new ae(0);this.currentAudioSegmentLength$=new ae(0);this.error$=new Mn;this.lastConnectionType$=new ae(void 0);this.lastConnectionReused$=new ae(void 0);this.lastRequestFirstBytes$=new ae(void 0);this.isLive$=new ae(!1);this.liveDuration$=new ae(0);this.liveAvailabilityStartTime$=new ae(void 0);this.bufferLength$=new ae(0);this.liveLoadBufferLength$=new ae(0);this.livePositionFromPlayer$=new ae(0);this.timeInWaiting=0;this.isActiveLowLatency$=new ae(!1);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Mn;this.gapWatchdogActive=!1;this.destroyController=new AbortController;this.initManifest=Pa(this.destroyController.signal,async function*(e,t,i){var r;this.element=e,this.manifestUrlString=q(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:je.PARSER,message:"No playable video representations"})}.bind(this));this.updateManifest=Pa(this.destroyController.signal,async function*(){var r;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(a=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:je.NETWORK,message:"Failed to load manifest",thrown:a})});if(!e)return null;let t;try{t=gn(e!=null?e:"",this.manifestUrlString)}catch(a){this.error$.next({id:"ManifestParsing",category:je.PARSER,message:"Failed to parse MPD manifest",thrown:a})}if(!t)return null;let i=({kind:a,mime:s,codecs:o})=>{var u,d,l,c;return!!((d=(u=this.element)==null?void 0:u.canPlayType)!=null&&d.call(u,s)&&((c=(l=Re())==null?void 0:l.isTypeSupported)!=null&&c.call(l,`${s}; codecs="${o}"`))||a==="text")};return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((r=t.duration)!=null?r:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),{...t,representations:Object.fromEntries(Object.entries(t.representations).map(([a,s])=>[a,s.filter(i)]))}}.bind(this));this.initRepresentations=Pa(this.destroyController.signal,async function*(e,t,i){var m;lt(this.manifest),lt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=h=>{this.representationSubscription.add(kt(h,"error").pipe(or(f=>{var g;return!!((g=this.element)!=null&&g.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:je.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?Ln():new MediaSource;let a=document.createElement("source");if(r(a),a.src=URL.createObjectURL(this.source),this.element.appendChild(a),this.tuning.useManagedMediaSource&&sr())if(i){let h=document.createElement("source");r(h),h.type="application/x-mpegurl",h.src=i.url,this.element.appendChild(h)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive);let s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest};if(this.videoBufferManager=new fi("video",this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],Dn(t)&&(this.audioBufferManager=new fi("audio",this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),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(ka(1e3).subscribe(h=>{var f;if((f=this.element)!=null&&f.paused){let g=Kr(this.manifestUrlString,2);this.manifestUrlString=q(this.manifestUrlString,g+1e3,2)}})),this.representationSubscription.add(At(...Bn.filter(h=>h!=="waiting").map(h=>kt(this.element,h))).pipe(Aa(h=>this.element?$e(this.element.buffered,this.element.currentTime*1e3):0),Rn(),or(h=>!!h),rl(h=>{var f;(f=this.stallWatchdogSubscription)==null||f.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Rn()).subscribe(f=>xa(this.element,1))),this.representationSubscription.add(nr({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(or(({bufferLength:f,isActiveLowLatency:g})=>g&&!!f)).subscribe(({bufferLength:f})=>this.liveEstimatedDelay.next(f))),this.representationSubscription.add(nr({liveEstimatedDelay:this.liveEstimatedDelay.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveEstimatedDelay:f,isActiveLowLatency:g})=>{if(!g)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,b=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,k=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=f-v,y=1;Math.abs(S)>b&&(y=1+Math.sign(S)*k),xa(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var v,b;let g=0;if(f){let k=((b=(v=this.element)==null?void 0:v.currentTime)!=null?b:0)*1e3;g=Math.min(...this.bufferManagers.map(y=>{var C,$;return($=(C=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:C.to)!=null?$:k}))-k}this.liveLoadBufferLength$.getValue()!==g&&this.liveLoadBufferLength$.next(g)}));let h=0;this.representationSubscription.add(nr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(al(1e3)).subscribe(async({liveLoadBufferLength:f,bufferLength:g})=>{if(lt(this.element),this.isUpdatingLive)return;let v=this.element.playbackRate,b=Kr(this.manifestUrlString,2),k=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,S=Math.min(k,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),y=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,C=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,$=isFinite(f)?f:g,R=this.isActiveLowLatency$.getValue(),N=k<=this.tuning.live.activeLiveDelay&&b===0;this.isActiveLowLatency$.next(R&&N);let A="none";if(R?A="active_low_latency":this.tuning.dashCmafLive.lowLatency.isActive&&N?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(w=>w.proceedLowLatencyLive()),A="active_low_latency"):b!==0&&$<S?A="live_forward_buffering":$<S+C&&(A="live_with_target_offset"),isFinite(f)&&(h=f>h?f:h),A==="live_forward_buffering"||A==="live_with_target_offset"){let w=h-(S+y),x=this.normolizeLiveOffset(Math.trunc(b+w/v)),_=Math.abs(x-b),G;!f||_<=this.tuning.dashCmafLive.offsetCalculationError?G=b:x>0&&_>this.tuning.dashCmafLive.offsetCalculationError?G=x:G=0,this.manifestUrlString=q(this.manifestUrlString,G,2)}A!=="none"&&A!=="active_low_latency"&&(h=0,this.updateLive())}))}let o=At(...this.bufferManagers.map(h=>h.fullyBuffered$)).pipe(Aa(()=>this.bufferManagers.every(h=>h.fullyBuffered$.getValue()))),u=At(...this.bufferManagers.map(h=>h.onLastSegment$)).pipe(Aa(()=>this.bufferManagers.some(h=>h.onLastSegment$.getValue())));this.representationSubscription.add(At(this.forceEnded$,nr({allBuffersFull:o,someBufferEnded:u}).pipe(or(({allBuffersFull:h,someBufferEnded:f})=>h&&f))).subscribe(()=>{var h;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(h=this.source)==null||h.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:je.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(At(...this.bufferManagers.map(h=>h.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.subscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&this.subscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$)),this.source.readyState!=="open"&&(yield new Promise(h=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",h)}));let d=(m=this.manifest.duration)!=null?m:0,l=(h,f)=>{var g;return Math.max(h,(g=f.duration)!=null?g:0)},c=this.manifest.representations.audio.reduce(l,d),p=this.manifest.representations.video.reduce(l,d);(c||p)&&(this.source.duration=Math.max(c,p)/1e3),this.audioBufferManager&&Dn(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")}.bind(this));this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=ka(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),r=>{this.error$.next({id:"GapWatchdog",category:je.WTF,message:"Error handling gaps",thrown:r})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new tr({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=dt.getLiveEstimatedDelaySmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var i,r,a,s;lt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.tuning.dashCmafLive.lowLatency.isActive&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=q(this.manifestUrlString,t,2),this.manifest=await this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,await((r=this.videoBufferManager)==null?void 0:r.seekLive((i=this.manifest)==null?void 0:i.representations.video)),await((s=this.audioBufferManager)==null?void 0:s.seekLive((a=this.manifest)==null?void 0:a.representations.audio)))}initBuffer(){lt(this.element),this.state$.setState("running"),this.subscription.add(At(...Bn.map(e=>kt(this.element,e)),kt(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:je.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(kt(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(kt(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&jt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var i,r;if(this.element){if(this.timeInWaiting+=1e3,this.timeInWaiting>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${this.tuning.dash.crashOnStallTimeout} ms`);if(this.isLive$.getValue()&&this.timeInWaiting%5e3===0)this.seekLive(this.liveLastSeekOffset);else{let a=this.element.currentTime*1e3;(i=this.videoBufferManager)==null||i.maintain(a),(r=this.audioBufferManager)==null||r.maintain(a)}}};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=ka(1e3).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:je.FATAL,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}async switchRepresentation(e,t){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var r,a,s,o,u;lt(this.element),lt(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(s=(a=this.audioBufferManager)==null?void 0:a.findSegmentStartTime(e))!=null?s:e),jt(this.element.buffered,i)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3}stop(){var e,t,i;(e=this.element)==null||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)==null?void 0:e.representations}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let t=this.element.currentTime*1e3,i=[],r=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let a of this.bufferManagers)for(let s of a.gaps)a.playingRepresentation$.getValue()===s.representation&&s.from-r<=t&&s.to+r>t&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?i.push(1/0):i.push(s.to));if(i.length){let a=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,a===1/0?this.forceEnded$.next():this.element.currentTime=a/1e3}}};var dr=class{constructor(e,t){this.fov=e,this.orientation=t}};var lr=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,s=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:s},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Vn=`attribute vec2 a_vertex;
38
38
  attribute vec2 a_texel;
39
39
 
40
40
  varying vec2 v_texel;
@@ -45,7 +45,7 @@ void main(void) {
45
45
  // save texel vector to pass to fragment shader
46
46
  v_texel = a_texel;
47
47
  }
48
- `;var bS=`#ifdef GL_ES
48
+ `;var On=`#ifdef GL_ES
49
49
  precision highp float;
50
50
  precision highp int;
51
51
  #else
@@ -88,5 +88,5 @@ void main(void) {
88
88
  // sample using new coordinates
89
89
  gl_FragColor = texture2D(u_texture, tc);
90
90
  }
91
- `;var Ts=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 vs(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(mS,this.gl.VERTEX_SHADER),r=this.createShader(bS,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,l=t-a,u=e+r,c=t+a,d=e-r,p=t+a;return[s,n,o,l,u,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Wt=class{constructor(e){this.subscription=new Hk;this.videoState=new L("stopped");this.elementSize$=new jk(void 0);this.textTracksManager=new Ie;this.droppedFramesManager=new es;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Ka;this.textTracks=[];this.syncPlayback=()=>{var n,o,l;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==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let u=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(a.position-u,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==null?void 0:r.to)==="ready"&&I(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(l=this.liveOffset)==null||l.pause(),this.video.pause()):(r==null?void 0: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==null?void 0:r.to)==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return Dk(e)}}};this.init3DScene=e=>{var r,a,s;if(this.scene3D)return;this.scene3D=new Ts(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((a=e.projectionData)==null?void 0:a.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=se(e.container),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(J(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new gs({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=ue(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:ku.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,l)=>this.subscription.add(o.subscribe(l,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(SS(u=>!!u.length),vS()).subscribe(u=>{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:u})})),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(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(SS(_k),vS()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(qe(this.video,t.isLooped,a)),this.subscription.add(oe(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Te(this.video,t.playbackRate,r.playbackRateState$,a)),s(Uk(this.video),this.elementSize$),s(xe(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:u})=>{if(u==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(Ok(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let h of c.audio){p.push({id:h.id,language:h.language,label:h.label});let m=[];for(let b of h.representations){let S=eS(b);m.push(S),this.audioTracksMap.set(S,{stream:h,representation:b})}this.audioStreamsMap.set(h,m)}this.params.output.availableAudioStreams$.next(p)}let d=[];for(let p of c.video){d.push({id:p.id,language:p.language,hdr:p.hdr,label:p.label});let h=[];for(let m of p.representations){let b=Zb(m);b&&(h.push(b),this.videoTracksMap.set(b,{stream:p,representation:m}))}this.videoStreamsMap.set(p,h)}this.params.output.availableVideoStreams$.next(d);for(let p of c.text)for(let h of p.representations){let m=tS(p,h);this.textTracksMap.set(m,{stream:p,representation:h})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size>0&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else u==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=u=>e.error$.next({id:"RepresentationSwitch",category:ku.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(Is(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Vk(this.video,"progress")).subscribe(()=>{let u=this.player.state$.getState(),c=this.player.state$.getTransition();if(!["manifest_ready","running"].includes(u)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[p,h]=d,m=this.params.desiredState.autoVideoTrackLimits.getTransition();m&&this.params.output.autoVideoTrackLimits$.next(m.to),u==="manifest_ready"?this.player.initRepresentations(p.id,h==null?void 0:h.id,this.params.sourceHls):(this.player.switchRepresentation("video",p.id).catch(n),h&&this.player.switchRepresentation("audio",h.id).catch(n))},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ru()).subscribe(u=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:d}])=>d.id===u);if(c){let[d,{stream:p}]=c;e.currentVideoTrack$.next(d),e.currentVideoStream$.next(p)}else e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0)},a)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ru()).subscribe(u=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:d}])=>d.id===u);if(c){let[,{stream:d}]=c;e.currentAudioStream$.next(d)}else e.currentAudioStream$.next(void 0)},a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var c,d;if(u!=null&&u.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.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 o=t.playbackState.stateChangeStarted$.pipe(Fk(({to:u})=>u==="ready"),Ru());this.subscription.add(Is(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let u=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(Is(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Is(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,qk(["init"])).pipe(Bk(0));this.subscription.add(l.subscribe(this.syncPlayback,a))}selectVideoAudioRepresentations(){var O,k,F,R,M,w,q,Q,A,E,V,U,G;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),a=(O=e.videoTrack.getState())==null?void 0:O.id,n=[...this.videoTracksMap.keys()].find(({id:C})=>C===a),o=t.currentVideoTrack$.getValue(),l=((R=(F=e.videoStream.getState())!=null?F:n&&((k=this.videoTracksMap.get(n))==null?void 0:k.stream))!=null?R:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!l)return;let u=[...this.videoStreamsMap.keys()].find(({id:C})=>C===l.id),c=u&&this.videoStreamsMap.get(u);if(!c)return;let d=ht(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),m=(M=e.audioStream.getState())!=null?M:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=[...this.audioStreamsMap.keys()].find(({id:C})=>C===(m==null?void 0:m.id)),S=0;if(b){if(n&&!r){let C=ps(n,c,(w=this.audioStreamsMap.get(b))!=null?w:[]);S=Math.max(S,(q=C==null?void 0:C.bitrate)!=null?q:-1/0)}if(o){let C=ps(o,c,(Q=this.audioStreamsMap.get(b))!=null?Q:[]);S=Math.max(S,(A=C==null?void 0:C.bitrate)!=null?A:-1/0)}}let T=pt(c,{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:h,current:o,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),{backgroundVideoQualityLimit:v}=this.params.tuning.autoTrackSelection;!this.params.output.elementVisible$.getValue()&&r&&(T=(E=c.filter(C=>!Nk(C.quality)).sort((C,we)=>{var gt,rt;return((gt=we.bitrate)!=null?gt:0)-((rt=C.bitrate)!=null?rt:0)}).filter(C=>gS(C.quality,T.quality)&&gS(C.quality,v))[0])!=null?E:T);let P=r?T!=null?T:n:n!=null?n:T,g=b&&ps(P,c,(V=this.audioStreamsMap.get(b))!=null?V:[]),y=(U=this.videoTracksMap.get(P))==null?void 0:U.representation,$=g&&((G=this.audioTracksMap.get(g))==null?void 0:G.representation);if(y&&$)return[y,$];if(y&&!$&&this.audioTracksMap.size===0)return[y,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){le(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.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:ku.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ne(this.video)}};var Ui=class extends Wt{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 yS,interval as Gk,map as Yk}from"@vkontakte/videoplayer-shared";var Hi=class extends Wt{constructor(e){super(e),this.liveOffset=new We}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(yS({interval:Gk(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var s;if(this.videoState.getState()==="playing"&&!this.player.isActiveLowLatency){let n=e.position$.getValue()+(a-1);e.position$.next(n),(s=this.liveOffset)==null||s.resetTo(-n*1e3)}})).add(yS({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Yk(({liveBufferTime:a,liveAvailabilityStartTime:s})=>a&&s?a+s:void 0)).subscribe(e.liveTime$))}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(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,a)})}};var IS=_e(Wa(),1);import{assertNever as ji,assertNonNullable as TS,debounce as Wk,ErrorCategory as Es,filter as Qk,isNonNullable as zk,isNullable as Kk,map as $u,merge as Jk,Observable as Xk,observableFrom as Zk,Subscription as eR,videoSizeToQuality as tR}from"@vkontakte/videoplayer-shared";var Oe={};var kr=(i,e)=>new Xk(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Gi=class{constructor(e){this.subscription=new eR;this.videoState=new L("initializing");this.textTracksManager=new Ie;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==null?void 0: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:ji(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ji(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ji(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:ji(e)}break;default:ji(t)}};this.video=se(e.container),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(J(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ne(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Es.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,IS.default)(import("hls.js").then(a=>{e||(Oe.Hls=a.default,Oe.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){TS(Oe.Hls,"hls.js not loaded"),this.hls=new Oe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){TS(Oe.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:Es.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=ue(this.video),s=(u,c)=>this.subscription.add(u.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.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(qe(this.video,e.isLooped,r)),this.subscription.add(oe(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Te(this.video,e.playbackRate,a.playbackRateState$,r)),s(xe(this.video),t.elementVisible$),this.subscription.add(kr(this.hls,Oe.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:Es.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)==null?void 0:c.message} ${u.reason}`,thrown:u.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(()=>{var u;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(kr(this.hls,Oe.Events.MANIFEST_PARSED).pipe($u(({levels:u})=>u.reduce((c,d)=>{var v,P;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(P=ct((v=d.attrs.QUALITY)!=null?v:""))!=null?P:tR({width:h,height:m});if(!b)return c;let S=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,T={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:S};return this.trackLevels.set(p,{track:T,level:d}),c.push(T),c},[]))),t.availableVideoTracks$),s(kr(this.hls,Oe.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){let c=[];for(let d of u.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang,b="internal";c.push({id:p,url:h,language:m,type:b})}e.internalTextTracks.startTransitionTo(c)}}),s(kr(this.hls,Oe.Events.LEVEL_LOADING).pipe($u(({url:u})=>J(u))),t.hostname$),s(kr(this.hls,Oe.Events.FRAG_CHANGED),u=>{var p,h,m,b;let{video:c,audio:d}=u.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(ot(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));let n=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===u))==null?void 0:c.track},o=kr(this.hls,Oe.Events.LEVEL_SWITCHED).pipe($u(({level:u})=>n(this.hls.levels[u])));o.pipe(Qk(zk)).subscribe(t.currentVideoTrack$,r),this.subscription.add(ot(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),u=>{var m;if(Kk(u))return;let c=(m=this.trackLevels.get(u.id))==null?void 0:m.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 l=Jk(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Zk(["init"])).pipe(Wk(0));this.subscription.add(l.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 le(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Es.DOM,thrown:t}))||(this.videoState.setState("paused"),I(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("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 ES="X-Playback-Duration",Lu=async i=>{var a;let e=await ze(i),t=await e.text(),r=(a=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:a[1];return r?parseInt(r,10):e.headers.has(ES)?parseInt(e.headers.get(ES),10):void 0};import{assertNever as oR,combine as uR,debounce as lR,ErrorCategory as Ps,filter as cR,filterChanged as dR,isNonNullable as PS,isNullable as As,map as AS,merge as pR,observableFrom as hR,Subscription as fR,ValueSubject as Du,VideoQuality as mR}from"@vkontakte/videoplayer-shared";var Mu=_e(eo(),1);import{videoSizeToQuality as rR,getExponentialDelay as iR}from"@vkontakte/videoplayer-shared";var aR=i=>{let e=null;if(i.QUALITY&&(e=ct(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=rR({width:t,height:r})}return e!=null?e:null},sR=(i,e)=>{var s,n;let t=i.split(`
92
- `),r=[],a=[];for(let o=0;o<t.length;o++){let l=t[o],u=l.match(/^#EXT-X-STREAM-INF:(.+)/),c=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!c)){if(u){let d=(0,Mu.default)(u[1].split(",").map(v=>v.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=aR(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,S;if(d.RESOLUTION){let[v,P]=d.RESOLUTION.split("x").map(g=>parseInt(g,10));v&&P&&(S={width:v,height:P})}let T=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:T,bandwidth:m,size:S,fps:b})}if(c){let d=(0,Mu.default)(c[1].split(",").map(b=>b.split("=")).map(([b,S])=>[b,S.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&a.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},nR=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Cu=0,xS=async(i,e=i,t)=>{let a=await(await ze(i)).text();Cu+=1;try{let{qualityManifests:s,textTracks:n}=sR(a,e);return{qualityManifests:s,textTracks:n}}catch(s){if(Cu<=t.manifestRetryMaxCount)return await nR(iR(Cu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),xS(i,e,t)}return{qualityManifests:[],textTracks:[]}},xs=xS;var Yi=class{constructor(e){this.subscription=new fR;this.videoState=new L("stopped");this.textTracksManager=new Ie;this.manifests$=new Du([]);this.liveOffset=new We;this.manifestStartTime$=new Du(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 u=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),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((a==null?void 0:a.to)!=="paused"&&u.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(u.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.pause()):(a==null?void 0: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==null?void 0:a.to)==="paused"&&(I(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return oR(t)}};var t;this.params=e,this.video=se(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:mR.INVARIANT,url:this.params.source.url},xs(ee(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:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Ps.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ps.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(J(this.params.source.url)),this.maxSeekBackTime$=new Du((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var l,u,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(l=a==null?void 0:a.to)==null?void 0:l.id)!=null?c:(u=t.getState())==null?void 0:u.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Ps.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=ue(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,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.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(oe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Te(this.video,t.playbackRate,a.playbackRateState$,r)),s(xe(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(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(dR(),AS(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&PS(u.to)){let d=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(J(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{var l,u,c;let o=(c=(u=(l=this.video)==null?void 0:l.getStartDate)==null?void 0:u.call(l))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(uR({startTime:this.manifestStartTime$.pipe(cR(PS)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),r)),this.subscription.add(this.manifests$.pipe(AS(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:p})=>({id:l,quality:u,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=pR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,hR(["init"])).pipe(lR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ne(this.video)}prepare(){var o,l;let e=this.selectManifest();if(As(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:u,min:c}=(l=(o=t==null?void 0:t.to)!=null?o:r)!=null?l:{};for(let[d,p]of[[u,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&a.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ee(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Lu(n).then(u=>{var c;if(!As(u))this.maxSeekBackTime$.next(u);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(As(d)||!isFinite(d))try{ze(n).then(p=>p.text()).then(p=>{var m;let h=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:m[1];if(h){let b=new URL(h,n).toString();Lu(b).then(S=>{As(S)||this.maxSeekBackTime$.next(S)})}})}catch(p){}}})}playIfAllowed(){le(this.video).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:Ps.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 bR,debounce as SR,ErrorCategory as Ou,fromEvent as Bu,isNonNullable as gR,isNullable as vR,map as yR,merge as wS,observableFrom as kS,Subscription as TR,ValueSubject as IR,VideoQuality as ER,isIOS as xR}from"@vkontakte/videoplayer-shared";var Wi=class{constructor(e){this.subscription=new TR;this.videoState=new L("stopped");this.textTracksManager=new Ie;this.manifests$=new IR([]);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 u=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),u.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!=="paused"&&u.state==="requested"&&this.seek(u.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.pause()):(a==null?void 0:a.to)==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(a==null?void 0:a.to)==="paused"&&I(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return bR(t)}};this.params=e,this.video=se(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ER.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(J(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),xs(ee(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:Ou.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var l,u,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(l=a==null?void 0:a.to)==null?void 0:l.id)!=null?c:(u=t.getState())==null?void 0:u.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!a&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Ou.WTF,message:"HlsProvider internal logic error",thrown:o})},a=ue(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l));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.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(qe(this.video,t.isLooped,r)),this.subscription.add(oe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Te(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(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(a.loadedMetadata$.subscribe(()=>{var d;let o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&gR(u.to)){let p=u.to.id;this.params.desiredState.videoTrack.setState(u.to);let h=this.manifests$.getValue().find(m=>m.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(J(h.url));let m=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(m!==b){let S=this.params.output.element$.getValue();S&&(this.params.desiredState.playbackRate.setState(m),S.playbackRate=m)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),l&&l.from==="changing_manifest"&&this.videoState.setState(l.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(yR(o=>o.map(({id:l,quality:u,size:c,bandwidth:d,fps:p})=>({id:l,quality:u,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!xR()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(wS(Bu(o,"addtrack"),Bu(o,"removetrack"),Bu(o,"change"),kS(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},r))}let n=wS(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,kS(["init"])).pipe(SR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ne(this.video)}prepare(){var s,n;let e=this.selectManifest();if(vR(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:l}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[u,c]of[[o,"mq"],[l,"lq"]]){let d=String(parseFloat(u||""));c&&u&&a.searchParams.set(c,d)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){le(this.video).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:Ou.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as PR,assertNonNullable as RS,debounce as AR,ErrorCategory as $S,isHigher as wR,isHigherOrEqual as kR,isInvariantQuality as LS,isLowerOrEqual as RR,isNonNullable as $R,merge as LR,observableFrom as CR,Subscription as MR}from"@vkontakte/videoplayer-shared";var Qi=class{constructor(e){this.subscription=new MR;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new Ie;this.syncPlayback=()=>{var l,u,c;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:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((l=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:l.max)!==((c=(u=this.trackUrls[n.to.id])==null?void 0:u.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0: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.pause()):(r==null?void 0:r.to)==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return PR(e)}};this.params=e,this.video=se(e.container),this.params.output.element$.next(this.video),Object.entries(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(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:$S.WTF,message:"MpegProvider internal logic error",thrown:o})},a=ue(this.video),s=(o,l)=>this.subscription.add(o.subscribe(l,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.playing$,e.firstFrameEvent$),s(a.canplay$,e.canplay$),s(a.seeked$,e.seekedEvent$),s(a.inPiP$,e.inPiP$),s(a.inFullscreen$,e.inFullscreen$),this.subscription.add(qe(this.video,t.isLooped,r)),this.subscription.add(oe(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Te(this.video,t.playbackRate,a.playbackRateState$,r)),s(xe(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(()=>{var l,u;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&$R(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(u=this.params.output.element$.getValue())==null?void 0:u.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=LR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,CR(["init"])).pipe(AR(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),ne(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;RS(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];RS(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ni(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(J(t))}playIfAllowed(){le(this.video).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:$S.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var a,s,n,o;let t,r=e;if(e&&((a=this.params.output.currentVideoTrack$.getValue())==null?void 0:a.quality)!==e){let l=(s=Object.values(this.trackUrls).find(d=>!LS(d.track.quality)&&RR(d.track.quality,e)))==null?void 0:s.track,u=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[u!=null?u:"0"])==null?void 0:o.track;if(l&&c&&kR(c.quality,l.quality)&&(t=l),!t){let d=Object.values(this.trackUrls).filter(h=>!LS(h.track.quality)&&wR(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let l=Object.values(this.trackUrls).map(u=>u.track);t=pt(l,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput: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 MS,debounce as VR,merge as DS,observableFrom as _R,Subscription as NR,map as OS,ValueSubject as FR,ErrorCategory as _u,VideoQuality as qR}from"@vkontakte/videoplayer-shared";import{ErrorCategory as DR}from"@vkontakte/videoplayer-shared";var CS=["stun:videostun.mycdn.me:80"],OR=1e3,BR=3,Vu=()=>null,ws=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=Vu;this.externalStopCallback=Vu;this.externalErrorCallback=Vu;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:CS}]};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:DR.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(t){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),OR)}normalizeOptions(e={}){let t={stunServerList:CS,maxRetryNumber:BR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var zi=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new FR(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.pause()):(r==null?void 0:r.to)==="playing"&&I(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&I(this.params.desiredState.playbackState,"paused");return;default:return MS(e)}};this.subscription=new NR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=se(e.container),this.liveStreamClient=new ws(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.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ne(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:_u.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};DS(this.videoState.stateChangeStarted$.pipe(OS(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(OS(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=ue(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(xe(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(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.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(oe(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 MS(n.to)}},r)).add(DS(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,_R(["init"])).pipe(VR(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(J(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:qR.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:_u.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){le(this.video).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:_u.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ki=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 Ji,assertNonNullable as bt,ErrorCategory as ks,filter as GR,isNonNullable as _S,isNullable as YR,map as WR,merge as QR,once as zR,Subject as Be,Subscription as NS,ValueSubject as D}from"@vkontakte/videoplayer-shared";import{Observable as UR,map as BS,Subscription as HR,Subject as jR}from"@vkontakte/videoplayer-shared";var VS=i=>new UR(e=>{let t=new HR,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(BS(({from:u,to:c})=>`${u}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(BS(({type:u})=>u!==void 0)),n=new jR,o=0,l="unknown";return t.add(r.subscribe(u=>{o&&window.clearTimeout(o),l=u,o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(s.subscribe(u=>{o&&(window.clearTimeout(o),o=0,u&&(o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var KR={chunkDuration:5e3,maxParallelRequests:5},Xi=class{constructor(e){this.current$=new D({type:void 0});this.providerError$=new Be;this.noAvailableProvidersError$=new Be;this.providerOutput={position$:new D(0),duration$:new D(1/0),volume$:new D({muted:!1,volume:1}),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableVideoTracks$:new D([]),currentVideoTrack$:new D(void 0),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0),isAudioAvailable$:new D(!0),autoVideoTrackLimitingAvailable$:new D(!1),autoVideoTrackLimits$:new D(void 0),currentBuffer$:new D(void 0),isBuffering$:new D(!0),error$:new Be,warning$:new Be,willSeekEvent$:new Be,seekedEvent$:new Be,loopedEvent$:new Be,endedEvent$:new Be,firstBytesEvent$:new Be,firstFrameEvent$:new Be,canplay$:new Be,isLive$:new D(void 0),isLowLatency$:new D(!1),canChangePlaybackSpeed$:new D(!0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),inPiP$:new D(!1),inFullscreen$:new D(!1),element$:new D(void 0),elementVisible$:new D(!0),availableSources$:new D(void 0),is3DVideo$:new D(!1)};this.subscription=new NS;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=ab([...nb(this.params.tuning),...sb(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>_S(e.sources[o])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(o=>!a.includes(o)),...t.filter(o=>a.includes(o))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new Ki(s);let n=[...su(!0),...su(!1)];this.chromecastFormatsIterator=new Ki(n.filter(o=>_S(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}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()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(YR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:ks.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.destroyProvider(),this.initProvider()}switchToNextProvider(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"});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}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ji(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]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return bt(o),new Ui({...n,source:o,sourceHls:l})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return bt(o),new Hi({...n,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return bt(o),vr||!this.params.tuning.useHlsJs?new Wi({...n,source:o}):new Gi({...n,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return bt(o),new Yi({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return bt(o),new Qi({...n,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return bt(o),new Nm({...n,source:o,config:{...KR,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return bt(o),new zi({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 Ji(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:a,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return bt(o),new Zr({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 Ji(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ji(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 Ji(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,FS.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new NS,t=!1,r=0;return e.add(QR(this.providerOutput.error$,VS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(WR(a=>({id:`ProviderHangup:${a}`,category:ks.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(GR(({to:s})=>s==="playing"),zR()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{let s=this.current$.getValue().destination;if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let n=a.category===ks.NETWORK,o=a.category===ks.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=r<this.params.tuning.providerErrorLimit&&!o;l&&!o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};import{fromEvent as Rs,once as JR,combine as XR,Subscription as qS,ValueSubject as Nu,map as ZR,filter as e$,isNonNullable as $s,now as ge,safeStorage as Fu}from"@vkontakte/videoplayer-shared";var t$=5e3,US="one_video_throughput",HS="one_video_rtt",et=window.navigator.connection,jS=()=>{let i=et==null?void 0:et.downlink;if($s(i)&&i!==10)return i*1e3},GS=()=>{let i=et==null?void 0:et.rtt;if($s(i)&&i!==3e3)return i},YS=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},qu=class i{constructor(e){this.subscription=new qS;this.concurrentDownloads=new Set;var a,s;this.tuningConfig=e;let t=i.load(US)||(e.useBrowserEstimation?jS():void 0)||t$,r=(s=(a=i.load(HS))!=null?a:e.useBrowserEstimation?GS():void 0)!=null?s:0;if(this.throughput$=new Nu(t),this.rtt$=new Nu(r),this.rttAdjustedThroughput$=new Nu(YS(t,r,e.rttPenaltyRequestSize)),this.throughput=jt.getSmoothedValue(t,-1,e),this.rtt=jt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let l=jS();l&&this.throughput.next(l);let u=GS();$s(u)&&this.rtt.next(u)};et&&"onchange"in et&&this.subscription.add(Rs(et,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Fu.set(US,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Fu.set(HS,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(XR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(ZR(({throughput:n,rtt:o})=>YS(n,o,e.rttPenaltyRequestSize)),e$(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=ge(),a=new qS;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(Rs(e,"progress").pipe(JR()).subscribe(s=>{t=s.loaded,r=ge()}));break;case 1:case 0:a.add(Rs(e,"loadstart").subscribe(()=>{t=0,r=ge()}));break}a.add(Rs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ge(),l=n-t,u=o-r;this.addRawSpeed(l,u,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=ge(),n=0,o=ge(),l=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=async({done:c,value:d})=>{if(c)!t&&this.addRawSpeed(a,ge()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if(ge()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let h=o-s;h&&this.addRawSpeed(n,h,1,t),n=d.byteLength,s=ge()}o=ge()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ge()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ge()-o,this.concurrentDownloads.size),n=0,o=ge());await(r==null?void 0:r.read().then(u,l))}};this.concurrentDownloads.add(e),r==null||r.read().then(u,l)}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){var r;let t=Fu.get(e);if($s(t))return(r=parseInt(t,10))!=null?r:void 0}},WS=qu;import{fillWithDefault as r$,VideoQuality as QS}from"@vkontakte/videoplayer-shared";var zS={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:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:QS.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:QS.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:3e4,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:200,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!0,preferHDR:!0,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,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},KS=i=>{var e;return{...r$(i,zS),configName:[...(e=i.configName)!=null?e:[],...zS.configName]}};import{assertNonNullable as Ls,combine as Cs,ErrorCategory as Ms,filter as Zi,filterChanged as Ae,fromEvent as Hu,isNonNullable as l$,isNullable as c$,Logger as d$,map as B,mapTo as eg,merge as St,now as Ds,once as tt,Subject as H,Subscription as tg,tap as rg,ValueSubject as x,isHigher as p$,isInvariantQuality as ig}from"@vkontakte/videoplayer-shared";import{merge as i$,map as a$,filter as JS,isNonNullable as s$}from"@vkontakte/videoplayer-shared";var Uu=({seekState:i,position$:e})=>i$(i.stateChangeEnded$.pipe(a$(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),JS(s$)),e.pipe(JS(()=>i.getState().state==="none")));import{assertNonNullable as n$}from"@vkontakte/videoplayer-shared";var XS=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return n$(e,`Wrong container or containerId {${i.container}}`),e};import{filter as o$,once as u$}from"@vkontakte/videoplayer-shared";var ZS=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(o$(a=>a.length>0),u$()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};var Os=class{constructor(e={configName:[]}){this.subscription=new tg;this.logger=new d$;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new x(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),videoStream:new L(void 0),audioStream:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new x("stopped"),position$:new x(0),duration$:new x(1/0),muted$:new x(!1),volume$:new x(1),availableVideoStreams$:new x([]),currentVideoStream$:new x(void 0),availableQualities$:new x([]),availableQualitiesFps$:new x({}),currentQuality$:new x(void 0),isAutoQualityEnabled$:new x(!0),autoQualityLimitingAvailable$:new x(!1),autoQualityLimits$:new x({}),availableAudioStreams$:new x([]),currentAudioStream$:new x(void 0),availableAudioTracks$:new x([]),isAudioAvailable$:new x(!0),currentPlaybackRate$:new x(1),currentBuffer$:new x({start:0,end:0}),isBuffering$:new x(!0),isStalled$:new x(!1),isEnded$:new x(!1),isLooped$:new x(!1),isLive$:new x(void 0),canChangePlaybackSpeed$:new x(void 0),atLiveEdge$:new x(void 0),atLiveDurationEdge$:new x(void 0),liveTime$:new x(void 0),liveBufferTime$:new x(void 0),currentFormat$:new x(void 0),availableTextTracks$:new x([]),currentTextTrack$:new x(void 0),throughputEstimation$:new x(void 0),rttEstimation$:new x(void 0),videoBitrate$:new x(void 0),hostname$:new x(void 0),httpConnectionType$:new x(void 0),httpConnectionReused$:new x(void 0),surface$:new x("none"),chromecastState$:new x("NOT_AVAILABLE"),chromecastDeviceName$:new x(void 0),intrinsicVideoSize$:new x(void 0),availableSources$:new x(void 0),is3DVideo$:new x(!1),currentVideoSegmentLength$:new x(0),currentAudioSegmentLength$:new x(0)};this.events={inited$:new H,ready$:new H,started$:new H,playing$:new H,paused$:new H,stopped$:new H,willStart$:new H,willResume$:new H,willPause$:new H,willStop$:new H,willDestruct$:new H,watchCoverageRecord$:new H,watchCoverageLive$:new H,managedError$:new H,fatalError$:new H,ended$:new H,looped$:new H,seeked$:new H,willSeek$:new H,firstBytes$:new H,firstFrame$:new H,canplay$:new H,log$:new H};this.experimental={element$:new x(void 0),tuningConfigName$:new x([]),enableDebugTelemetry$:new x(!1),dumpTelemetry:Pm};if(this.initLogs(),this.tuning=KS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new oa({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new WS(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,a)=>{let s=Reflect.get(t,r,a);return typeof s!="function"?s:(...n)=>{try{return s.apply(t,n)}catch(o){let l=n.map(d=>JSON.stringify(d,(p,h)=>{let m=typeof h;return["number","string","boolean"].includes(m)?h:h===null?null:`<${m}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${l.join(", ")})`;throw this.events.fatalError$.next({id:u,category:Ms.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,a;return this.config=e,this.domContainer=XS(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Xi({sources:e.sources,meta:(r=e.meta)!=null?r:{},failoverHosts:(a=e.failoverHosts)!=null?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!li()?Hu(document,"visibilitychange").pipe(tt()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=r&&!a&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return 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.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){Ls(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Zi(r=>r.length>0),tt()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Ls(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return ZS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(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(c$(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return l$(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.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(St(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(B(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(B(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Zi(({from:e})=>e==="stopped"),tt()).subscribe(()=>{this.initedAt=Ds(),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();n.state==="requested"?this.desiredState.seekState.setState({...n,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ms.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(B(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(B(n=>n.destination),Ae()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(e.providerOutput.availableVideoTracks$.pipe(B(n=>n.map(({quality:o})=>o).sort((o,l)=>ig(o)?1:ig(l)?-1:p$(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let l of n)l.fps&&(o[l.quality]=l.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$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Ae()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Ae()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Ae()).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!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(B(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(Cs({hasLiveOffsetByPaused:St(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(B(n=>n.to),Ae(),B(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(Cs({atLiveEdge:Cs({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Uu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(B(({isLive:n,position:o,isLowLatency:l})=>{let u=this.getActiveLiveDelay(l);return n&&Math.abs(o)<u/1e3}),Ae(),rg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(B(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Cs({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(B(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Ae(),rg(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(B(n=>n.muted),Ae()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(B(n=>n.volume),Ae()).subscribe(this.info.volume$)).add(Uu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(St(e.providerOutput.endedEvent$.pipe(eg(!0)),e.providerOutput.seekedEvent$.pipe(eg(!1))).pipe(Ae()).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.noAvailableProvidersError$.pipe(B(n=>({id:n?`No${n}`:"NoProviders",category:Ms.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(tt(),B(n=>n!=null?n:Ds()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(tt(),B(()=>Ds()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(tt(),B(()=>Ds()-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(Zi(({to:n})=>n==="playing"),tt()).subscribe(()=>r.next(!1)));let a=0,s=St(e.providerOutput.isBuffering$,t,r).pipe(B(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),Ae());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(St(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var l,u;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=n==null?void 0:n.size)==null?void 0:l.width,height:(u=n==null?void 0:n.size)==null?void 0:u.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(St(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(),l=e.providerOutput.element$.getValue(),u=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":l?u?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(B(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new tg;this.subscription.add(t),this.subscription.add(e.current$.pipe(Ae((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Zi(r=>r.length>0),tt()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var a;let t,r=(a=this.desiredState.videoTrack.getState())==null?void 0:a.quality;r&&(t=e.find(({quality:s})=>s===r),t||this.setAutoQuality(!0)),t||(t=pt(e,{container:this.domContainer.getBoundingClientRect(),throughput: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(St(this.desiredState.videoTrack.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(B(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(B(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(B(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(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Ls(this.providerContainer),Ls(e),xm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Em(r)),this.providerContainer.current$.subscribe(({type:r})=>ai("provider",r)),e.duration$.subscribe(r=>ai("duration",r)),e.availableVideoTracks$.pipe(Zi(r=>!!r.length),tt()).subscribe(r=>ai("tracks",r)),this.events.fatalError$.subscribe(new te("fatalError")),this.events.managedError$.subscribe(new te("managedError")),e.position$.subscribe(new te("position")),e.currentVideoTrack$.pipe(B(r=>r==null?void 0:r.quality)).subscribe(new te("quality")),this.info.currentBuffer$.subscribe(new te("buffer")),e.isBuffering$.subscribe(new te("isBuffering"))].forEach(r=>this.subscription.add(r)),ai("codecs",ib())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||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:Ms.DOM,message:String(a)})})};this.subscription.add(St(Hu(document,"visibilitychange"),Hu(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let a=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);a&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(a=>a.quality===t);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 Rj,Observable as $j,Subject as Lj,ValueSubject as Cj,VideoQuality as Mj}from"@vkontakte/videoplayer-shared";var Dj=`@vkontakte/videoplayer-core@${hl}`;export{sa as ChromecastState,zs as HttpConnectionType,$j as Observable,me as PlaybackState,Os as Player,Dj as SDK_VERSION,Lj as Subject,Rj as Subscription,Ks as Surface,hl as VERSION,Cj as ValueSubject,Pt as VideoFormat,Mj as VideoQuality};
91
+ `;var cr=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new dr(this.params.fov,this.params.orientation),this.cameraRotationManager=new lr(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Vn,this.gl.VERTEX_SHADER),i=this.createShader(On,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,s=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,p=t+r;return[a,s,o,u,d,l,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}};var ct=class{constructor(e){this.subscription=new gl;this.videoState=new L("stopped");this.elementSize$=new Hn(void 0);this.textTracksManager=new le;this.droppedFramesManager=new Xi;this.videoTracks$=new Hn([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new qi;this.textTracks=[];this.syncPlayback=()=>{var s,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let d=(o=(s=this.liveOffset)==null?void 0:s.getTotalPausedTime())!=null?o:0;this.seek(r.position-d,r.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"),T(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&T(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.pause()):(i==null?void 0:i.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return dl(e)}}};this.init3DScene=e=>{var i,r,a;if(this.scene3D)return;this.scene3D=new cr(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((a=e.projectionData)==null?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSize$.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=Z(e.container,e.tuning.audioVideoSyncRate),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(j(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new ur({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,i=ie(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:wa.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(pr(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(cl(hl),bl()),e.firstBytesEvent$),a(this.videoState.stateChangeEnded$.pipe(pr(d=>d.to)),this.params.output.playbackState$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ie(this.video,t.isLooped,r)),this.subscription.add(te(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(de(this.video,t.playbackRate,i.playbackRateState$,r)),a(fl(this.video),this.elementSize$),a(pe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d==="manifest_ready"){let c=[];this.audioTracks=[],this.textTracks=[];let p=this.player.getRepresentations();Nn(p,"Manifest not loaded or empty");let m=Array.from(p.audio).sort((v,b)=>b.bitrate-v.bitrate),h=Array.from(p.video).sort((v,b)=>b.bitrate-v.bitrate),f=Array.from(p.text);if(!this.params.tuning.isAudioDisabled)for(let v of m){let b=vn(v);b&&this.audioTracks.push({track:b,representation:v})}for(let v of h){let b=Sn(v);if(b){c.push({track:b,representation:v});let k=!this.params.tuning.isAudioDisabled&&yn(m,h,v);k&&this.audioRepresentations.set(v.id,k)}}this.videoTracks$.next(c);for(let v of f){let b=Tn(v);b&&this.textTracks.push({track:b,representation:v})}this.params.output.availableVideoTracks$.next(c.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));let g=this.selectVideoRepresentation();Nn(g),this.player.initRepresentations(g.id,(l=this.audioRepresentations.get(g.id))==null?void 0:l.id,this.params.sourceHls)}else d==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r));let s=d=>e.error$.next({id:"RepresentationSwitch",category:wa.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(hr(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,pl(this.video,"progress")).subscribe(()=>{let d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!=="running"||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let c=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);let m=this.params.desiredState.autoVideoTrackSwitching.getState(),h=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let f=c.id;!this.params.output.elementVisible$.getValue()&&m&&(f=this.videoTracks$.getValue().map(v=>v.representation).sort((v,b)=>b.bitrate-v.bitrate).filter(v=>{let b=Un(v),k=Un(c);if(b&&k)return Fn(b,k)&&Fn(b,h)}).map(v=>v.id)[0]),this.player.switchRepresentation("video",f).catch(s);let g=this.audioRepresentations.get(c.id);g&&this.player.switchRepresentation("audio",g.id).catch(s)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(_n(),pr(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))==null?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&((l=this.params.tuning.spherical)!=null&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(c=this.params.tuning.spherical)!=null&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(pr(({to:d})=>d==="ready"),_n());this.subscription.add(hr(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(hr(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=hr(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ml(["init"])).pipe(ll(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var c,p,m,h,f,g,v;let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=(c=this.params.desiredState.videoTrack.getState())==null?void 0:c.id,i=(p=this.videoTracks$.getValue().find(({track:{id:b}})=>b===t))==null?void 0:p.track,r=this.params.output.currentVideoTrack$.getValue(),a=$e(this.video.buffered,this.video.currentTime*1e3),s=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(a/Math.min(s,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),u=Math.max(i&&!e&&(h=(m=this.audioRepresentations.get(i.id))==null?void 0:m.bitrate)!=null?h:0,r&&(g=(f=this.audioRepresentations.get(r.id))==null?void 0:f.bitrate)!=null?g:0),d=We(this.videoTracks$.getValue().map(({track:b})=>b),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:u,forwardBufferHealth:o,current:r,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),l=e?d!=null?d:i:i!=null?i:d;return l&&((v=this.videoTracks$.getValue().find(({track:b})=>b===l))==null?void 0:v.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){re(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:wa.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ee(this.video)}};var yi=class extends ct{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Gn,interval as Sl,map as vl}from"@vkontakte/videoplayer-shared";var Ti=class extends ct{constructor(e){super(e),this.liveOffset=new we}subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Gn({interval:Sl(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()==="playing"){let s=e.position$.getValue()+(r-1);s<=0&&e.position$.next(s),(a=this.liveOffset)==null||a.resetTo(-s*1e3)}})).add(Gn({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(vl(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",a=-e,s=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(s).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(s,r)})}};import{assertNever as Ii,assertNonNullable as Wn,debounce as yl,ErrorCategory as mr,filter as Tl,isNonNullable as Il,isNullable as El,map as fr,merge as xl,Observable as Pl,observableFrom as kl,Subscription as Al,videoSizeToQuality as wl}from"@vkontakte/videoplayer-shared";var ye={};var wt=(n,e)=>new Pl(t=>{let i=(r,a)=>t.next(a);return n.on(e,i),()=>n.off(e,i)}),Ei=class{constructor(e){this.subscription=new Al;this.videoState=new L("initializing");this.textTracksManager=new le;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Ii(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ii(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ii(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ii(e)}break;default:Ii(t)}};this.video=Z(e.container,e.tuning.audioVideoSyncRate),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(j(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),ee(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:mr.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(ye.Hls=r.default,ye.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){Wn(ye.Hls,"hls.js not loaded"),this.hls=new ye.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Wn(ye.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:mr.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=ie(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Ie(this.video,e.isLooped,i)),this.subscription.add(te(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(de(this.video,e.playbackRate,r.playbackRateState$,i)),a(pe(this.video),t.elementVisible$),a(this.videoState.stateChangeEnded$.pipe(fr(d=>d.to)),this.params.output.playbackState$),this.subscription.add(wt(this.hls,ye.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:mr.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)==null?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())==null?void 0:d.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),a(wt(this.hls,ye.Events.MANIFEST_PARSED).pipe(fr(({levels:d})=>d.reduce((l,c)=>{var b,k;let p=c.name||c.height.toString(10),{width:m,height:h}=c,f=(k=He((b=c.attrs.QUALITY)!=null?b:""))!=null?k:wl({width:m,height:h});if(!f)return l;let g=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:f,bitrate:c.bitrate/1e3,size:{width:m,height:h},fps:g};return this.trackLevels.set(p,{track:v,level:c}),l.push(v),l},[]))),t.availableVideoTracks$),a(wt(this.hls,ye.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){let l=[];for(let c of d.subtitleTracks){let p=c.name,m=c.attrs.URI||"",h=c.lang,f="internal";l.push({id:p,url:m,language:h,type:f})}e.internalTextTracks.startTransitionTo(l)}}),a(wt(this.hls,ye.Events.LEVEL_LOADING).pipe(fr(({url:d})=>j(d))),t.hostname$),a(wt(this.hls,ye.Events.FRAG_CHANGED),d=>{var p,m,h,f;let{video:l,audio:c}=d.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=l==null?void 0:l.endPTS)!=null?p:0)-((m=l==null?void 0:l.startPTS)!=null?m:0))*1e3),t.currentAudioSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((f=c==null?void 0:c.startPTS)!=null?f:0))*1e3)}),this.subscription.add(_e(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));let s=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))==null?void 0:l.track},o=wt(this.hls,ye.Events.LEVEL_SWITCHED).pipe(fr(({level:d})=>s(this.hls.levels[d])));o.pipe(Tl(Il)).subscribe(t.currentVideoTrack$,i),this.subscription.add(_e(e.videoTrack,()=>s(this.hls.levels[this.hls.currentLevel]),d=>{var h;if(El(d))return;let l=(h=this.trackLevels.get(d.id))==null?void 0:h.level;if(!l)return;let c=this.hls.levels.indexOf(l),p=this.hls.currentLevel,m=this.hls.levels[p];!m||l.bitrate>m.bitrate?this.hls.nextLevel=c:(this.hls.loadLevel=c,this.hls.loadLevel=c)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=xl(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,kl(["init"])).pipe(yl(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo("playing"),await re(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:mr.DOM,thrown:t}))||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))}pause(){this.videoState.startTransitionTo("paused"),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0)}};var Qn="X-Playback-Duration",La=async n=>{var r;let e=await fetch(n),t=await e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(Qn)?parseInt(e.headers.get(Qn),10):void 0};import{assertNever as Cl,combine as Bl,debounce as Vl,ErrorCategory as gr,filter as Ol,filterChanged as Nl,isNonNullable as Yn,isNullable as Sr,map as qn,merge as _l,observableFrom as Fl,Subscription as Ul,ValueSubject as Ra,VideoQuality as Hl}from"@vkontakte/videoplayer-shared";import{videoSizeToQuality as Ll,getExponentialDelay as $l}from"@vkontakte/videoplayer-shared";var Rl=n=>{let e=null;if(n.QUALITY&&(e=He(n.QUALITY)),!e&&n.RESOLUTION){let[t,i]=n.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Ll({width:t,height:i})}return e!=null?e:null},Dl=(n,e)=>{var a,s;let t=n.split(`
92
+ `),i=[],r=[];for(let o=0;o<t.length;o++){let u=t[o],d=u.match(/^#EXT-X-STREAM-INF:(.+)/),l=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!l)){if(d){let c=Object.fromEntries(d[1].split(",").map(b=>b.split("="))),p=(a=c.QUALITY)!=null?a:`stream-${c.BANDWIDTH}`,m=Rl(c),h;c.BANDWIDTH&&(h=parseInt(c.BANDWIDTH,10)/1e3||void 0),!h&&c["AVERAGE-BANDWIDTH"]&&(h=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let f=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0,g;if(c.RESOLUTION){let[b,k]=c.RESOLUTION.split("x").map(S=>parseInt(S,10));b&&k&&(g={width:b,height:k})}let v=new URL(t[++o],e).toString();m&&i.push({id:p,quality:m,url:v,bandwidth:h,size:g,fps:f})}if(l){let c=Object.fromEntries(l[1].split(",").map(f=>f.split("=")).map(([f,g])=>[f,g.replace(/^"|"$/g,"")])),p=(s=c.URI)==null?void 0:s.replace(/playlist$/,"subtitles.vtt"),m=c.LANGUAGE,h=c.NAME;p&&m&&r.push({type:"internal",id:m,label:h,language:m,url:p,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},Ml=n=>new Promise(e=>{setTimeout(()=>{e()},n)}),$a=0,jn=async(n,e=n,t)=>{let r=await(await fetch(n)).text();$a+=1;try{let{qualityManifests:a,textTracks:s}=Dl(r,e);return{qualityManifests:a,textTracks:s}}catch(a){if($a<=t.manifestRetryMaxCount)return await Ml($l($a-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),jn(n,e,t)}return{qualityManifests:[],textTracks:[]}},br=jn;var xi=class{constructor(e){this.subscription=new Ul;this.videoState=new L("stopped");this.textTracksManager=new le;this.manifests$=new Ra([]);this.liveOffset=new we;this.manifestStartTime$=new Ra(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((r==null?void 0:r.to)!=="paused"&&d.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(d.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":i==="ready"?T(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.pause()):(r==null?void 0:r.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let l=this.liveOffset.getTotalOffset();l>=this.maxSeekBackTime$.getValue()&&(l=0,this.liveOffset.resetTo(l)),this.liveOffset.resume(),this.params.output.position$.next(-l/1e3),this.prepare()}else(r==null?void 0:r.to)==="paused"&&(T(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Cl(t)}};var t;this.params=e,this.video=Z(e.container,e.tuning.audioVideoSyncRate),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Hl.INVARIANT,url:this.params.source.url},br(q(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:i})=>{i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:gr.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:gr.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(j(this.params.source.url)),this.maxSeekBackTime$=new Ra((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,d,l,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(d=t.getState())==null?void 0:d.id)!=null?c:"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:gr.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ie(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(te(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(de(this.video,t.playbackRate,r.playbackRateState$,i)),a(pe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(Nl(),qn(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Yn(d.to)){let c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let p=this.manifests$.getValue().find(m=>m.id===c);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(j(p.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var u,d,l;let o=(l=(d=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:d.call(u))==null?void 0:l.getTime();this.manifestStartTime$.next(o||void 0)},i)),this.subscription.add(Bl({startTime:this.manifestStartTime$.pipe(Ol(Yn)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(qn(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:p})=>({id:u,quality:d,size:l,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));let s=_l(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Fl(["init"])).pipe(Vl(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ee(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Sr(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:d,min:l}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[c,p]of[[d,"mq"],[l,"lq"]]){let m=String(parseFloat(c||""));p&&c&&r.searchParams.set(p,m)}}let a=this.params.format==="HLS_LIVE_CMAF"?2:0,s=q(r.toString(),this.liveOffset.getTotalOffset(),a);this.video.setAttribute("src",s),this.video.load(),La(s).then(d=>{var l;if(!Sr(d))this.maxSeekBackTime$.next(d);else{let c=(l=this.params.source.maxSeekBackTime)!=null?l:this.maxSeekBackTime$.getValue();if(Sr(c)||!isFinite(c))try{fetch(s).then(p=>p.text()).then(p=>{var h;let m=(h=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:h[1];if(m){let f=new URL(m,s).toString();La(f).then(g=>{Sr(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){re(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:gr.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as Gl,debounce as Wl,ErrorCategory as Da,fromEvent as Ma,isNonNullable as Ql,isNullable as jl,map as zn,merge as Kn,observableFrom as Jn,Subscription as Yl,ValueSubject as ql,VideoQuality as zl,isIOS as Kl}from"@vkontakte/videoplayer-shared";var Pi=class{constructor(e){this.subscription=new Yl;this.videoState=new L("stopped");this.textTracksManager=new le;this.manifests$=new ql([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),s=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let d=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a||s||o){let l=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(l);let{currentTime:c}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),d.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!=="paused"&&d.state==="requested"&&this.seek(d.position),t){case"ready":i==="ready"?T(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(r==null?void 0:r.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return Gl(t)}};this.params=e,this.video=Z(e.container,e.tuning.audioVideoSyncRate),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:zl.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(j(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),br(q(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Da.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,d,l,c;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),a=(c=(l=(u=r==null?void 0:r.to)==null?void 0:u.id)!=null?l:(d=t.getState())==null?void 0:d.id)!=null?c:"master",s=this.manifests$.getValue();if(!s.length)return;let o=i?"master":a;return i&&!r&&t.startTransitionTo(this.masterManifest),s.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Da.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ie(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(zn(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ie(this.video,t.isLooped,i)),this.subscription.add(te(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(de(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var c;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&Ql(d.to)){let p=d.to.id;this.params.desiredState.videoTrack.setState(d.to);let m=this.manifests$.getValue().find(h=>h.id===p);if(m){this.params.output.currentVideoTrack$.next(m),this.params.output.hostname$.next(j(m.url));let h=this.params.desiredState.playbackRate.getState(),f=(c=this.params.output.element$.getValue())==null?void 0:c.playbackRate;if(h!==f){let g=this.params.output.element$.getValue();g&&(this.params.desiredState.playbackRate.setState(h),g.playbackRate=h)}}}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(zn(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:p})=>({id:u,quality:d,size:l,fps:p,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!Kl()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Kn(Ma(o,"addtrack"),Ma(o,"removetrack"),Ma(o,"change"),Jn(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let s=Kn(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Jn(["init"])).pipe(Wl(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ee(this.video)}prepare(){var a,s;let e=this.selectManifest();if(jl(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(s=(a=t==null?void 0:t.to)!=null?a:i)!=null?s:{};for(let[d,l]of[[o,"mq"],[u,"lq"]]){let c=String(parseFloat(d||""));l&&d&&r.searchParams.set(l,c)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){re(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Da.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as Jl,assertNonNullable as Xn,debounce as Xl,ErrorCategory as Zn,isHigher as Zl,isHigherOrEqual as ec,isInvariantQuality as eo,isLowerOrEqual as tc,isNonNullable as ic,merge as rc,observableFrom as ac,Subscription as sc,map as nc}from"@vkontakte/videoplayer-shared";var ki=class{constructor(e){this.subscription=new sc;this.videoState=new L("stopped");this.trackUrls={};this.textTracksManager=new le;this.syncPlayback=()=>{var u,d,l;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.autoVideoTrackLimits.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(a&&e!=="ready"&&!s){this.handleQualityLimitTransition(a.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){let{currentTime:c}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:c*1e3,forcePrecise:!0}),s.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((l=(d=this.trackUrls[s.to.id])==null?void 0:d.track)==null?void 0:l.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?T(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(i==null?void 0:i.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return Jl(e)}};this.params=e,this.video=Z(e.container,e.tuning.audioVideoSyncRate),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{let a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:Zn.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ie(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),a(this.videoState.stateChangeEnded$.pipe(nc(o=>o.to)),this.params.output.playbackState$),this.subscription.add(Ie(this.video,t.isLooped,i)),this.subscription.add(te(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(de(this.video,t.playbackRate,r.playbackRateState$,i)),a(pe(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),T(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),T(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var u,d;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&ic(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let l=this.params.desiredState.playbackRate.getState(),c=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(l!==c){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(l),p.playbackRate=l)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let s=rc(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,ac(["init"])).pipe(Xl(0));this.subscription.add(s.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ee(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;Xn(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Xn(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=bi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(j(t))}playIfAllowed(){re(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Zn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var r,a,s,o;let t,i=e;if(e&&((r=this.params.output.currentVideoTrack$.getValue())==null?void 0:r.quality)!==e){let u=(a=Object.values(this.trackUrls).find(c=>!eo(c.track.quality)&&tc(c.track.quality,e)))==null?void 0:a.track,d=(s=this.params.desiredState.videoTrack.getState())==null?void 0:s.id,l=(o=this.trackUrls[d!=null?d:"0"])==null?void 0:o.track;if(u&&l&&ec(l.quality,u.quality)&&(t=u),!t){let c=Object.values(this.trackUrls).filter(m=>!eo(m.track.quality)&&Zl(m.track.quality,e)),p=c.length;p&&(t=c[p-1].track)}t&&(i=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(d=>d.track);t=We(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:i})}};import{assertNever as io,debounce as lc,merge as ro,observableFrom as cc,Subscription as pc,map as ao,ValueSubject as hc,ErrorCategory as Ba,VideoQuality as mc}from"@vkontakte/videoplayer-shared";import{ErrorCategory as oc}from"@vkontakte/videoplayer-shared";var to=["stun:videostun.mycdn.me:80"],uc=1e3,dc=3,Ca=()=>null,vr=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=Ca;this.externalStopCallback=Ca;this.externalErrorCallback=Ca;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{let t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{let e={iceServers:[{urls:to}]};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:oc.WTF,message:e.message})}async onPeerConnectionStream(e){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){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),uc)}normalizeOptions(e={}){let t={stunServerList:to,maxRetryNumber:dc,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ai=class{constructor(e){this.videoState=new L("stopped");this.maxSeekBackTime$=new hc(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),T(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let a=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(a){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.pause()):(i==null?void 0:i.to)==="playing"&&T(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&T(this.params.desiredState.playbackState,"paused");return;default:return io(e)}};this.subscription=new pc,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Z(e.container,e.tuning.audioVideoSyncRate),this.liveStreamClient=new vr(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.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ee(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=s=>{e.error$.next({id:"WebRTCLiveProvider",category:Ba.WTF,message:"WebRTCLiveProvider internal logic error",thrown:s})};ro(this.videoState.stateChangeStarted$.pipe(ao(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ao(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(s)}`})});let r=ie(this.video),a=(s,o)=>this.subscription.add(s.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(pe(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(s=>{e.duration$.next(s===1/0?0:s)})).add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())==null?void 0:s.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(te(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.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 io(s.to)}},i)).add(ro(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,cc(["init"])).pipe(lc(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(j(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:mc.INVARIANT}),this.video.srcObject=e,T(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:Ba.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){re(this.video).then(e=>{e||(this.videoState.setState("paused"),T(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ba.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var wi=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 Di,assertNonNullable as qe,ErrorCategory as wr,filter as Dc,isNonNullable as Lo,isNullable as Mc,map as Cc,merge as Bc,once as Vc,Subject as fe,Subscription as $o,ValueSubject as M}from"@vkontakte/videoplayer-shared";import{assertNever as kr,CurrentClientBrowser as gc,CurrentClientDevice as Sc,getCurrentBrowser as so,isAndroid as vc}from"@vkontakte/videoplayer-shared";var go=vc(),me=document.createElement("video"),yc='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Tc='video/mp4; codecs="hev1.1.6.L93.B0"',So='video/webm; codecs="vp09.00.10.08"',vo='video/webm; codecs="av01.0.00M.08"',Ic='audio/mp4; codecs="mp4a.40.2"',Ec='audio/webm; codecs="opus"',no,oo,pt={mms:sr(),mse:wn(),hls:!!((no=me.canPlayType)!=null&&no.call(me,"application/x-mpegurl")||(oo=me.canPlayType)!=null&&oo.call(me,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},uo,lo,he={mp4:!!((uo=me.canPlayType)!=null&&uo.call(me,"video/mp4")),webm:!!((lo=me.canPlayType)!=null&&lo.call(me,"video/webm")),cmaf:!0},yr,co,Tr,po,Ir,ho,Er,mo,xr,fo,Pr,bo,Pe={h264:!!((co=(yr=Re())==null?void 0:yr.isTypeSupported)!=null&&co.call(yr,yc)),h265:!!((po=(Tr=Re())==null?void 0:Tr.isTypeSupported)!=null&&po.call(Tr,Tc)),vp9:!!((ho=(Ir=Re())==null?void 0:Ir.isTypeSupported)!=null&&ho.call(Ir,So)),av1:!!((mo=(Er=Re())==null?void 0:Er.isTypeSupported)!=null&&mo.call(Er,vo)),aac:!!((fo=(xr=Re())==null?void 0:xr.isTypeSupported)!=null&&fo.call(xr,Ic)),opus:!!((bo=(Pr=Re())==null?void 0:Pr.isTypeSupported)!=null&&bo.call(Pr,Ec))},Li=(Pe.h264||Pe.h265)&&Pe.aac,ht,xc=async()=>{if(!window.navigator.mediaCapabilities)return;let n={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:vo}}),window.navigator.mediaCapabilities.decodingInfo({...n,video:{...n.video,contentType:So}})]);ht={DASH_WEBM_AV1:e,DASH_WEBM:t}};try{xc()}catch(n){console.error(n)}var Lt=pt.hls&&he.mp4,yo=()=>Object.keys(Pe).filter(n=>Pe[n]),To=(n,e=!1,t=!1)=>{let i=pt.mse||pt.mms&&t;return n.filter(r=>{switch(r){case"DASH_SEP":return i&&he.mp4&&Li;case"DASH_WEBM":return i&&he.webm&&Pe.vp9&&Pe.opus;case"DASH_WEBM_AV1":return i&&he.webm&&Pe.av1&&Pe.opus;case"DASH_LIVE":return pt.mse&&he.mp4&&Li;case"DASH_LIVE_CMAF":return i&&he.mp4&&Li&&he.cmaf;case"DASH_ONDEMAND":return i&&he.mp4&&Li;case"HLS":case"HLS_ONDEMAND":return Lt||e&&pt.mse&&he.mp4&&Li;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Lt;case"MPEG":return he.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return pt.webrtc&&pt.ws&&Pe.h264&&(he.mp4||he.webm);default:return kr(r)}})},Ye=n=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(n){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return ht?ht[t].smooth?[t,e]:ht[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ht?ht[t].powerEfficient?[t,e]:ht[e].powerEfficient?[e,t]:[t,e]:[e,t];default:kr(n)}return[e,t]},Io=({webmCodec:n,androidPreferredFormat:e})=>{if(go)switch(e){case"mpeg":return["MPEG",...Ye(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...Ye(n),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...Ye(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...Ye(n),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...Ye(n),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...Ye(n),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:kr(e)}return Lt?[...Ye(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...Ye(n),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},Eo=({androidPreferredFormat:n,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],a=[...i,...r],s=[...r,...i],o,u=so().device===Sc.Mac&&so().browser===gc.Safari;if(go)switch(n){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=a;break}case"hls":case"mpeg":{o=s;break}default:kr(n)}else Lt&&!u?o=s:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=a;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Va=n=>n?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];import{Observable as Pc,map as xo,Subscription as kc,Subject as Ac}from"@vkontakte/videoplayer-shared";var Po=n=>new Pc(e=>{let t=new kc,i=n.desiredPlaybackState$.stateChangeStarted$.pipe(xo(({from:d,to:l})=>`${d}-${l}`)),r=n.desiredPlaybackState$.stateChangeEnded$,a=n.providerChanged$.pipe(xo(({type:d})=>d!==void 0)),s=new Ac,o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>s.next(d),n.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>s.next(u),n.maxTransitionInterval)))})),t.add(s.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as ko,Subscription as wc,combine as Lc,filter as Ao,once as wo}from"@vkontakte/videoplayer-shared";var $i=null,Ar=null;function Oa(){return $i||($i=new(window.AudioContext||window.webkitAudioContext)),Ar||(Ar=new GainNode($i,{gain:1}),Ar.connect($i.destination)),{audioCtx:$i,gainNode:Ar}}import{getCurrentBrowser as $c,CurrentClientBrowser as Rc}from"@vkontakte/videoplayer-shared";var $t=class $t{constructor(e,t,i,r,a){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.subscriptions=new wc;this.lastAudioContextResumeId=0;!a||!this.isSupported()||r===1||this.subscriptions.add(this.provider$.pipe(Ao(s=>!!s.type),wo()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){let{browser:t}=$c();t===Rc.Safari&&e!=="MPEG"||this.subscriptions.add(Lc({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(Ao(({playbackState:i,video:r,volume:{muted:a,volume:s}})=>i==="playing"&&!!r&&!a&&!!s),wo()).subscribe(({video:i})=>this.initAudioContextOnce(i)))}isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){let{volumeMultiplier:t}=this,{audioCtx:i,gainNode:r}=Oa(),a=(Math.random()+1)*999999;this.lastAudioContextResumeId=a,i.resume().then(()=>{var s;if(a!==this.lastAudioContextResumeId)throw new Error(`AudioContext.resume() resolved after ${$t.errorId} destroyed`);r.gain.value=t;try{new MediaElementAudioSourceNode(i,{mediaElement:e}).connect(r)}catch(o){this.volumeMultiplierError$.next({id:$t.errorId,category:ko.VIDEO_PIPELINE,message:(s=o==null?void 0:o.message)!=null?s:"initAudioContextOnce: (new MediaElementAudioSourceNode).connect() exception",thrown:o})}}).catch(s=>{var o;this.volumeMultiplierError$.next({id:$t.errorId,category:ko.VIDEO_PIPELINE,message:(o=s==null?void 0:s.message)!=null?o:"initAudioContextOnce: AudioContext.resume() exception",thrown:s})})}destroy(){let{gainNode:e}=Oa();e.gain.value=1,this.subscriptions.unsubscribe(),this.lastAudioContextResumeId=0}};$t.errorId="VolumeMultiplierManager";var Ri=$t;var Oc={chunkDuration:5e3,maxParallelRequests:5},Mi=class{constructor(e){this.current$=new M({type:void 0});this.providerError$=new fe;this.noAvailableProvidersError$=new fe;this.volumeMultiplierError$=new fe;this.providerOutput={position$:new M(0),duration$:new M(1/0),volume$:new M({muted:!1,volume:1}),currentVideoTrack$:new M(void 0),currentVideoSegmentLength$:new M(0),currentAudioSegmentLength$:new M(0),availableVideoTracks$:new M([]),availableAudioTracks$:new M([]),isAudioAvailable$:new M(!0),autoVideoTrackLimitingAvailable$:new M(!1),autoVideoTrackLimits$:new M(void 0),currentBuffer$:new M(void 0),isBuffering$:new M(!0),error$:new fe,warning$:new fe,willSeekEvent$:new fe,seekedEvent$:new fe,loopedEvent$:new fe,endedEvent$:new fe,firstBytesEvent$:new fe,firstFrameEvent$:new fe,canplay$:new fe,isLive$:new M(void 0),isLowLatency$:new M(!1),canChangePlaybackSpeed$:new M(!0),liveTime$:new M(void 0),liveBufferTime$:new M(void 0),availableTextTracks$:new M([]),currentTextTrack$:new M(void 0),hostname$:new M(void 0),httpConnectionType$:new M(void 0),httpConnectionReused$:new M(void 0),inPiP$:new M(!1),inFullscreen$:new M(!1),element$:new M(void 0),elementVisible$:new M(!0),availableSources$:new M(void 0),is3DVideo$:new M(!1),playbackState$:new M("")};this.subscription=new $o;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=To([...Eo(this.params.tuning),...Io(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>Lo(e.sources[u])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,a=[];i?a=[i]:r.length?a=[...t.filter(u=>!r.includes(u)),...t.filter(u=>r.includes(u))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new wi(a);let s=[...Va(!0),...Va(!1)];this.chromecastFormatsIterator=new wi(s.filter(u=>Lo(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Ri(this.providerOutput,this.current$,this.volumeMultiplierError$,(o=this.params.volumeMultiplier)!=null?o:1,this.params.tuning.useVolumeMultiplier)}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()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Mc(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:wr.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(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"});let t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let s=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:s.x,y:s.y})}e.destroy();let a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Di(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,s={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return qe(o),new yi({...s,source:o,sourceHls:u})}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return qe(o),new Ti({...s,source:o})}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return qe(o),Lt||!this.params.tuning.useHlsJs?new Pi({...s,source:o}):new Ei({...s,source:o})}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return qe(o),new xi({...s,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case"MPEG":{let o=this.applyFailoverHost(t[e]);return qe(o),new ki({...s,source:o})}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return qe(o),new Js({...s,source:o,config:{...Oc,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return qe(o),new Ai({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return Di(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:a}=this.params,s=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return qe(o),new Bt({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:s,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 Di(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Di(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 Di(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Object.fromEntries(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){let e=new $o,t=!1,i=0;return e.add(Bc(this.providerOutput.error$,Po({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(Cc(r=>({id:`ProviderHangup:${r}`,category:wr.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(Dc(({to:a})=>a==="playing"),Vc()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let a=this.current$.getValue().destination;if(a==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let s=r.category===wr.NETWORK,o=r.category===wr.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(s&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:"SCREEN")}})),e}};import{fromEvent as Lr,once as Nc,combine as _c,Subscription as Ro,ValueSubject as Na,map as Fc,filter as Uc,isNonNullable as $r,now as ne,safeStorage as _a}from"@vkontakte/videoplayer-shared";var Hc=5e3,Do="one_video_throughput",Mo="one_video_rtt",De=window.navigator.connection,Co=()=>{let n=De==null?void 0:De.downlink;if($r(n)&&n!==10)return n*1e3},Bo=()=>{let n=De==null?void 0:De.rtt;if($r(n)&&n!==3e3)return n},Vo=(n,e,t)=>{let i=t*8,r=i/n;return i/(r+e)},Fa=class n{constructor(e){this.subscription=new Ro;this.concurrentDownloads=new Set;var r,a;this.tuningConfig=e;let t=n.load(Do)||(e.useBrowserEstimation?Co():void 0)||Hc,i=(a=(r=n.load(Mo))!=null?r:e.useBrowserEstimation?Bo():void 0)!=null?a:0;if(this.throughput$=new Na(t),this.rtt$=new Na(i),this.rttAdjustedThroughput$=new Na(Vo(t,i,e.rttPenaltyRequestSize)),this.throughput=dt.getSmoothedValue(t,-1,e),this.rtt=dt.getSmoothedValue(i,1,e),e.useBrowserEstimation){let s=()=>{let u=Co();u&&this.throughput.next(u);let d=Bo();$r(d)&&this.rtt.next(d)};De&&"onchange"in De&&this.subscription.add(Lr(De,"change").subscribe(s)),s()}this.subscription.add(this.throughput.smoothed$.subscribe(s=>{_a.set(Do,s.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(s=>{_a.set(Mo,s.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(_c({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(Fc(({throughput:s,rtt:o})=>Vo(s,o,e.rttPenaltyRequestSize)),Uc(s=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(s-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=ne(),r=new Ro;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Lr(e,"progress").pipe(Nc()).subscribe(a=>{t=a.loaded,i=ne()}));break;case 1:case 0:r.add(Lr(e,"loadstart").subscribe(()=>{t=0,i=ne()}));break}r.add(Lr(e,"loadend").subscribe(a=>{if(e.status===200){let s=a.loaded,o=ne(),u=s-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=ne(),s=0,o=ne(),u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=async({done:l,value:c})=>{if(l)!t&&this.addRawSpeed(r,ne()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){let p=ne();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-a>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let h=o-a;h&&this.addRawSpeed(s,h,1,t),s=c.byteLength,a=ne()}else s+=c.byteLength;o=ne()}else r+=c.byteLength,s+=c.byteLength,s>=this.tuningConfig.streamMinSampleSize&&ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(s,ne()-o,this.concurrentDownloads.size),s=0,o=ne());await(i==null?void 0:i.read().then(d,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(n.sanityCheck(e,t,r)){let a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=_a.get(e);if($r(t))return(i=parseInt(t,10))!=null?i:void 0}},Oo=Fa;import{fillWithDefault as Gc,VideoQuality as No}from"@vkontakte/videoplayer-shared";var _o={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:No.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:No.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,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"mpeg",preferCMAF:!0,preferWebRTC:!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,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,useNewPruneBufferStrategy:!1,useNewPartialSegmentFeeding:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1},Fo=n=>{var e;return{...Gc(n,_o),configName:[...(e=n.configName)!=null?e:[],..._o.configName]}};import{assertNonNullable as Rr,combine as Dr,ErrorCategory as Mr,filter as Ci,filterChanged as be,fromEvent as Ha,isNonNullable as Kc,isNullable as Jc,Logger as Xc,map as D,mapTo as Wo,merge as ze,now as Cr,once as Me,Subject as F,Subscription as Qo,tap as jo,ValueSubject as E,isHigher as Zc,isInvariantQuality as Yo}from"@vkontakte/videoplayer-shared";import{merge as Wc,map as Qc,filter as Uo,isNonNullable as jc}from"@vkontakte/videoplayer-shared";var Ua=({seekState:n,position$:e})=>Wc(n.stateChangeEnded$.pipe(Qc(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),Uo(jc)),e.pipe(Uo(()=>n.getState().state==="none")));import{assertNonNullable as Yc}from"@vkontakte/videoplayer-shared";var Ho=n=>{let e=typeof n.container=="string"?document.getElementById(n.container):n.container;return Yc(e,`Wrong container or containerId {${n.container}}`),e};import{filter as qc,once as zc}from"@vkontakte/videoplayer-shared";var Go=(n,e,t,i)=>{n!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(qc(r=>r.length>0),zc()).subscribe(r=>{r.find(i)&&e.startTransitionTo(n)}):(n===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(n)};var Br=class{constructor(e={configName:[]}){this.subscription=new Qo;this.logger=new Xc;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new E(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new L("stopped"),seekState:new L({state:"none"}),volume:new L({volume:1,muted:!1}),videoTrack:new L(void 0),autoVideoTrackSwitching:new L(!0),autoVideoTrackLimits:new L({}),isLooped:new L(!1),playbackRate:new L(1),externalTextTracks:new L([]),internalTextTracks:new L([]),currentTextTrack:new L(void 0),textTrackCuesSettings:new L({}),cameraOrientation:new L({x:0,y:0})};this.info={playbackState$:new E("stopped"),position$:new E(0),duration$:new E(1/0),muted$:new E(!1),volume$:new E(1),availableQualities$:new E([]),availableQualitiesFps$:new E({}),availableAudioTracks$:new E([]),isAudioAvailable$:new E(!0),currentQuality$:new E(void 0),isAutoQualityEnabled$:new E(!0),autoQualityLimitingAvailable$:new E(!1),autoQualityLimits$:new E({}),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),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 F,ready$:new F,started$:new F,playing$:new F,paused$:new F,stopped$:new F,willStart$:new F,willResume$:new F,willPause$:new F,willStop$:new F,willDestruct$:new F,watchCoverageRecord$:new F,watchCoverageLive$:new F,managedError$:new F,fatalError$:new F,ended$:new F,looped$:new F,seeked$:new F,willSeek$:new F,firstBytes$:new F,firstFrame$:new F,canplay$:new F,log$:new F};this.experimental={element$:new E(void 0),tuningConfigName$:new E([]),enableDebugTelemetry$:new E(!1),dumpTelemetry:Ns};if(this.initLogs(),this.tuning=Fo(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Qi({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Oo(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{let a=Reflect.get(t,i,r);return typeof a!="function"?a:(...s)=>{try{return a.apply(t,s)}catch(o){let u=s.map(c=>JSON.stringify(c,(p,m)=>{let h=typeof m;return["number","string","boolean"].includes(h)?m:m===null?null:`<${h}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:Mr.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=Ho(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Mi({sources:e.sources,meta:(i=e.meta)!=null?i:{},failoverHosts:(r=e.failoverHosts)!=null?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){let e=this.desiredState.playbackState;return e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Wt()?Ha(document,"visibilitychange").pipe(Me()).subscribe(e):e(),this}pause(){let e=this.desiredState.playbackState;return e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:"requested",position:e*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return 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.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){Rr(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Ci(i=>i.length>0),Me()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var i;Rr(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();return t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return Go(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let i=this.getScene3D();if(i){let r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.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(Jc(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return Kc(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(ze(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(Ci(({from:e})=>e==="stopped"),Me()).subscribe(()=>{this.initedAt=Cr(),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 s=this.desiredState.seekState.getState();s.state==="requested"?this.desiredState.seekState.setState({...s,state:"applying"}):this.events.managedError$.next({id:`WillSeekIn${s.state}`,category:Mr.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(D(s=>s.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(D(s=>s.destination),be()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(D(s=>s.map(({quality:o})=>o).sort((o,u)=>Yo(o)?1:Yo(u)?-1:Zc(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(s=>{let o={};for(let u of s)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{this.info.currentQuality$.next(s==null?void 0:s.quality),this.info.videoBitrate$.next(s==null?void 0:s.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(be()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(be()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(be()).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(s=>{this.desiredState.autoVideoTrackLimits.setState(s!=null?s:{})})).add(e.providerOutput.currentBuffer$.pipe(D(s=>s?{start:s.from,end:s.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(Dr({hasLiveOffsetByPaused:ze(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(D(s=>s.to),be(),D(s=>s==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:s,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),s){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Dr({atLiveEdge:Dr({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ua({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(D(({isLive:s,position:o,isLowLatency:u})=>{let d=this.getActiveLiveDelay(u);return s&&Math.abs(o)<d/1e3}),be(),jo(s=>s&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(D(({atLiveEdge:s,hasPausedTimeoutCase:o})=>s&&!o)).subscribe(this.info.atLiveEdge$)).add(Dr({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(D(({isLive:s,position:o,duration:u})=>s&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),be(),jo(s=>s&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(D(s=>s.muted),be()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(D(s=>s.volume),be()).subscribe(this.info.volume$)).add(Ua({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(ze(e.providerOutput.endedEvent$.pipe(Wo(!0)),e.providerOutput.seekedEvent$.pipe(Wo(!1))).pipe(be()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(D(s=>({id:s?`No${s}`:"NoProviders",category:Mr.VIDEO_PIPELINE,message:s?`${s} 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(Me(),D(s=>s!=null?s:Cr()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Me(),D(()=>Cr()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Me(),D(()=>Cr()-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 i=new E(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Ci(({to:s})=>s==="playing"),Me()).subscribe(()=>i.next(!1)));let r=0,a=ze(e.providerOutput.isBuffering$,t,i).pipe(D(()=>{let s=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return s&&!o}),be());this.subscription.add(a.subscribe(s=>{s?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(ze(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{let s=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:s==null?void 0:s.videoWidth,height:s==null?void 0:s.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(s=>{var u,d;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=s==null?void 0:s.size)==null?void 0:u.width,height:(d=s==null?void 0:s.size)==null?void 0:d.height},{width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(ze(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let s=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=e.providerOutput.elementVisible$.getValue(),l=this.chromecastInitializer.castState$.getValue(),c;l==="CONNECTED"?c="second_screen":u?d?s?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(D(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new Qo;this.subscription.add(t),this.subscription.add(e.current$.pipe(be((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Ci(i=>i.length>0),Me()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t,i=(r=this.desiredState.videoTrack.getState())==null?void 0:r.quality;i&&(t=e.find(({quality:a})=>a===i),t||this.setAutoQuality(!0)),t||(t=We(e,{container:this.domContainer.getBoundingClientRect(),throughput: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(ze(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(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Rr(this.providerContainer),Rr(e),Os(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Vs(i)),this.providerContainer.current$.subscribe(({type:i})=>_t("provider",i)),e.duration$.subscribe(i=>_t("duration",i)),e.availableVideoTracks$.pipe(Ci(i=>!!i.length),Me()).subscribe(i=>_t("tracks",i)),this.events.fatalError$.subscribe(new K("fatalError")),this.events.managedError$.subscribe(new K("managedError")),e.position$.subscribe(new K("position")),e.currentVideoTrack$.pipe(D(i=>i==null?void 0:i.quality)).subscribe(new K("quality")),this.info.currentBuffer$.subscribe(new K("buffer")),e.isBuffering$.subscribe(new K("isBuffering"))].forEach(i=>this.subscription.add(i)),_t("codecs",yo())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Mr.DOM,message:String(r)})})};this.subscription.add(ze(Ha(document,"visibilitychange"),Ha(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()==="playing",s=!!e&&!(e!=null&&e.released);r&&a?s||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as Qx,Observable as jx,Subject as Yx,ValueSubject as qx,VideoQuality as zx}from"@vkontakte/videoplayer-shared";var Kx=`@vkontakte/videoplayer-core@${os}`;export{Gi as ChromecastState,jr as HttpConnectionType,jx as Observable,X as PlaybackState,Br as Player,Kx as SDK_VERSION,Yx as Subject,Qx as Subscription,Yr as Surface,os as VERSION,qx as ValueSubject,Ne as VideoFormat,zx as VideoQuality};