@vkontakte/videoplayer-core 2.0.104-dev.7ccfc328.0 → 2.0.105-dev.27e8f5c9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.esm.js CHANGED
@@ -1,15 +1,15 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.104-dev.7ccfc328.0
3
- * Mon, 24 Jun 2024 09:56:11 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-104/doc/
2
+ * @vkontakte/videoplayer-core v2.0.105-dev.27e8f5c9.0
3
+ * Wed, 26 Jun 2024 08:17:33 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-105/doc/
5
5
  */
6
- var mv=Object.create;var zs=Object.defineProperty,bv=Object.defineProperties,gv=Object.getOwnPropertyDescriptor,vv=Object.getOwnPropertyDescriptors,Sv=Object.getOwnPropertyNames,ol=Object.getOwnPropertySymbols,yv=Object.getPrototypeOf,ll=Object.prototype.hasOwnProperty,Tv=Object.prototype.propertyIsEnumerable;var Ne=Math.pow,ul=(i,e,t)=>e in i?zs(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,w=(i,e)=>{for(var t in e||(e={}))ll.call(e,t)&&ul(i,t,e[t]);if(ol)for(var t of ol(e))Tv.call(e,t)&&ul(i,t,e[t]);return i},B=(i,e)=>bv(i,vv(e));var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var Iv=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Sv(e))!ll.call(i,a)&&a!==t&&zs(i,a,{get:()=>e[a],enumerable:!(r=gv(e,a))||r.enumerable});return i};var Fe=(i,e,t)=>(t=i!=null?mv(yv(i)):{},Iv(e||!i||!i.__esModule?zs(t,"default",{value:i,enumerable:!0}):t,i));var R=(i,e,t)=>new Promise((r,a)=>{var s=u=>{try{o(t.next(u))}catch(l){a(l)}},n=u=>{try{o(t.throw(u))}catch(l){a(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(i,e)).next())}),Ev=function(i,e){this[0]=i,this[1]=e},J=(i,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Ev,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},a=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(i,e),s[Symbol.asyncIterator]=()=>s,a("next"),a("throw"),a("return"),s};var me=m((IL,gl)=>{"use strict";gl.exports=function(i){try{return!!i()}catch(e){return!0}}});var Or=m((EL,vl)=>{"use strict";var $v=me();vl.exports=!$v(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ne=m((xL,Tl)=>{"use strict";var Sl=Or(),yl=Function.prototype,en=yl.call,Cv=Sl&&yl.bind.bind(en,en);Tl.exports=Sl?Cv:function(i){return function(){return en.apply(i,arguments)}}});var rr=m((PL,El)=>{"use strict";var Il=ne(),Dv=Il({}.toString),Mv=Il("".slice);El.exports=function(i){return Mv(Dv(i),8,-1)}});var Pl=m((kL,xl)=>{"use strict";var Ov=ne(),Bv=me(),Vv=rr(),tn=Object,_v=Ov("".split);xl.exports=Bv(function(){return!tn("z").propertyIsEnumerable(0)})?function(i){return Vv(i)=="String"?_v(i,""):tn(i)}:tn});var ir=m((wL,kl)=>{"use strict";kl.exports=function(i){return i==null}});var ca=m((AL,wl)=>{"use strict";var Nv=ir(),Fv=TypeError;wl.exports=function(i){if(Nv(i))throw Fv("Can't call method on "+i);return i}});var ar=m((RL,Al)=>{"use strict";var qv=Pl(),Uv=ca();Al.exports=function(i){return qv(Uv(i))}});var rn=m((LL,Rl)=>{"use strict";Rl.exports=function(){}});var Rt=m(($L,Ll)=>{"use strict";Ll.exports={}});var X=m(($l,Cl)=>{"use strict";var da=function(i){return i&&i.Math==Math&&i};Cl.exports=da(typeof globalThis=="object"&&globalThis)||da(typeof window=="object"&&window)||da(typeof self=="object"&&self)||da(typeof global=="object"&&global)||function(){return this}()||$l||Function("return this")()});var sn=m((CL,Dl)=>{"use strict";var an=typeof document=="object"&&document.all,Hv=typeof an=="undefined"&&an!==void 0;Dl.exports={all:an,IS_HTMLDDA:Hv}});var G=m((DL,Ol)=>{"use strict";var Ml=sn(),jv=Ml.all;Ol.exports=Ml.IS_HTMLDDA?function(i){return typeof i=="function"||i===jv}:function(i){return typeof i=="function"}});var _l=m((ML,Vl)=>{"use strict";var Gv=X(),Yv=G(),Bl=Gv.WeakMap;Vl.exports=Yv(Bl)&&/native code/.test(String(Bl))});var qe=m((OL,ql)=>{"use strict";var Nl=G(),Fl=sn(),Wv=Fl.all;ql.exports=Fl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Nl(i)||i===Wv}:function(i){return typeof i=="object"?i!==null:Nl(i)}});var Ue=m((BL,Ul)=>{"use strict";var Qv=me();Ul.exports=!Qv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var pa=m((VL,jl)=>{"use strict";var zv=X(),Hl=qe(),nn=zv.document,Kv=Hl(nn)&&Hl(nn.createElement);jl.exports=function(i){return Kv?nn.createElement(i):{}}});var on=m((_L,Gl)=>{"use strict";var Jv=Ue(),Xv=me(),Zv=pa();Gl.exports=!Jv&&!Xv(function(){return Object.defineProperty(Zv("div"),"a",{get:function(){return 7}}).a!=7})});var un=m((NL,Yl)=>{"use strict";var eS=Ue(),tS=me();Yl.exports=eS&&tS(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Le=m((FL,Wl)=>{"use strict";var rS=qe(),iS=String,aS=TypeError;Wl.exports=function(i){if(rS(i))return i;throw aS(iS(i)+" is not an object")}});var oe=m((qL,Ql)=>{"use strict";var sS=Or(),ha=Function.prototype.call;Ql.exports=sS?ha.bind(ha):function(){return ha.apply(ha,arguments)}});var fa=m((UL,zl)=>{"use strict";zl.exports={}});var We=m((HL,Jl)=>{"use strict";var ln=fa(),cn=X(),nS=G(),Kl=function(i){return nS(i)?i:void 0};Jl.exports=function(i,e){return arguments.length<2?Kl(ln[i])||Kl(cn[i]):ln[i]&&ln[i][e]||cn[i]&&cn[i][e]}});var Br=m((jL,Xl)=>{"use strict";var oS=ne();Xl.exports=oS({}.isPrototypeOf)});var Vr=m((GL,Zl)=>{"use strict";Zl.exports=typeof navigator!="undefined"&&String(navigator.userAgent)||""});var pn=m((YL,sc)=>{"use strict";var ac=X(),dn=Vr(),ec=ac.process,tc=ac.Deno,rc=ec&&ec.versions||tc&&tc.version,ic=rc&&rc.v8,$e,ma;ic&&($e=ic.split("."),ma=$e[0]>0&&$e[0]<4?1:+($e[0]+$e[1]));!ma&&dn&&($e=dn.match(/Edge\/(\d+)/),(!$e||$e[1]>=74)&&($e=dn.match(/Chrome\/(\d+)/),$e&&(ma=+$e[1])));sc.exports=ma});var hn=m((WL,oc)=>{"use strict";var nc=pn(),uS=me(),lS=X(),cS=lS.String;oc.exports=!!Object.getOwnPropertySymbols&&!uS(function(){var i=Symbol();return!cS(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&nc&&nc<41})});var fn=m((QL,uc)=>{"use strict";var dS=hn();uc.exports=dS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var mn=m((zL,lc)=>{"use strict";var pS=We(),hS=G(),fS=Br(),mS=fn(),bS=Object;lc.exports=mS?function(i){return typeof i=="symbol"}:function(i){var e=pS("Symbol");return hS(e)&&fS(e.prototype,bS(i))}});var _r=m((KL,cc)=>{"use strict";var gS=String;cc.exports=function(i){try{return gS(i)}catch(e){return"Object"}}});var Qe=m((JL,dc)=>{"use strict";var vS=G(),SS=_r(),yS=TypeError;dc.exports=function(i){if(vS(i))return i;throw yS(SS(i)+" is not a function")}});var Nr=m((XL,pc)=>{"use strict";var TS=Qe(),IS=ir();pc.exports=function(i,e){var t=i[e];return IS(t)?void 0:TS(t)}});var fc=m((ZL,hc)=>{"use strict";var bn=oe(),gn=G(),vn=qe(),ES=TypeError;hc.exports=function(i,e){var t,r;if(e==="string"&&gn(t=i.toString)&&!vn(r=bn(t,i))||gn(t=i.valueOf)&&!vn(r=bn(t,i))||e!=="string"&&gn(t=i.toString)&&!vn(r=bn(t,i)))return r;throw ES("Can't convert object to primitive value")}});var Ce=m((e$,mc)=>{"use strict";mc.exports=!0});var vc=m((t$,gc)=>{"use strict";var bc=X(),xS=Object.defineProperty;gc.exports=function(i,e){try{xS(bc,i,{value:e,configurable:!0,writable:!0})}catch(t){bc[i]=e}return e}});var ba=m((r$,yc)=>{"use strict";var PS=X(),kS=vc(),Sc="__core-js_shared__",wS=PS[Sc]||kS(Sc,{});yc.exports=wS});var Sn=m((i$,Ic)=>{"use strict";var AS=Ce(),Tc=ba();(Ic.exports=function(i,e){return Tc[i]||(Tc[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:AS?"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 Fr=m((a$,Ec)=>{"use strict";var RS=ca(),LS=Object;Ec.exports=function(i){return LS(RS(i))}});var De=m((s$,xc)=>{"use strict";var $S=ne(),CS=Fr(),DS=$S({}.hasOwnProperty);xc.exports=Object.hasOwn||function(e,t){return DS(CS(e),t)}});var yn=m((n$,Pc)=>{"use strict";var MS=ne(),OS=0,BS=Math.random(),VS=MS(1 .toString);Pc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+VS(++OS+BS,36)}});var te=m((o$,wc)=>{"use strict";var _S=X(),NS=Sn(),kc=De(),FS=yn(),qS=hn(),US=fn(),sr=_S.Symbol,Tn=NS("wks"),HS=US?sr.for||sr:sr&&sr.withoutSetter||FS;wc.exports=function(i){return kc(Tn,i)||(Tn[i]=qS&&kc(sr,i)?sr[i]:HS("Symbol."+i)),Tn[i]}});var $c=m((u$,Lc)=>{"use strict";var jS=oe(),Ac=qe(),Rc=mn(),GS=Nr(),YS=fc(),WS=te(),QS=TypeError,zS=WS("toPrimitive");Lc.exports=function(i,e){if(!Ac(i)||Rc(i))return i;var t=GS(i,zS),r;if(t){if(e===void 0&&(e="default"),r=jS(t,i,e),!Ac(r)||Rc(r))return r;throw QS("Can't convert object to primitive value")}return e===void 0&&(e="number"),YS(i,e)}});var ga=m((l$,Cc)=>{"use strict";var KS=$c(),JS=mn();Cc.exports=function(i){var e=KS(i,"string");return JS(e)?e:e+""}});var Lt=m(Mc=>{"use strict";var XS=Ue(),ZS=on(),ey=un(),va=Le(),Dc=ga(),ty=TypeError,In=Object.defineProperty,ry=Object.getOwnPropertyDescriptor,En="enumerable",xn="configurable",Pn="writable";Mc.f=XS?ey?function(e,t,r){if(va(e),t=Dc(t),va(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Pn in r&&!r[Pn]){var a=ry(e,t);a&&a[Pn]&&(e[t]=r.value,r={configurable:xn in r?r[xn]:a[xn],enumerable:En in r?r[En]:a[En],writable:!1})}return In(e,t,r)}:In:function(e,t,r){if(va(e),t=Dc(t),va(r),ZS)try{return In(e,t,r)}catch(a){}if("get"in r||"set"in r)throw ty("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var qr=m((d$,Oc)=>{"use strict";Oc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var $t=m((p$,Bc)=>{"use strict";var iy=Ue(),ay=Lt(),sy=qr();Bc.exports=iy?function(i,e,t){return ay.f(i,e,sy(1,t))}:function(i,e,t){return i[e]=t,i}});var Sa=m((h$,_c)=>{"use strict";var ny=Sn(),oy=yn(),Vc=ny("keys");_c.exports=function(i){return Vc[i]||(Vc[i]=oy(i))}});var ya=m((f$,Nc)=>{"use strict";Nc.exports={}});var Rn=m((m$,Uc)=>{"use strict";var uy=_l(),qc=X(),ly=qe(),cy=$t(),kn=De(),wn=ba(),dy=Sa(),py=ya(),Fc="Object already initialized",An=qc.TypeError,hy=qc.WeakMap,Ta,Ur,Ia,fy=function(i){return Ia(i)?Ur(i):Ta(i,{})},my=function(i){return function(e){var t;if(!ly(e)||(t=Ur(e)).type!==i)throw An("Incompatible receiver, "+i+" required");return t}};uy||wn.state?(Me=wn.state||(wn.state=new hy),Me.get=Me.get,Me.has=Me.has,Me.set=Me.set,Ta=function(i,e){if(Me.has(i))throw An(Fc);return e.facade=i,Me.set(i,e),e},Ur=function(i){return Me.get(i)||{}},Ia=function(i){return Me.has(i)}):(Ct=dy("state"),py[Ct]=!0,Ta=function(i,e){if(kn(i,Ct))throw An(Fc);return e.facade=i,cy(i,Ct,e),e},Ur=function(i){return kn(i,Ct)?i[Ct]:{}},Ia=function(i){return kn(i,Ct)});var Me,Ct;Uc.exports={set:Ta,get:Ur,has:Ia,enforce:fy,getterFor:my}});var Ln=m((b$,Yc)=>{"use strict";var by=Or(),Gc=Function.prototype,Hc=Gc.apply,jc=Gc.call;Yc.exports=typeof Reflect=="object"&&Reflect.apply||(by?jc.bind(Hc):function(){return jc.apply(Hc,arguments)})});var $n=m((g$,Wc)=>{"use strict";var gy=rr(),vy=ne();Wc.exports=function(i){if(gy(i)==="Function")return vy(i)}});var Jc=m(Kc=>{"use strict";var Qc={}.propertyIsEnumerable,zc=Object.getOwnPropertyDescriptor,Sy=zc&&!Qc.call({1:2},1);Kc.f=Sy?function(e){var t=zc(this,e);return!!t&&t.enumerable}:Qc});var Cn=m(Zc=>{"use strict";var yy=Ue(),Ty=oe(),Iy=Jc(),Ey=qr(),xy=ar(),Py=ga(),ky=De(),wy=on(),Xc=Object.getOwnPropertyDescriptor;Zc.f=yy?Xc:function(e,t){if(e=xy(e),t=Py(t),wy)try{return Xc(e,t)}catch(r){}if(ky(e,t))return Ey(!Ty(Iy.f,e,t),e[t])}});var Dn=m((y$,ed)=>{"use strict";var Ay=me(),Ry=G(),Ly=/#|\.prototype\./,Hr=function(i,e){var t=Cy[$y(i)];return t==My?!0:t==Dy?!1:Ry(e)?Ay(e):!!e},$y=Hr.normalize=function(i){return String(i).replace(Ly,".").toLowerCase()},Cy=Hr.data={},Dy=Hr.NATIVE="N",My=Hr.POLYFILL="P";ed.exports=Hr});var jr=m((T$,rd)=>{"use strict";var td=$n(),Oy=Qe(),By=Or(),Vy=td(td.bind);rd.exports=function(i,e){return Oy(i),e===void 0?i:By?Vy(i,e):function(){return i.apply(e,arguments)}}});var Te=m((I$,ad)=>{"use strict";var Ea=X(),_y=Ln(),Ny=$n(),Fy=G(),qy=Cn().f,Uy=Dn(),nr=fa(),Hy=jr(),or=$t(),id=De(),jy=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 _y(i,this,arguments)};return e.prototype=i.prototype,e};ad.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Ea:a?Ea[t]:(Ea[t]||{}).prototype,o=r?nr:nr[t]||or(nr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,v,S;for(p in e)l=Uy(r?p:t+(a?".":"#")+p,i.forced),c=!l&&n&&id(n,p),f=o[p],c&&(i.dontCallGetSet?(S=qy(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(c&&typeof f==typeof h)&&(i.bind&&c?v=Hy(h,Ea):i.wrap&&c?v=jy(h):s&&Fy(h)?v=Ny(h):v=h,(i.sham||h&&h.sham||f&&f.sham)&&or(v,"sham",!0),or(o,p,v),s&&(d=t+"Prototype",id(nr,d)||or(nr,d,{}),or(nr[d],p,h),i.real&&u&&(l||!u[p])&&or(u,p,h)))}});var od=m((E$,nd)=>{"use strict";var Mn=Ue(),Gy=De(),sd=Function.prototype,Yy=Mn&&Object.getOwnPropertyDescriptor,On=Gy(sd,"name"),Wy=On&&function(){}.name==="something",Qy=On&&(!Mn||Mn&&Yy(sd,"name").configurable);nd.exports={EXISTS:On,PROPER:Wy,CONFIGURABLE:Qy}});var ld=m((x$,ud)=>{"use strict";var zy=Math.ceil,Ky=Math.floor;ud.exports=Math.trunc||function(e){var t=+e;return(t>0?Ky:zy)(t)}});var xa=m((P$,cd)=>{"use strict";var Jy=ld();cd.exports=function(i){var e=+i;return e!==e||e===0?0:Jy(e)}});var pd=m((k$,dd)=>{"use strict";var Xy=xa(),Zy=Math.max,eT=Math.min;dd.exports=function(i,e){var t=Xy(i);return t<0?Zy(t+e,0):eT(t,e)}});var fd=m((w$,hd)=>{"use strict";var tT=xa(),rT=Math.min;hd.exports=function(i){return i>0?rT(tT(i),9007199254740991):0}});var Pa=m((A$,md)=>{"use strict";var iT=fd();md.exports=function(i){return iT(i.length)}});var vd=m((R$,gd)=>{"use strict";var aT=ar(),sT=pd(),nT=Pa(),bd=function(i){return function(e,t,r){var a=aT(e),s=nT(a),n=sT(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}};gd.exports={includes:bd(!0),indexOf:bd(!1)}});var Td=m((L$,yd)=>{"use strict";var oT=ne(),Bn=De(),uT=ar(),lT=vd().indexOf,cT=ya(),Sd=oT([].push);yd.exports=function(i,e){var t=uT(i),r=0,a=[],s;for(s in t)!Bn(cT,s)&&Bn(t,s)&&Sd(a,s);for(;e.length>r;)Bn(t,s=e[r++])&&(~lT(a,s)||Sd(a,s));return a}});var Vn=m(($$,Id)=>{"use strict";Id.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var xd=m((C$,Ed)=>{"use strict";var dT=Td(),pT=Vn();Ed.exports=Object.keys||function(e){return dT(e,pT)}});var kd=m(Pd=>{"use strict";var hT=Ue(),fT=un(),mT=Lt(),bT=Le(),gT=ar(),vT=xd();Pd.f=hT&&!fT?Object.defineProperties:function(e,t){bT(e);for(var r=gT(t),a=vT(t),s=a.length,n=0,o;s>n;)mT.f(e,o=a[n++],r[o]);return e}});var _n=m((M$,wd)=>{"use strict";var ST=We();wd.exports=ST("document","documentElement")});var Un=m((O$,Md)=>{"use strict";var yT=Le(),TT=kd(),Ad=Vn(),IT=ya(),ET=_n(),xT=pa(),PT=Sa(),Rd=">",Ld="<",Fn="prototype",qn="script",Cd=PT("IE_PROTO"),Nn=function(){},Dd=function(i){return Ld+qn+Rd+i+Ld+"/"+qn+Rd},$d=function(i){i.write(Dd("")),i.close();var e=i.parentWindow.Object;return i=null,e},kT=function(){var i=xT("iframe"),e="java"+qn+":",t;return i.style.display="none",ET.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Dd("document.F=Object")),t.close(),t.F},ka,wa=function(){try{ka=new ActiveXObject("htmlfile")}catch(e){}wa=typeof document!="undefined"?document.domain&&ka?$d(ka):kT():$d(ka);for(var i=Ad.length;i--;)delete wa[Fn][Ad[i]];return wa()};IT[Cd]=!0;Md.exports=Object.create||function(e,t){var r;return e!==null?(Nn[Fn]=yT(e),r=new Nn,Nn[Fn]=null,r[Cd]=e):r=wa(),t===void 0?r:TT.f(r,t)}});var Bd=m((B$,Od)=>{"use strict";var wT=me();Od.exports=!wT(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var jn=m((V$,_d)=>{"use strict";var AT=De(),RT=G(),LT=Fr(),$T=Sa(),CT=Bd(),Vd=$T("IE_PROTO"),Hn=Object,DT=Hn.prototype;_d.exports=CT?Hn.getPrototypeOf:function(i){var e=LT(i);if(AT(e,Vd))return e[Vd];var t=e.constructor;return RT(t)&&e instanceof t?t.prototype:e instanceof Hn?DT:null}});var ur=m((_$,Nd)=>{"use strict";var MT=$t();Nd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:MT(i,e,t),i}});var Qn=m((N$,Ud)=>{"use strict";var OT=me(),BT=G(),VT=qe(),_T=Un(),Fd=jn(),NT=ur(),FT=te(),qT=Ce(),Wn=FT("iterator"),qd=!1,ze,Gn,Yn;[].keys&&(Yn=[].keys(),"next"in Yn?(Gn=Fd(Fd(Yn)),Gn!==Object.prototype&&(ze=Gn)):qd=!0);var UT=!VT(ze)||OT(function(){var i={};return ze[Wn].call(i)!==i});UT?ze={}:qT&&(ze=_T(ze));BT(ze[Wn])||NT(ze,Wn,function(){return this});Ud.exports={IteratorPrototype:ze,BUGGY_SAFARI_ITERATORS:qd}});var Aa=m((F$,jd)=>{"use strict";var HT=te(),jT=HT("toStringTag"),Hd={};Hd[jT]="z";jd.exports=String(Hd)==="[object z]"});var lr=m((q$,Gd)=>{"use strict";var GT=Aa(),YT=G(),Ra=rr(),WT=te(),QT=WT("toStringTag"),zT=Object,KT=Ra(function(){return arguments}())=="Arguments",JT=function(i,e){try{return i[e]}catch(t){}};Gd.exports=GT?Ra:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=JT(e=zT(i),QT))=="string"?t:KT?Ra(e):(r=Ra(e))=="Object"&&YT(e.callee)?"Arguments":r}});var Wd=m((U$,Yd)=>{"use strict";var XT=Aa(),ZT=lr();Yd.exports=XT?{}.toString:function(){return"[object "+ZT(this)+"]"}});var La=m((H$,zd)=>{"use strict";var eI=Aa(),tI=Lt().f,rI=$t(),iI=De(),aI=Wd(),sI=te(),Qd=sI("toStringTag");zd.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;iI(a,Qd)||tI(a,Qd,{configurable:!0,value:e}),r&&!eI&&rI(a,"toString",aI)}}});var Jd=m((j$,Kd)=>{"use strict";var nI=Qn().IteratorPrototype,oI=Un(),uI=qr(),lI=La(),cI=Rt(),dI=function(){return this};Kd.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=oI(nI,{next:uI(+!r,t)}),lI(i,a,!1,!0),cI[a]=dI,i}});var Zd=m((G$,Xd)=>{"use strict";var pI=ne(),hI=Qe();Xd.exports=function(i,e,t){try{return pI(hI(Object.getOwnPropertyDescriptor(i,e)[t]))}catch(r){}}});var tp=m((Y$,ep)=>{"use strict";var fI=G(),mI=String,bI=TypeError;ep.exports=function(i){if(typeof i=="object"||fI(i))return i;throw bI("Can't set "+mI(i)+" as a prototype")}});var zn=m((W$,rp)=>{"use strict";var gI=Zd(),vI=Le(),SI=tp();rp.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=gI(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch(r){}return function(a,s){return vI(a),SI(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var hp=m((Q$,pp)=>{"use strict";var yI=Te(),TI=oe(),$a=Ce(),cp=od(),II=G(),EI=Jd(),ip=jn(),ap=zn(),xI=La(),PI=$t(),Kn=ur(),kI=te(),sp=Rt(),dp=Qn(),wI=cp.PROPER,AI=cp.CONFIGURABLE,np=dp.IteratorPrototype,Ca=dp.BUGGY_SAFARI_ITERATORS,Gr=kI("iterator"),op="keys",Yr="values",up="entries",lp=function(){return this};pp.exports=function(i,e,t,r,a,s,n){EI(t,e,r);var o=function(S){if(S===a&&p)return p;if(!Ca&&S in c)return c[S];switch(S){case op:return function(){return new t(this,S)};case Yr:return function(){return new t(this,S)};case up:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[Gr]||c["@@iterator"]||a&&c[a],p=!Ca&&d||o(a),h=e=="Array"&&c.entries||d,f,b,v;if(h&&(f=ip(h.call(new i)),f!==Object.prototype&&f.next&&(!$a&&ip(f)!==np&&(ap?ap(f,np):II(f[Gr])||Kn(f,Gr,lp)),xI(f,u,!0,!0),$a&&(sp[u]=lp))),wI&&a==Yr&&d&&d.name!==Yr&&(!$a&&AI?PI(c,"name",Yr):(l=!0,p=function(){return TI(d,this)})),a)if(b={values:o(Yr),keys:s?p:o(op),entries:o(up)},n)for(v in b)(Ca||l||!(v in c))&&Kn(c,v,b[v]);else yI({target:e,proto:!0,forced:Ca||l},b);return(!$a||n)&&c[Gr]!==p&&Kn(c,Gr,p,{name:a}),sp[e]=p,b}});var mp=m((z$,fp)=>{"use strict";fp.exports=function(i,e){return{value:i,done:e}}});var Xn=m((K$,yp)=>{"use strict";var RI=ar(),Jn=rn(),bp=Rt(),vp=Rn(),LI=Lt().f,$I=hp(),Da=mp(),CI=Ce(),DI=Ue(),Sp="Array Iterator",MI=vp.set,OI=vp.getterFor(Sp);yp.exports=$I(Array,"Array",function(i,e){MI(this,{type:Sp,target:RI(i),index:0,kind:e})},function(){var i=OI(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Da(void 0,!0)):t=="keys"?Da(r,!1):t=="values"?Da(e[r],!1):Da([r,e[r]],!1)},"values");var gp=bp.Arguments=bp.Array;Jn("keys");Jn("values");Jn("entries");if(!CI&&DI&&gp.name!=="values")try{LI(gp,"name",{value:"values"})}catch(i){}});var Ip=m((J$,Tp)=>{"use strict";var BI=te(),VI=Rt(),_I=BI("iterator"),NI=Array.prototype;Tp.exports=function(i){return i!==void 0&&(VI.Array===i||NI[_I]===i)}});var Zn=m((X$,xp)=>{"use strict";var FI=lr(),Ep=Nr(),qI=ir(),UI=Rt(),HI=te(),jI=HI("iterator");xp.exports=function(i){if(!qI(i))return Ep(i,jI)||Ep(i,"@@iterator")||UI[FI(i)]}});var kp=m((Z$,Pp)=>{"use strict";var GI=oe(),YI=Qe(),WI=Le(),QI=_r(),zI=Zn(),KI=TypeError;Pp.exports=function(i,e){var t=arguments.length<2?zI(i):e;if(YI(t))return WI(GI(t,i));throw KI(QI(i)+" is not iterable")}});var Rp=m((eC,Ap)=>{"use strict";var JI=oe(),wp=Le(),XI=Nr();Ap.exports=function(i,e,t){var r,a;wp(i);try{if(r=XI(i,"return"),!r){if(e==="throw")throw t;return t}r=JI(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return wp(r),t}});var Oa=m((tC,Dp)=>{"use strict";var ZI=jr(),eE=oe(),tE=Le(),rE=_r(),iE=Ip(),aE=Pa(),Lp=Br(),sE=kp(),nE=Zn(),$p=Rp(),oE=TypeError,Ma=function(i,e){this.stopped=i,this.result=e},Cp=Ma.prototype;Dp.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=ZI(e,r),l,c,d,p,h,f,b,v=function(g){return l&&$p(l,"normal",g),new Ma(!0,g)},S=function(g){return a?(tE(g),o?u(g[0],g[1],v):u(g[0],g[1])):o?u(g,v):u(g)};if(s)l=i.iterator;else if(n)l=i;else{if(c=nE(i),!c)throw oE(rE(i)+" is not iterable");if(iE(c)){for(d=0,p=aE(i);p>d;d++)if(h=S(i[d]),h&&Lp(Cp,h))return h;return new Ma(!1)}l=sE(i,c)}for(f=s?i.next:l.next;!(b=eE(f,l)).done;){try{h=S(b.value)}catch(g){$p(l,"throw",g)}if(typeof h=="object"&&h&&Lp(Cp,h))return h}return new Ma(!1)}});var Op=m((rC,Mp)=>{"use strict";var uE=ga(),lE=Lt(),cE=qr();Mp.exports=function(i,e,t){var r=uE(e);r in i?lE.f(i,r,cE(0,t)):i[r]=t}});var Bp=m(()=>{"use strict";var dE=Te(),pE=Oa(),hE=Op();dE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return pE(e,function(r,a){hE(t,r,a)},{AS_ENTRIES:!0}),t}})});var _p=m((sC,Vp)=>{"use strict";Xn();Bp();var fE=fa();Vp.exports=fE.Object.fromEntries});var Fp=m((nC,Np)=>{"use strict";Np.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 Hp=m(()=>{"use strict";Xn();var mE=Fp(),bE=X(),gE=lr(),vE=$t(),qp=Rt(),SE=te(),Up=SE("toStringTag");for(Ba in mE)eo=bE[Ba],Va=eo&&eo.prototype,Va&&gE(Va)!==Up&&vE(Va,Up,Ba),qp[Ba]=qp.Array;var eo,Va,Ba});var Gp=m((lC,jp)=>{"use strict";var yE=_p();Hp();jp.exports=yE});var _a=m((cC,Yp)=>{"use strict";var TE=Gp();Yp.exports=TE});var Wp=m(()=>{"use strict"});var Wr=m((hC,Qp)=>{"use strict";var IE=rr();Qp.exports=typeof process!="undefined"&&IE(process)=="process"});var Kp=m((fC,zp)=>{"use strict";var EE=Lt();zp.exports=function(i,e,t){return EE.f(i,e,t)}});var Zp=m((mC,Xp)=>{"use strict";var xE=We(),PE=Kp(),kE=te(),wE=Ue(),Jp=kE("species");Xp.exports=function(i){var e=xE(i);wE&&e&&!e[Jp]&&PE(e,Jp,{configurable:!0,get:function(){return this}})}});var th=m((bC,eh)=>{"use strict";var AE=Br(),RE=TypeError;eh.exports=function(i,e){if(AE(e,i))return i;throw RE("Incorrect invocation")}});var ro=m((gC,rh)=>{"use strict";var LE=ne(),$E=G(),to=ba(),CE=LE(Function.toString);$E(to.inspectSource)||(to.inspectSource=function(i){return CE(i)});rh.exports=to.inspectSource});var uh=m((vC,oh)=>{"use strict";var DE=ne(),ME=me(),ih=G(),OE=lr(),BE=We(),VE=ro(),ah=function(){},_E=[],sh=BE("Reflect","construct"),io=/^\s*(?:class|function)\b/,NE=DE(io.exec),FE=!io.exec(ah),Qr=function(e){if(!ih(e))return!1;try{return sh(ah,_E,e),!0}catch(t){return!1}},nh=function(e){if(!ih(e))return!1;switch(OE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return FE||!!NE(io,VE(e))}catch(t){return!0}};nh.sham=!0;oh.exports=!sh||ME(function(){var i;return Qr(Qr.call)||!Qr(Object)||!Qr(function(){i=!0})||i})?nh:Qr});var ch=m((SC,lh)=>{"use strict";var qE=uh(),UE=_r(),HE=TypeError;lh.exports=function(i){if(qE(i))return i;throw HE(UE(i)+" is not a constructor")}});var ao=m((yC,ph)=>{"use strict";var dh=Le(),jE=ch(),GE=ir(),YE=te(),WE=YE("species");ph.exports=function(i,e){var t=dh(i).constructor,r;return t===void 0||GE(r=dh(t)[WE])?e:jE(r)}});var fh=m((TC,hh)=>{"use strict";var QE=ne();hh.exports=QE([].slice)});var bh=m((IC,mh)=>{"use strict";var zE=TypeError;mh.exports=function(i,e){if(i<e)throw zE("Not enough arguments");return i}});var so=m((EC,gh)=>{"use strict";var KE=Vr();gh.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(KE)});var mo=m((xC,kh)=>{"use strict";var be=X(),JE=Ln(),XE=jr(),vh=G(),ZE=De(),Ph=me(),Sh=_n(),ex=fh(),yh=pa(),tx=bh(),rx=so(),ix=Wr(),po=be.setImmediate,ho=be.clearImmediate,ax=be.process,no=be.Dispatch,sx=be.Function,Th=be.MessageChannel,nx=be.String,oo=0,zr={},Ih="onreadystatechange",Kr,Dt,uo,lo;Ph(function(){Kr=be.location});var fo=function(i){if(ZE(zr,i)){var e=zr[i];delete zr[i],e()}},co=function(i){return function(){fo(i)}},Eh=function(i){fo(i.data)},xh=function(i){be.postMessage(nx(i),Kr.protocol+"//"+Kr.host)};(!po||!ho)&&(po=function(e){tx(arguments.length,1);var t=vh(e)?e:sx(e),r=ex(arguments,1);return zr[++oo]=function(){JE(t,void 0,r)},Dt(oo),oo},ho=function(e){delete zr[e]},ix?Dt=function(i){ax.nextTick(co(i))}:no&&no.now?Dt=function(i){no.now(co(i))}:Th&&!rx?(uo=new Th,lo=uo.port2,uo.port1.onmessage=Eh,Dt=XE(lo.postMessage,lo)):be.addEventListener&&vh(be.postMessage)&&!be.importScripts&&Kr&&Kr.protocol!=="file:"&&!Ph(xh)?(Dt=xh,be.addEventListener("message",Eh,!1)):Ih in yh("script")?Dt=function(i){Sh.appendChild(yh("script"))[Ih]=function(){Sh.removeChild(this),fo(i)}}:Dt=function(i){setTimeout(co(i),0)});kh.exports={set:po,clear:ho}});var bo=m((PC,Ah)=>{"use strict";var wh=function(){this.head=null,this.tail=null};wh.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}}};Ah.exports=wh});var Lh=m((kC,Rh)=>{"use strict";var ox=Vr();Rh.exports=/ipad|iphone|ipod/i.test(ox)&&typeof Pebble!="undefined"});var Ch=m((wC,$h)=>{"use strict";var ux=Vr();$h.exports=/web0s(?!.*chrome)/i.test(ux)});var Fh=m((AC,Nh)=>{"use strict";var Mt=X(),Dh=jr(),lx=Cn().f,go=mo().set,cx=bo(),dx=so(),px=Lh(),hx=Ch(),vo=Wr(),Mh=Mt.MutationObserver||Mt.WebKitMutationObserver,Oh=Mt.document,Bh=Mt.process,Na=Mt.Promise,Vh=lx(Mt,"queueMicrotask"),To=Vh&&Vh.value,cr,So,yo,Fa,_h;To||(Jr=new cx,Xr=function(){var i,e;for(vo&&(i=Bh.domain)&&i.exit();e=Jr.get();)try{e()}catch(t){throw Jr.head&&cr(),t}i&&i.enter()},!dx&&!vo&&!hx&&Mh&&Oh?(So=!0,yo=Oh.createTextNode(""),new Mh(Xr).observe(yo,{characterData:!0}),cr=function(){yo.data=So=!So}):!px&&Na&&Na.resolve?(Fa=Na.resolve(void 0),Fa.constructor=Na,_h=Dh(Fa.then,Fa),cr=function(){_h(Xr)}):vo?cr=function(){Bh.nextTick(Xr)}:(go=Dh(go,Mt),cr=function(){go(Xr)}),To=function(i){Jr.head||cr(),Jr.add(i)});var Jr,Xr;Nh.exports=To});var Uh=m((RC,qh)=>{"use strict";qh.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}}});var qa=m((LC,Hh)=>{"use strict";Hh.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Ot=m(($C,jh)=>{"use strict";var fx=X();jh.exports=fx.Promise});var Io=m((CC,Gh)=>{"use strict";Gh.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var Wh=m((DC,Yh)=>{"use strict";var mx=Io(),bx=Wr();Yh.exports=!mx&&!bx&&typeof window=="object"&&typeof document=="object"});var dr=m((MC,Kh)=>{"use strict";var gx=X(),Zr=Ot(),vx=G(),Sx=Dn(),yx=ro(),Tx=te(),Ix=Wh(),Ex=Io(),xx=Ce(),Eo=pn(),Qh=Zr&&Zr.prototype,Px=Tx("species"),xo=!1,zh=vx(gx.PromiseRejectionEvent),kx=Sx("Promise",function(){var i=yx(Zr),e=i!==String(Zr);if(!e&&Eo===66||xx&&!(Qh.catch&&Qh.finally))return!0;if(!Eo||Eo<51||!/native code/.test(i)){var t=new Zr(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Px]=r,xo=t.then(function(){})instanceof r,!xo)return!0}return!e&&(Ix||Ex)&&!zh});Kh.exports={CONSTRUCTOR:kx,REJECTION_EVENT:zh,SUBCLASSING:xo}});var pr=m((OC,Xh)=>{"use strict";var Jh=Qe(),wx=TypeError,Ax=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw wx("Bad Promise constructor");e=r,t=a}),this.resolve=Jh(e),this.reject=Jh(t)};Xh.exports.f=function(i){return new Ax(i)}});var vf=m(()=>{"use strict";var Rx=Te(),Lx=Ce(),Ga=Wr(),ct=X(),br=oe(),Zh=ur(),ef=zn(),$x=La(),Cx=Zp(),Dx=Qe(),ja=G(),Mx=qe(),Ox=th(),Bx=ao(),nf=mo().set,Ro=Fh(),Vx=Uh(),_x=qa(),Nx=bo(),of=Rn(),Ya=Ot(),Lo=dr(),uf=pr(),Wa="Promise",lf=Lo.CONSTRUCTOR,Fx=Lo.REJECTION_EVENT,qx=Lo.SUBCLASSING,Po=of.getterFor(Wa),Ux=of.set,hr=Ya&&Ya.prototype,Bt=Ya,Ua=hr,cf=ct.TypeError,ko=ct.document,$o=ct.process,wo=uf.f,Hx=wo,jx=!!(ko&&ko.createEvent&&ct.dispatchEvent),df="unhandledrejection",Gx="rejectionhandled",tf=0,pf=1,Yx=2,Co=1,hf=2,Ha,rf,Wx,af,ff=function(i){var e;return Mx(i)&&ja(e=i.then)?e:!1},mf=function(i,e){var t=e.value,r=e.state==pf,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===hf&&zx(e),e.rejection=Co),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(cf("Promise-chain cycle")):(l=ff(u))?br(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},bf=function(i,e){i.notified||(i.notified=!0,Ro(function(){for(var t=i.reactions,r;r=t.get();)mf(r,i);i.notified=!1,e&&!i.rejection&&Qx(i)}))},gf=function(i,e,t){var r,a;jx?(r=ko.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),ct.dispatchEvent(r)):r={promise:e,reason:t},!Fx&&(a=ct["on"+i])?a(r):i===df&&Vx("Unhandled promise rejection",t)},Qx=function(i){br(nf,ct,function(){var e=i.facade,t=i.value,r=sf(i),a;if(r&&(a=_x(function(){Ga?$o.emit("unhandledRejection",t,e):gf(df,e,t)}),i.rejection=Ga||sf(i)?hf:Co,a.error))throw a.value})},sf=function(i){return i.rejection!==Co&&!i.parent},zx=function(i){br(nf,ct,function(){var e=i.facade;Ga?$o.emit("rejectionHandled",e):gf(Gx,e,i.value)})},fr=function(i,e,t){return function(r){i(e,r,t)}},mr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Yx,bf(i,!0))},Ao=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw cf("Promise can't be resolved itself");var r=ff(e);r?Ro(function(){var a={done:!1};try{br(r,e,fr(Ao,a,i),fr(mr,a,i))}catch(s){mr(a,s,i)}}):(i.value=e,i.state=pf,bf(i,!1))}catch(a){mr({done:!1},a,i)}}};if(lf&&(Bt=function(e){Ox(this,Ua),Dx(e),br(Ha,this);var t=Po(this);try{e(fr(Ao,t),fr(mr,t))}catch(r){mr(t,r)}},Ua=Bt.prototype,Ha=function(e){Ux(this,{type:Wa,done:!1,notified:!1,parent:!1,reactions:new Nx,rejection:!1,state:tf,value:void 0})},Ha.prototype=Zh(Ua,"then",function(e,t){var r=Po(this),a=wo(Bx(this,Bt));return r.parent=!0,a.ok=ja(e)?e:!0,a.fail=ja(t)&&t,a.domain=Ga?$o.domain:void 0,r.state==tf?r.reactions.add(a):Ro(function(){mf(a,r)}),a.promise}),rf=function(){var i=new Ha,e=Po(i);this.promise=i,this.resolve=fr(Ao,e),this.reject=fr(mr,e)},uf.f=wo=function(i){return i===Bt||i===Wx?new rf(i):Hx(i)},!Lx&&ja(Ya)&&hr!==Object.prototype)){af=hr.then,qx||Zh(hr,"then",function(e,t){var r=this;return new Bt(function(a,s){br(af,r,a,s)}).then(e,t)},{unsafe:!0});try{delete hr.constructor}catch(i){}ef&&ef(hr,Ua)}Rx({global:!0,constructor:!0,wrap:!0,forced:lf},{Promise:Bt});$x(Bt,Wa,!1,!0);Cx(Wa)});var Ef=m((_C,If)=>{"use strict";var Kx=te(),yf=Kx("iterator"),Tf=!1;try{Sf=0,Do={next:function(){return{done:!!Sf++}},return:function(){Tf=!0}},Do[yf]=function(){return this},Array.from(Do,function(){throw 2})}catch(i){}var Sf,Do;If.exports=function(i,e){if(!e&&!Tf)return!1;var t=!1;try{var r={};r[yf]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(a){}return t}});var Mo=m((NC,xf)=>{"use strict";var Jx=Ot(),Xx=Ef(),Zx=dr().CONSTRUCTOR;xf.exports=Zx||!Xx(function(i){Jx.all(i).then(void 0,function(){})})});var Pf=m(()=>{"use strict";var eP=Te(),tP=oe(),rP=Qe(),iP=pr(),aP=qa(),sP=Oa(),nP=Mo();eP({target:"Promise",stat:!0,forced:nP},{all:function(e){var t=this,r=iP.f(t),a=r.resolve,s=r.reject,n=aP(function(){var o=rP(t.resolve),u=[],l=0,c=1;sP(e,function(d){var p=l++,h=!1;c++,tP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var wf=m(()=>{"use strict";var oP=Te(),uP=Ce(),lP=dr().CONSTRUCTOR,Bo=Ot(),cP=We(),dP=G(),pP=ur(),kf=Bo&&Bo.prototype;oP({target:"Promise",proto:!0,forced:lP,real:!0},{catch:function(i){return this.then(void 0,i)}});!uP&&dP(Bo)&&(Oo=cP("Promise").prototype.catch,kf.catch!==Oo&&pP(kf,"catch",Oo,{unsafe:!0}));var Oo});var Af=m(()=>{"use strict";var hP=Te(),fP=oe(),mP=Qe(),bP=pr(),gP=qa(),vP=Oa(),SP=Mo();hP({target:"Promise",stat:!0,forced:SP},{race:function(e){var t=this,r=bP.f(t),a=r.reject,s=gP(function(){var n=mP(t.resolve);vP(e,function(o){fP(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Rf=m(()=>{"use strict";var yP=Te(),TP=oe(),IP=pr(),EP=dr().CONSTRUCTOR;yP({target:"Promise",stat:!0,forced:EP},{reject:function(e){var t=IP.f(this);return TP(t.reject,void 0,e),t.promise}})});var Vo=m((QC,Lf)=>{"use strict";var xP=Le(),PP=qe(),kP=pr();Lf.exports=function(i,e){if(xP(i),PP(e)&&e.constructor===i)return e;var t=kP.f(i),r=t.resolve;return r(e),t.promise}});var Df=m(()=>{"use strict";var wP=Te(),AP=We(),$f=Ce(),RP=Ot(),Cf=dr().CONSTRUCTOR,LP=Vo(),$P=AP("Promise"),CP=$f&&!Cf;wP({target:"Promise",stat:!0,forced:$f||Cf},{resolve:function(e){return LP(CP&&this===$P?RP:this,e)}})});var Mf=m(()=>{"use strict";vf();Pf();wf();Af();Rf();Df()});var _f=m(()=>{"use strict";var DP=Te(),MP=Ce(),Qa=Ot(),OP=me(),Bf=We(),Vf=G(),BP=ao(),Of=Vo(),VP=ur(),No=Qa&&Qa.prototype,_P=!!Qa&&OP(function(){No.finally.call({then:function(){}},function(){})});DP({target:"Promise",proto:!0,real:!0,forced:_P},{finally:function(i){var e=BP(this,Bf("Promise")),t=Vf(i);return this.then(t?function(r){return Of(e,i()).then(function(){return r})}:i,t?function(r){return Of(e,i()).then(function(){throw r})}:i)}});!MP&&Vf(Qa)&&(_o=Bf("Promise").prototype.finally,No.finally!==_o&&VP(No,"finally",_o,{unsafe:!0}));var _o});var za=m((tD,Nf)=>{"use strict";var NP=We();Nf.exports=NP});var qf=m((rD,Ff)=>{"use strict";Wp();Mf();_f();var FP=za();Ff.exports=FP("Promise","finally")});var Hf=m((iD,Uf)=>{"use strict";var qP=qf();Uf.exports=qP});var Ka=m((aD,jf)=>{"use strict";var UP=Hf();jf.exports=UP});var fm=m(()=>{"use strict";var fk=Te(),mk=Fr(),bk=Pa(),gk=xa(),vk=rn();fk({target:"Array",proto:!0},{at:function(e){var t=mk(this),r=bk(t),a=gk(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});vk("at")});var bm=m((hM,mm)=>{"use strict";fm();var Sk=za();mm.exports=Sk("Array","at")});var vm=m((fM,gm)=>{"use strict";var yk=bm();gm.exports=yk});var Za=m((mM,Sm)=>{"use strict";var Tk=vm();Sm.exports=Tk});var Jm=m(()=>{"use strict"});var Xm=m(()=>{"use strict"});var eb=m((oV,Zm)=>{"use strict";var kw=qe(),ww=rr(),Aw=te(),Rw=Aw("match");Zm.exports=function(i){var e;return kw(i)&&((e=i[Rw])!==void 0?!!e:ww(i)=="RegExp")}});var rb=m((uV,tb)=>{"use strict";var Lw=lr(),$w=String;tb.exports=function(i){if(Lw(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return $w(i)}});var ab=m((lV,ib)=>{"use strict";var Cw=Le();ib.exports=function(){var i=Cw(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 ob=m((cV,nb)=>{"use strict";var Dw=oe(),Mw=De(),Ow=Br(),Bw=ab(),sb=RegExp.prototype;nb.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in sb)&&!Mw(i,"flags")&&Ow(sb,i)?Dw(Bw,i):e}});var lb=m((dV,ub)=>{"use strict";var pu=ne(),Vw=Fr(),_w=Math.floor,cu=pu("".charAt),Nw=pu("".replace),du=pu("".slice),Fw=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qw=/\$([$&'`]|\d{1,2})/g;ub.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=qw;return a!==void 0&&(a=Vw(a),u=Fw),Nw(s,u,function(l,c){var d;switch(cu(c,0)){case"$":return"$";case"&":return i;case"`":return du(e,0,t);case"'":return du(e,n);case"<":d=a[du(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=_w(p/10);return h===0?l:h<=o?r[h-1]===void 0?cu(c,1):r[h-1]+cu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var fb=m(()=>{"use strict";var Uw=Te(),Hw=oe(),hu=ne(),cb=ca(),jw=G(),Gw=ir(),Yw=eb(),Er=rb(),Ww=Nr(),Qw=ob(),zw=lb(),Kw=te(),Jw=Ce(),Xw=Kw("replace"),Zw=TypeError,hb=hu("".indexOf),eA=hu("".replace),db=hu("".slice),tA=Math.max,pb=function(i,e,t){return t>i.length?-1:e===""?t:hb(i,e,t)};Uw({target:"String",proto:!0},{replaceAll:function(e,t){var r=cb(this),a,s,n,o,u,l,c,d,p,h=0,f=0,b="";if(!Gw(e)){if(a=Yw(e),a&&(s=Er(cb(Qw(e))),!~hb(s,"g")))throw Zw("`.replaceAll` does not allow non-global regexes");if(n=Ww(e,Xw),n)return Hw(n,e,r,t);if(Jw&&a)return eA(Er(r),e,t)}for(o=Er(r),u=Er(e),l=jw(t),l||(t=Er(t)),c=u.length,d=tA(1,c),h=pb(o,u,0);h!==-1;)p=l?Er(t(u,h,o)):zw(u,o,h,[],void 0,t),b+=db(o,f,h)+p,f=h+c,h=pb(o,u,h+d);return f<o.length&&(b+=db(o,f)),b}})});var bb=m((fV,mb)=>{"use strict";Jm();Xm();fb();var rA=za();mb.exports=rA("String","replaceAll")});var vb=m((mV,gb)=>{"use strict";var iA=bb();gb.exports=iA});var yb=m((bV,Sb)=>{"use strict";var aA=vb();Sb.exports=aA});var cl="__VERSION__";var fe=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(fe||{}),At=(g=>(g.MPEG="MPEG",g.DASH="DASH_SEP",g.DASH_SEP="DASH_SEP",g.DASH_SEP_VK="DASH_SEP",g.DASH_WEBM="DASH_WEBM",g.DASH_WEBM_AV1="DASH_WEBM_AV1",g.DASH_WEBM_VK="DASH_WEBM",g.DASH_ONDEMAND="DASH_ONDEMAND",g.DASH_ONDEMAND_VK="DASH_ONDEMAND",g.DASH_LIVE="DASH_LIVE",g.DASH_LIVE_CMAF="DASH_LIVE_CMAF",g.DASH_LIVE_WEBM="DASH_LIVE_WEBM",g.HLS="HLS",g.HLS_ONDEMAND="HLS_ONDEMAND",g.HLS_JS="HLS",g.HLS_LIVE="HLS_LIVE",g.HLS_LIVE_CMAF="HLS_LIVE_CMAF",g.WEB_RTC_LIVE="WEB_RTC_LIVE",g))(At||{});var oa=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(oa||{}),Ks=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Ks||{});var Js=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Js||{});import{assertNever as bl,assertNonNullable as xv,isNonNullable as ua,ValueSubject as Xs,Subject as Pv,Subscription as kv,merge as wv,observableFrom as Av,fromEvent as pl,map as hl,tap as fl,filterChanged as Rv,isNullable as Zs,ErrorCategory as ml}from"@vkontakte/videoplayer-shared";var dl=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 la=class{constructor(e){this.connection$=new Xs(void 0);this.castState$=new Xs("NOT_AVAILABLE");this.errorEvent$=new Pv;this.realCastState$=new Xs("NOT_AVAILABLE");this.subscription=new kv;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=ua((s=window.chrome)==null?void 0:s.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||dl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ml.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(){ua(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Zs(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Zs(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(pl(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 bl(a.sessionState)}})).add(wv(pl(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(fl(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),hl(a=>a.castState)),Av([r.getCastState()])).pipe(Rv(),hl(Lv),fl(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var o;let s=a==="CONNECTED",n=ua(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();xv(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(Zs(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?ua(this.connection$.getValue())?"CONNECTED":"AVAILABLE":a)}))}initializeCastApi(){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:ml.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Lv=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 bl(i)}};var Vg=Fe(_a(),1);var em=Fe(Ka(),1);import{assertNever as Gf}from"@vkontakte/videoplayer-shared";var re=(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:Gf(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:Gf(e)}};var E=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as HP,Subject as Ja,merge as Yf}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.transitionStarted$=new Ja;this.transitionEnded$=new Ja;this.transitionUpdated$=new Ja;this.forceChanged$=new Ja;this.stateChangeStarted$=Yf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Yf(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||HP(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 jP}from"@vkontakte/videoplayer-shared";var Wf=i=>{switch(i){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 jP(i)}};import{assertNever as gr,assertNonNullable as Vt,debounce as Qf,ErrorCategory as zf,fromEvent as _t,isNonNullable as Kf,map as Jf,merge as Xf,observableFrom as GP,Subject as YP,Subscription as qo,timeout as WP,getHighestQuality as QP}from"@vkontakte/videoplayer-shared";var zP=5,KP=5,JP=500,Zf=7e3,ei=class{constructor(e){this.subscription=new qo;this.loadMediaTimeoutSubscription=new qo;this.videoState=new C("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:gr(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:gr(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:gr(e)}break}default:gr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Wf(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(Xf(this.videoState.stateChangeStarted$.pipe(Jf(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(Jf(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 YP;e.add(a.pipe(Qf(JP)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(_t(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)>zP)&&a.next(o),s=o})),e.add(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<KP&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(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:gr(n)}}),t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=Xf(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,GP(["init"])).pipe(Qf(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"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(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"),E(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"),E(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"&&E(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 l;let t=this.params.source,r,a,s;switch(e){case"MPEG":{let c=t[e];Vt(c);let d=QP(Object.keys(c));Vt(d);let p=c[d];Vt(p),r=p,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Vt(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":{let c=t[e];Vt(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Vt(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];Vt(c),r=re(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:zf.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return gr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Kf(o)&&(n.metadata.title=o),Kf(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(WP(Zf).subscribe(()=>s(`timeout(${Zf})`)))});(0,em.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:zf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ti=i=>{i.removeAttribute("src"),i.load()};var tm=i=>{try{i.pause(),i.playbackRate=0,ti(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,ue=i=>{let e=i.querySelector("video"),t=!!e;return e?ti(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},le=i=>{let e=Ho.get(i);Ho.delete(i),e?ti(i):tm(i)};import{assertNonNullable as ri,isNonNullable as je,isNullable as ek,fromEvent as vr,merge as rm,observableFrom as im,filterChanged as am,map as ii,Subject as sm,Subscription as tk,ValueSubject as rk,ErrorCategory as ik}from"@vkontakte/videoplayer-shared";import{isNonNullable as jo,isNullable as XP,Subscription as ZP}from"@vkontakte/videoplayer-shared";var Xa=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=XP(a),l=new ZP;return a&&l.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},s)),l},He=(i,e,t)=>Xa(e,()=>i.loop,r=>{jo(r)&&(i.loop=r)},{onError:t}),ce=(i,e,t,r)=>Xa(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}),Ie=(i,e,t,r)=>Xa(e,()=>i.playbackRate,a=>{jo(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),dt=Xa;var ak=i=>["__",i.language,i.label].join("|"),sk=(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 sm;this.current$=new rk(void 0);this.error$=new sm;this.subscription=new tk;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:ik.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(dt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{je(s)&&this.setInternal(s)},{equal:(s,n)=>je(s)&&je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ii(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(dt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{je(s)&&this.setExternal(s)},{equal:(s,n)=>je(s)&&je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ii(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(dt(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(dt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ri(this.video);let{textTracks:e}=this.video;this.subscription.add(vr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(rm(vr(e,"addtrack"),vr(e,"removetrack"),im(["init"])).pipe(ii(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),am((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(rm(vr(e,"change"),im(["init"])).pipe(ii(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),ii(r=>r&&this.htmlTextTrackToITextTrack(r).id),am()).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(vr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let a=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.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(vr(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;je(t.align)&&(a.align=t.align),je(t.position)&&(a.position=t.position),je(t.size)&&(a.size=t.size),je(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){ri(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,a=e.id?e.id:ak(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:(u=this.internalTracks.get(a))==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(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){ri(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(ek(e)||!sk(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){ri(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){ri(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)}},Ee=Go;var Je=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 nm=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=nm(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},om=i=>{let e=nm(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as xe,map as pt,merge as lm,filterChanged as ok,isNonNullable as cm,Subject as uk,filter as dm,mapTo as pm,combine as lk,once as ck,ErrorCategory as dk,ValueSubject as hm,getCurrentBrowser as pk,CurrentClientBrowser as hk}from"@vkontakte/videoplayer-shared";var nk=3,um=(i,e,t=nk)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let u=s-1;u>=0;u--)i.end(u)+t>=r&&(r=i.start(u));for(let u=s+1;u<i.length;u++)i.start(u)-t<=a&&(a=i.end(u))}}return{from:r,to:a}};var de=i=>{let e=y=>xe(i,y).pipe(pm(void 0)),r=lm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>xe(i,y))).pipe(pt(y=>y.type==="ended"?i.readyState<2:i.readyState<3),ok()),a=lm(xe(i,"progress"),xe(i,"timeupdate")).pipe(pt(()=>um(i.buffered,i.currentTime))),n=pk().browser===hk.Safari?lk({play:e("play").pipe(ck()),playing:e("playing")}).pipe(pm(void 0)):e("playing"),o=xe(i,"volumechange").pipe(pt(()=>({muted:i.muted,volume:i.volume}))),u=xe(i,"ratechange").pipe(pt(()=>i.playbackRate)),l=xe(i,"error").pipe(dm(()=>!!(i.error||i.played.length)),pt(()=>{var T;let y=i.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:dk.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(T=i.error)!=null?T:void 0}})),c=xe(i,"timeupdate").pipe(pt(()=>i.currentTime)),d=new uk,p=.3,h;c.subscribe(y=>{i.loop&&cm(h)&&cm(y)&&h>=i.duration-p&&y<=p&&d.next(h),h=y});let f=xe(i,"enterpictureinpicture"),b=xe(i,"leavepictureinpicture"),v=new hm(om(i));f.subscribe(()=>v.next(!0)),b.subscribe(()=>v.next(!1));let S=new hm(Yo(i));return xe(i,"fullscreenchange").pipe(pt(()=>Yo(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(dm(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:xe(i,"durationchange").pipe(pt(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:u,inPiP$:v,inFullscreen$:S}};import{VideoQuality as ht}from"@vkontakte/videoplayer-shared";var ft=i=>{switch(i){case"mobile":return ht.Q_144P;case"lowest":return ht.Q_240P;case"low":return ht.Q_360P;case"sd":case"medium":return ht.Q_480P;case"hd":case"high":return ht.Q_720P;case"fullhd":case"full":return ht.Q_1080P;case"quadhd":case"quad":return ht.Q_1440P;case"ultrahd":case"ultra":return ht.Q_2160P}};var Jo=Fe(Za(),1);import{isNonNullable as mt,isNullable as Qo,now as Pm,isHigher as zo,isHigherOrEqual as Em,isInvariantQuality as xm,isLower as Ko,isLowerOrEqual as Ik,videoSizeToQuality as Ek,assertNotEmptyArray as xk}from"@vkontakte/videoplayer-shared";var Wo=!1,Xe={},ym=i=>{Wo=i},Tm=()=>{Xe={}},Im=i=>{i(Xe)},ai=(i,e)=>{var t;Wo&&(Xe.meta=(t=Xe.meta)!=null?t:{},Xe.meta[i]=e)},ae=class{constructor(e){this.name=e}next(e){var r,a;if(!Wo)return;Xe.series=(r=Xe.series)!=null?r:{};let t=(a=Xe.series[this.name])!=null?a:[];t.push([Date.now(),e]),Xe.series[this.name]=t}};var Pk=new ae("best_bitrate"),kk=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,es=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Pm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},wk='Assertion "ABR Tracks is empty array" failed',Ak=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var H,L,k,U,z;xk(i,wk);let p=r.usePixelRatio&&(H=window.devicePixelRatio)!=null?H:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},f=h&&Ek(h),b=r.considerPlaybackRate&&mt(o)?o:1,v=i.filter(A=>!xm(A.quality)).sort((A,x)=>zo(A.quality,x.quality)?-1:1),S=(L=(0,Jo.default)(v,-1))==null?void 0:L.quality,g=(k=(0,Jo.default)(v,0))==null?void 0:k.quality,y=Qo(a)||mt(a.min)&&mt(a.max)&&Ko(a.max,a.min)||mt(a.min)&&g&&zo(a.min,g)||mt(a.max)&&S&&Ko(a.max,S),T=b*kk(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),I={},D=v.filter(A=>(f?Ko(A.quality,f):!0)?(mt(t)&&isFinite(t)&&mt(A.bitrate)?t-s>=A.bitrate*T:!0)?r.lazyQualitySwitch&&mt(r.minBufferToSwitchUp)&&u&&!xm(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&zo(A.quality,u.quality)?(I[A.quality]="Buffer",!1):!!c&&Em(A.quality,c)?(I[A.quality]="DroppedFramesLimit",!1):y||(Qo(a.max)||Ik(A.quality,a.max))&&(Qo(a.min)||Em(A.quality,a.min))?!0:(I[A.quality]="FitsQualityLimits",!1):(I[A.quality]="FitsThroughput",!1):(I[A.quality]="FitsContainer",!1))[0];D&&D.bitrate&&Pk.next(D.bitrate);let $=(U=D!=null?D:v[Math.ceil((v.length-1)/2)])!=null?U:i[0];$.quality!==((z=l==null?void 0:l.last)==null?void 0:z.quality)&&d({message:`
6
+ var Sv=Object.create;var Xs=Object.defineProperty,yv=Object.defineProperties,Tv=Object.getOwnPropertyDescriptor,Iv=Object.getOwnPropertyDescriptors,Ev=Object.getOwnPropertyNames,dl=Object.getOwnPropertySymbols,xv=Object.getPrototypeOf,hl=Object.prototype.hasOwnProperty,Pv=Object.prototype.propertyIsEnumerable;var Ne=Math.pow,pl=(i,e,t)=>e in i?Xs(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,A=(i,e)=>{for(var t in e||(e={}))hl.call(e,t)&&pl(i,t,e[t]);if(dl)for(var t of dl(e))Pv.call(e,t)&&pl(i,t,e[t]);return i},B=(i,e)=>yv(i,Iv(e));var m=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var wv=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ev(e))!hl.call(i,a)&&a!==t&&Xs(i,a,{get:()=>e[a],enumerable:!(r=Tv(e,a))||r.enumerable});return i};var Fe=(i,e,t)=>(t=i!=null?Sv(xv(i)):{},wv(e||!i||!i.__esModule?Xs(t,"default",{value:i,enumerable:!0}):t,i));var R=(i,e,t)=>new Promise((r,a)=>{var s=u=>{try{o(t.next(u))}catch(l){a(l)}},n=u=>{try{o(t.throw(u))}catch(l){a(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(i,e)).next())}),Av=function(i,e){this[0]=i,this[1]=e},J=(i,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Av,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},a=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(i,e),s[Symbol.asyncIterator]=()=>s,a("next"),a("throw"),a("return"),s};var me=m((kL,Tl)=>{"use strict";Tl.exports=function(i){try{return!!i()}catch(e){return!0}}});var Br=m((RL,Il)=>{"use strict";var Ov=me();Il.exports=!Ov(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")})});var ne=m((LL,Pl)=>{"use strict";var El=Br(),xl=Function.prototype,an=xl.call,Bv=El&&xl.bind.bind(an,an);Pl.exports=El?Bv:function(i){return function(){return an.apply(i,arguments)}}});var rr=m(($L,Al)=>{"use strict";var wl=ne(),Vv=wl({}.toString),_v=wl("".slice);Al.exports=function(i){return _v(Vv(i),8,-1)}});var Rl=m((CL,kl)=>{"use strict";var Nv=ne(),Fv=me(),qv=rr(),sn=Object,Uv=Nv("".split);kl.exports=Fv(function(){return!sn("z").propertyIsEnumerable(0)})?function(i){return qv(i)=="String"?Uv(i,""):sn(i)}:sn});var ir=m((DL,Ll)=>{"use strict";Ll.exports=function(i){return i==null}});var pa=m((ML,$l)=>{"use strict";var Hv=ir(),jv=TypeError;$l.exports=function(i){if(Hv(i))throw jv("Can't call method on "+i);return i}});var ar=m((OL,Cl)=>{"use strict";var Gv=Rl(),Yv=pa();Cl.exports=function(i){return Gv(Yv(i))}});var nn=m((BL,Dl)=>{"use strict";Dl.exports=function(){}});var Rt=m((VL,Ml)=>{"use strict";Ml.exports={}});var X=m((Ol,Bl)=>{"use strict";var ha=function(i){return i&&i.Math==Math&&i};Bl.exports=ha(typeof globalThis=="object"&&globalThis)||ha(typeof window=="object"&&window)||ha(typeof self=="object"&&self)||ha(typeof global=="object"&&global)||function(){return this}()||Ol||Function("return this")()});var un=m((_L,Vl)=>{"use strict";var on=typeof document=="object"&&document.all,Wv=typeof on=="undefined"&&on!==void 0;Vl.exports={all:on,IS_HTMLDDA:Wv}});var G=m((NL,Nl)=>{"use strict";var _l=un(),Qv=_l.all;Nl.exports=_l.IS_HTMLDDA?function(i){return typeof i=="function"||i===Qv}:function(i){return typeof i=="function"}});var Ul=m((FL,ql)=>{"use strict";var zv=X(),Kv=G(),Fl=zv.WeakMap;ql.exports=Kv(Fl)&&/native code/.test(String(Fl))});var qe=m((qL,Gl)=>{"use strict";var Hl=G(),jl=un(),Jv=jl.all;Gl.exports=jl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Hl(i)||i===Jv}:function(i){return typeof i=="object"?i!==null:Hl(i)}});var Ue=m((UL,Yl)=>{"use strict";var Xv=me();Yl.exports=!Xv(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7})});var fa=m((HL,Ql)=>{"use strict";var Zv=X(),Wl=qe(),ln=Zv.document,eS=Wl(ln)&&Wl(ln.createElement);Ql.exports=function(i){return eS?ln.createElement(i):{}}});var cn=m((jL,zl)=>{"use strict";var tS=Ue(),rS=me(),iS=fa();zl.exports=!tS&&!rS(function(){return Object.defineProperty(iS("div"),"a",{get:function(){return 7}}).a!=7})});var dn=m((GL,Kl)=>{"use strict";var aS=Ue(),sS=me();Kl.exports=aS&&sS(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42})});var Le=m((YL,Jl)=>{"use strict";var nS=qe(),oS=String,uS=TypeError;Jl.exports=function(i){if(nS(i))return i;throw uS(oS(i)+" is not an object")}});var oe=m((WL,Xl)=>{"use strict";var lS=Br(),ma=Function.prototype.call;Xl.exports=lS?ma.bind(ma):function(){return ma.apply(ma,arguments)}});var ba=m((QL,Zl)=>{"use strict";Zl.exports={}});var We=m((zL,tc)=>{"use strict";var pn=ba(),hn=X(),cS=G(),ec=function(i){return cS(i)?i:void 0};tc.exports=function(i,e){return arguments.length<2?ec(pn[i])||ec(hn[i]):pn[i]&&pn[i][e]||hn[i]&&hn[i][e]}});var Vr=m((KL,rc)=>{"use strict";var dS=ne();rc.exports=dS({}.isPrototypeOf)});var _r=m((JL,ic)=>{"use strict";ic.exports=typeof navigator!="undefined"&&String(navigator.userAgent)||""});var mn=m((XL,lc)=>{"use strict";var uc=X(),fn=_r(),ac=uc.process,sc=uc.Deno,nc=ac&&ac.versions||sc&&sc.version,oc=nc&&nc.v8,$e,ga;oc&&($e=oc.split("."),ga=$e[0]>0&&$e[0]<4?1:+($e[0]+$e[1]));!ga&&fn&&($e=fn.match(/Edge\/(\d+)/),(!$e||$e[1]>=74)&&($e=fn.match(/Chrome\/(\d+)/),$e&&(ga=+$e[1])));lc.exports=ga});var bn=m((ZL,dc)=>{"use strict";var cc=mn(),pS=me(),hS=X(),fS=hS.String;dc.exports=!!Object.getOwnPropertySymbols&&!pS(function(){var i=Symbol();return!fS(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&cc&&cc<41})});var gn=m((e$,pc)=>{"use strict";var mS=bn();pc.exports=mS&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var vn=m((t$,hc)=>{"use strict";var bS=We(),gS=G(),vS=Vr(),SS=gn(),yS=Object;hc.exports=SS?function(i){return typeof i=="symbol"}:function(i){var e=bS("Symbol");return gS(e)&&vS(e.prototype,yS(i))}});var Nr=m((r$,fc)=>{"use strict";var TS=String;fc.exports=function(i){try{return TS(i)}catch(e){return"Object"}}});var Qe=m((i$,mc)=>{"use strict";var IS=G(),ES=Nr(),xS=TypeError;mc.exports=function(i){if(IS(i))return i;throw xS(ES(i)+" is not a function")}});var Fr=m((a$,bc)=>{"use strict";var PS=Qe(),wS=ir();bc.exports=function(i,e){var t=i[e];return wS(t)?void 0:PS(t)}});var vc=m((s$,gc)=>{"use strict";var Sn=oe(),yn=G(),Tn=qe(),AS=TypeError;gc.exports=function(i,e){var t,r;if(e==="string"&&yn(t=i.toString)&&!Tn(r=Sn(t,i))||yn(t=i.valueOf)&&!Tn(r=Sn(t,i))||e!=="string"&&yn(t=i.toString)&&!Tn(r=Sn(t,i)))return r;throw AS("Can't convert object to primitive value")}});var Ce=m((n$,Sc)=>{"use strict";Sc.exports=!0});var Ic=m((o$,Tc)=>{"use strict";var yc=X(),kS=Object.defineProperty;Tc.exports=function(i,e){try{kS(yc,i,{value:e,configurable:!0,writable:!0})}catch(t){yc[i]=e}return e}});var va=m((u$,xc)=>{"use strict";var RS=X(),LS=Ic(),Ec="__core-js_shared__",$S=RS[Ec]||LS(Ec,{});xc.exports=$S});var In=m((l$,wc)=>{"use strict";var CS=Ce(),Pc=va();(wc.exports=function(i,e){return Pc[i]||(Pc[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:CS?"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 qr=m((c$,Ac)=>{"use strict";var DS=pa(),MS=Object;Ac.exports=function(i){return MS(DS(i))}});var De=m((d$,kc)=>{"use strict";var OS=ne(),BS=qr(),VS=OS({}.hasOwnProperty);kc.exports=Object.hasOwn||function(e,t){return VS(BS(e),t)}});var En=m((p$,Rc)=>{"use strict";var _S=ne(),NS=0,FS=Math.random(),qS=_S(1 .toString);Rc.exports=function(i){return"Symbol("+(i===void 0?"":i)+")_"+qS(++NS+FS,36)}});var te=m((h$,$c)=>{"use strict";var US=X(),HS=In(),Lc=De(),jS=En(),GS=bn(),YS=gn(),sr=US.Symbol,xn=HS("wks"),WS=YS?sr.for||sr:sr&&sr.withoutSetter||jS;$c.exports=function(i){return Lc(xn,i)||(xn[i]=GS&&Lc(sr,i)?sr[i]:WS("Symbol."+i)),xn[i]}});var Oc=m((f$,Mc)=>{"use strict";var QS=oe(),Cc=qe(),Dc=vn(),zS=Fr(),KS=vc(),JS=te(),XS=TypeError,ZS=JS("toPrimitive");Mc.exports=function(i,e){if(!Cc(i)||Dc(i))return i;var t=zS(i,ZS),r;if(t){if(e===void 0&&(e="default"),r=QS(t,i,e),!Cc(r)||Dc(r))return r;throw XS("Can't convert object to primitive value")}return e===void 0&&(e="number"),KS(i,e)}});var Sa=m((m$,Bc)=>{"use strict";var ey=Oc(),ty=vn();Bc.exports=function(i){var e=ey(i,"string");return ty(e)?e:e+""}});var Lt=m(_c=>{"use strict";var ry=Ue(),iy=cn(),ay=dn(),ya=Le(),Vc=Sa(),sy=TypeError,Pn=Object.defineProperty,ny=Object.getOwnPropertyDescriptor,wn="enumerable",An="configurable",kn="writable";_c.f=ry?ay?function(e,t,r){if(ya(e),t=Vc(t),ya(r),typeof e=="function"&&t==="prototype"&&"value"in r&&kn in r&&!r[kn]){var a=ny(e,t);a&&a[kn]&&(e[t]=r.value,r={configurable:An in r?r[An]:a[An],enumerable:wn in r?r[wn]:a[wn],writable:!1})}return Pn(e,t,r)}:Pn:function(e,t,r){if(ya(e),t=Vc(t),ya(r),iy)try{return Pn(e,t,r)}catch(a){}if("get"in r||"set"in r)throw sy("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Ur=m((g$,Nc)=>{"use strict";Nc.exports=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}}});var $t=m((v$,Fc)=>{"use strict";var oy=Ue(),uy=Lt(),ly=Ur();Fc.exports=oy?function(i,e,t){return uy.f(i,e,ly(1,t))}:function(i,e,t){return i[e]=t,i}});var Ta=m((S$,Uc)=>{"use strict";var cy=In(),dy=En(),qc=cy("keys");Uc.exports=function(i){return qc[i]||(qc[i]=dy(i))}});var Ia=m((y$,Hc)=>{"use strict";Hc.exports={}});var Cn=m((T$,Yc)=>{"use strict";var py=Ul(),Gc=X(),hy=qe(),fy=$t(),Rn=De(),Ln=va(),my=Ta(),by=Ia(),jc="Object already initialized",$n=Gc.TypeError,gy=Gc.WeakMap,Ea,Hr,xa,vy=function(i){return xa(i)?Hr(i):Ea(i,{})},Sy=function(i){return function(e){var t;if(!hy(e)||(t=Hr(e)).type!==i)throw $n("Incompatible receiver, "+i+" required");return t}};py||Ln.state?(Me=Ln.state||(Ln.state=new gy),Me.get=Me.get,Me.has=Me.has,Me.set=Me.set,Ea=function(i,e){if(Me.has(i))throw $n(jc);return e.facade=i,Me.set(i,e),e},Hr=function(i){return Me.get(i)||{}},xa=function(i){return Me.has(i)}):(Ct=my("state"),by[Ct]=!0,Ea=function(i,e){if(Rn(i,Ct))throw $n(jc);return e.facade=i,fy(i,Ct,e),e},Hr=function(i){return Rn(i,Ct)?i[Ct]:{}},xa=function(i){return Rn(i,Ct)});var Me,Ct;Yc.exports={set:Ea,get:Hr,has:xa,enforce:vy,getterFor:Sy}});var Dn=m((I$,Kc)=>{"use strict";var yy=Br(),zc=Function.prototype,Wc=zc.apply,Qc=zc.call;Kc.exports=typeof Reflect=="object"&&Reflect.apply||(yy?Qc.bind(Wc):function(){return Qc.apply(Wc,arguments)})});var Mn=m((E$,Jc)=>{"use strict";var Ty=rr(),Iy=ne();Jc.exports=function(i){if(Ty(i)==="Function")return Iy(i)}});var td=m(ed=>{"use strict";var Xc={}.propertyIsEnumerable,Zc=Object.getOwnPropertyDescriptor,Ey=Zc&&!Xc.call({1:2},1);ed.f=Ey?function(e){var t=Zc(this,e);return!!t&&t.enumerable}:Xc});var On=m(id=>{"use strict";var xy=Ue(),Py=oe(),wy=td(),Ay=Ur(),ky=ar(),Ry=Sa(),Ly=De(),$y=cn(),rd=Object.getOwnPropertyDescriptor;id.f=xy?rd:function(e,t){if(e=ky(e),t=Ry(t),$y)try{return rd(e,t)}catch(r){}if(Ly(e,t))return Ay(!Py(wy.f,e,t),e[t])}});var Bn=m((w$,ad)=>{"use strict";var Cy=me(),Dy=G(),My=/#|\.prototype\./,jr=function(i,e){var t=By[Oy(i)];return t==_y?!0:t==Vy?!1:Dy(e)?Cy(e):!!e},Oy=jr.normalize=function(i){return String(i).replace(My,".").toLowerCase()},By=jr.data={},Vy=jr.NATIVE="N",_y=jr.POLYFILL="P";ad.exports=jr});var Gr=m((A$,nd)=>{"use strict";var sd=Mn(),Ny=Qe(),Fy=Br(),qy=sd(sd.bind);nd.exports=function(i,e){return Ny(i),e===void 0?i:Fy?qy(i,e):function(){return i.apply(e,arguments)}}});var Te=m((k$,ud)=>{"use strict";var Pa=X(),Uy=Dn(),Hy=Mn(),jy=G(),Gy=On().f,Yy=Bn(),nr=ba(),Wy=Gr(),or=$t(),od=De(),Qy=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 Uy(i,this,arguments)};return e.prototype=i.prototype,e};ud.exports=function(i,e){var t=i.target,r=i.global,a=i.stat,s=i.proto,n=r?Pa:a?Pa[t]:(Pa[t]||{}).prototype,o=r?nr:nr[t]||or(nr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,v,S;for(p in e)l=Yy(r?p:t+(a?".":"#")+p,i.forced),c=!l&&n&&od(n,p),f=o[p],c&&(i.dontCallGetSet?(S=Gy(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(c&&typeof f==typeof h)&&(i.bind&&c?v=Wy(h,Pa):i.wrap&&c?v=Qy(h):s&&jy(h)?v=Hy(h):v=h,(i.sham||h&&h.sham||f&&f.sham)&&or(v,"sham",!0),or(o,p,v),s&&(d=t+"Prototype",od(nr,d)||or(nr,d,{}),or(nr[d],p,h),i.real&&u&&(l||!u[p])&&or(u,p,h)))}});var dd=m((R$,cd)=>{"use strict";var Vn=Ue(),zy=De(),ld=Function.prototype,Ky=Vn&&Object.getOwnPropertyDescriptor,_n=zy(ld,"name"),Jy=_n&&function(){}.name==="something",Xy=_n&&(!Vn||Vn&&Ky(ld,"name").configurable);cd.exports={EXISTS:_n,PROPER:Jy,CONFIGURABLE:Xy}});var hd=m((L$,pd)=>{"use strict";var Zy=Math.ceil,eT=Math.floor;pd.exports=Math.trunc||function(e){var t=+e;return(t>0?eT:Zy)(t)}});var wa=m(($$,fd)=>{"use strict";var tT=hd();fd.exports=function(i){var e=+i;return e!==e||e===0?0:tT(e)}});var bd=m((C$,md)=>{"use strict";var rT=wa(),iT=Math.max,aT=Math.min;md.exports=function(i,e){var t=rT(i);return t<0?iT(t+e,0):aT(t,e)}});var vd=m((D$,gd)=>{"use strict";var sT=wa(),nT=Math.min;gd.exports=function(i){return i>0?nT(sT(i),9007199254740991):0}});var Aa=m((M$,Sd)=>{"use strict";var oT=vd();Sd.exports=function(i){return oT(i.length)}});var Id=m((O$,Td)=>{"use strict";var uT=ar(),lT=bd(),cT=Aa(),yd=function(i){return function(e,t,r){var a=uT(e),s=cT(a),n=lT(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}};Td.exports={includes:yd(!0),indexOf:yd(!1)}});var Pd=m((B$,xd)=>{"use strict";var dT=ne(),Nn=De(),pT=ar(),hT=Id().indexOf,fT=Ia(),Ed=dT([].push);xd.exports=function(i,e){var t=pT(i),r=0,a=[],s;for(s in t)!Nn(fT,s)&&Nn(t,s)&&Ed(a,s);for(;e.length>r;)Nn(t,s=e[r++])&&(~hT(a,s)||Ed(a,s));return a}});var Fn=m((V$,wd)=>{"use strict";wd.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var kd=m((_$,Ad)=>{"use strict";var mT=Pd(),bT=Fn();Ad.exports=Object.keys||function(e){return mT(e,bT)}});var Ld=m(Rd=>{"use strict";var gT=Ue(),vT=dn(),ST=Lt(),yT=Le(),TT=ar(),IT=kd();Rd.f=gT&&!vT?Object.defineProperties:function(e,t){yT(e);for(var r=TT(t),a=IT(t),s=a.length,n=0,o;s>n;)ST.f(e,o=a[n++],r[o]);return e}});var qn=m((F$,$d)=>{"use strict";var ET=We();$d.exports=ET("document","documentElement")});var Gn=m((q$,_d)=>{"use strict";var xT=Le(),PT=Ld(),Cd=Fn(),wT=Ia(),AT=qn(),kT=fa(),RT=Ta(),Dd=">",Md="<",Hn="prototype",jn="script",Bd=RT("IE_PROTO"),Un=function(){},Vd=function(i){return Md+jn+Dd+i+Md+"/"+jn+Dd},Od=function(i){i.write(Vd("")),i.close();var e=i.parentWindow.Object;return i=null,e},LT=function(){var i=kT("iframe"),e="java"+jn+":",t;return i.style.display="none",AT.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Vd("document.F=Object")),t.close(),t.F},ka,Ra=function(){try{ka=new ActiveXObject("htmlfile")}catch(e){}Ra=typeof document!="undefined"?document.domain&&ka?Od(ka):LT():Od(ka);for(var i=Cd.length;i--;)delete Ra[Hn][Cd[i]];return Ra()};wT[Bd]=!0;_d.exports=Object.create||function(e,t){var r;return e!==null?(Un[Hn]=xT(e),r=new Un,Un[Hn]=null,r[Bd]=e):r=Ra(),t===void 0?r:PT.f(r,t)}});var Fd=m((U$,Nd)=>{"use strict";var $T=me();Nd.exports=!$T(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype})});var Wn=m((H$,Ud)=>{"use strict";var CT=De(),DT=G(),MT=qr(),OT=Ta(),BT=Fd(),qd=OT("IE_PROTO"),Yn=Object,VT=Yn.prototype;Ud.exports=BT?Yn.getPrototypeOf:function(i){var e=MT(i);if(CT(e,qd))return e[qd];var t=e.constructor;return DT(t)&&e instanceof t?t.prototype:e instanceof Yn?VT:null}});var ur=m((j$,Hd)=>{"use strict";var _T=$t();Hd.exports=function(i,e,t,r){return r&&r.enumerable?i[e]=t:_T(i,e,t),i}});var Jn=m((G$,Yd)=>{"use strict";var NT=me(),FT=G(),qT=qe(),UT=Gn(),jd=Wn(),HT=ur(),jT=te(),GT=Ce(),Kn=jT("iterator"),Gd=!1,ze,Qn,zn;[].keys&&(zn=[].keys(),"next"in zn?(Qn=jd(jd(zn)),Qn!==Object.prototype&&(ze=Qn)):Gd=!0);var YT=!qT(ze)||NT(function(){var i={};return ze[Kn].call(i)!==i});YT?ze={}:GT&&(ze=UT(ze));FT(ze[Kn])||HT(ze,Kn,function(){return this});Yd.exports={IteratorPrototype:ze,BUGGY_SAFARI_ITERATORS:Gd}});var La=m((Y$,Qd)=>{"use strict";var WT=te(),QT=WT("toStringTag"),Wd={};Wd[QT]="z";Qd.exports=String(Wd)==="[object z]"});var lr=m((W$,zd)=>{"use strict";var zT=La(),KT=G(),$a=rr(),JT=te(),XT=JT("toStringTag"),ZT=Object,eI=$a(function(){return arguments}())=="Arguments",tI=function(i,e){try{return i[e]}catch(t){}};zd.exports=zT?$a:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=tI(e=ZT(i),XT))=="string"?t:eI?$a(e):(r=$a(e))=="Object"&&KT(e.callee)?"Arguments":r}});var Jd=m((Q$,Kd)=>{"use strict";var rI=La(),iI=lr();Kd.exports=rI?{}.toString:function(){return"[object "+iI(this)+"]"}});var Ca=m((z$,Zd)=>{"use strict";var aI=La(),sI=Lt().f,nI=$t(),oI=De(),uI=Jd(),lI=te(),Xd=lI("toStringTag");Zd.exports=function(i,e,t,r){if(i){var a=t?i:i.prototype;oI(a,Xd)||sI(a,Xd,{configurable:!0,value:e}),r&&!aI&&nI(a,"toString",uI)}}});var tp=m((K$,ep)=>{"use strict";var cI=Jn().IteratorPrototype,dI=Gn(),pI=Ur(),hI=Ca(),fI=Rt(),mI=function(){return this};ep.exports=function(i,e,t,r){var a=e+" Iterator";return i.prototype=dI(cI,{next:pI(+!r,t)}),hI(i,a,!1,!0),fI[a]=mI,i}});var ip=m((J$,rp)=>{"use strict";var bI=ne(),gI=Qe();rp.exports=function(i,e,t){try{return bI(gI(Object.getOwnPropertyDescriptor(i,e)[t]))}catch(r){}}});var sp=m((X$,ap)=>{"use strict";var vI=G(),SI=String,yI=TypeError;ap.exports=function(i){if(typeof i=="object"||vI(i))return i;throw yI("Can't set "+SI(i)+" as a prototype")}});var Xn=m((Z$,np)=>{"use strict";var TI=ip(),II=Le(),EI=sp();np.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var i=!1,e={},t;try{t=TI(Object.prototype,"__proto__","set"),t(e,[]),i=e instanceof Array}catch(r){}return function(a,s){return II(a),EI(s),i?t(a,s):a.__proto__=s,a}}():void 0)});var gp=m((eC,bp)=>{"use strict";var xI=Te(),PI=oe(),Da=Ce(),fp=dd(),wI=G(),AI=tp(),op=Wn(),up=Xn(),kI=Ca(),RI=$t(),Zn=ur(),LI=te(),lp=Rt(),mp=Jn(),$I=fp.PROPER,CI=fp.CONFIGURABLE,cp=mp.IteratorPrototype,Ma=mp.BUGGY_SAFARI_ITERATORS,Yr=LI("iterator"),dp="keys",Wr="values",pp="entries",hp=function(){return this};bp.exports=function(i,e,t,r,a,s,n){AI(t,e,r);var o=function(S){if(S===a&&p)return p;if(!Ma&&S in c)return c[S];switch(S){case dp:return function(){return new t(this,S)};case Wr:return function(){return new t(this,S)};case pp:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=i.prototype,d=c[Yr]||c["@@iterator"]||a&&c[a],p=!Ma&&d||o(a),h=e=="Array"&&c.entries||d,f,b,v;if(h&&(f=op(h.call(new i)),f!==Object.prototype&&f.next&&(!Da&&op(f)!==cp&&(up?up(f,cp):wI(f[Yr])||Zn(f,Yr,hp)),kI(f,u,!0,!0),Da&&(lp[u]=hp))),$I&&a==Wr&&d&&d.name!==Wr&&(!Da&&CI?RI(c,"name",Wr):(l=!0,p=function(){return PI(d,this)})),a)if(b={values:o(Wr),keys:s?p:o(dp),entries:o(pp)},n)for(v in b)(Ma||l||!(v in c))&&Zn(c,v,b[v]);else xI({target:e,proto:!0,forced:Ma||l},b);return(!Da||n)&&c[Yr]!==p&&Zn(c,Yr,p,{name:a}),lp[e]=p,b}});var Sp=m((tC,vp)=>{"use strict";vp.exports=function(i,e){return{value:i,done:e}}});var to=m((rC,xp)=>{"use strict";var DI=ar(),eo=nn(),yp=Rt(),Ip=Cn(),MI=Lt().f,OI=gp(),Oa=Sp(),BI=Ce(),VI=Ue(),Ep="Array Iterator",_I=Ip.set,NI=Ip.getterFor(Ep);xp.exports=OI(Array,"Array",function(i,e){_I(this,{type:Ep,target:DI(i),index:0,kind:e})},function(){var i=NI(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Oa(void 0,!0)):t=="keys"?Oa(r,!1):t=="values"?Oa(e[r],!1):Oa([r,e[r]],!1)},"values");var Tp=yp.Arguments=yp.Array;eo("keys");eo("values");eo("entries");if(!BI&&VI&&Tp.name!=="values")try{MI(Tp,"name",{value:"values"})}catch(i){}});var wp=m((iC,Pp)=>{"use strict";var FI=te(),qI=Rt(),UI=FI("iterator"),HI=Array.prototype;Pp.exports=function(i){return i!==void 0&&(qI.Array===i||HI[UI]===i)}});var ro=m((aC,kp)=>{"use strict";var jI=lr(),Ap=Fr(),GI=ir(),YI=Rt(),WI=te(),QI=WI("iterator");kp.exports=function(i){if(!GI(i))return Ap(i,QI)||Ap(i,"@@iterator")||YI[jI(i)]}});var Lp=m((sC,Rp)=>{"use strict";var zI=oe(),KI=Qe(),JI=Le(),XI=Nr(),ZI=ro(),eE=TypeError;Rp.exports=function(i,e){var t=arguments.length<2?ZI(i):e;if(KI(t))return JI(zI(t,i));throw eE(XI(i)+" is not iterable")}});var Dp=m((nC,Cp)=>{"use strict";var tE=oe(),$p=Le(),rE=Fr();Cp.exports=function(i,e,t){var r,a;$p(i);try{if(r=rE(i,"return"),!r){if(e==="throw")throw t;return t}r=tE(r,i)}catch(s){a=!0,r=s}if(e==="throw")throw t;if(a)throw r;return $p(r),t}});var Va=m((oC,Vp)=>{"use strict";var iE=Gr(),aE=oe(),sE=Le(),nE=Nr(),oE=wp(),uE=Aa(),Mp=Vr(),lE=Lp(),cE=ro(),Op=Dp(),dE=TypeError,Ba=function(i,e){this.stopped=i,this.result=e},Bp=Ba.prototype;Vp.exports=function(i,e,t){var r=t&&t.that,a=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=iE(e,r),l,c,d,p,h,f,b,v=function(g){return l&&Op(l,"normal",g),new Ba(!0,g)},S=function(g){return a?(sE(g),o?u(g[0],g[1],v):u(g[0],g[1])):o?u(g,v):u(g)};if(s)l=i.iterator;else if(n)l=i;else{if(c=cE(i),!c)throw dE(nE(i)+" is not iterable");if(oE(c)){for(d=0,p=uE(i);p>d;d++)if(h=S(i[d]),h&&Mp(Bp,h))return h;return new Ba(!1)}l=lE(i,c)}for(f=s?i.next:l.next;!(b=aE(f,l)).done;){try{h=S(b.value)}catch(g){Op(l,"throw",g)}if(typeof h=="object"&&h&&Mp(Bp,h))return h}return new Ba(!1)}});var Np=m((uC,_p)=>{"use strict";var pE=Sa(),hE=Lt(),fE=Ur();_p.exports=function(i,e,t){var r=pE(e);r in i?hE.f(i,r,fE(0,t)):i[r]=t}});var Fp=m(()=>{"use strict";var mE=Te(),bE=Va(),gE=Np();mE({target:"Object",stat:!0},{fromEntries:function(e){var t={};return bE(e,function(r,a){gE(t,r,a)},{AS_ENTRIES:!0}),t}})});var Up=m((dC,qp)=>{"use strict";to();Fp();var vE=ba();qp.exports=vE.Object.fromEntries});var jp=m((pC,Hp)=>{"use strict";Hp.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 Wp=m(()=>{"use strict";to();var SE=jp(),yE=X(),TE=lr(),IE=$t(),Gp=Rt(),EE=te(),Yp=EE("toStringTag");for(_a in SE)io=yE[_a],Na=io&&io.prototype,Na&&TE(Na)!==Yp&&IE(Na,Yp,_a),Gp[_a]=Gp.Array;var io,Na,_a});var zp=m((mC,Qp)=>{"use strict";var xE=Up();Wp();Qp.exports=xE});var Fa=m((bC,Kp)=>{"use strict";var PE=zp();Kp.exports=PE});var Jp=m(()=>{"use strict"});var Qr=m((SC,Xp)=>{"use strict";var wE=rr();Xp.exports=typeof process!="undefined"&&wE(process)=="process"});var eh=m((yC,Zp)=>{"use strict";var AE=Lt();Zp.exports=function(i,e,t){return AE.f(i,e,t)}});var ih=m((TC,rh)=>{"use strict";var kE=We(),RE=eh(),LE=te(),$E=Ue(),th=LE("species");rh.exports=function(i){var e=kE(i);$E&&e&&!e[th]&&RE(e,th,{configurable:!0,get:function(){return this}})}});var sh=m((IC,ah)=>{"use strict";var CE=Vr(),DE=TypeError;ah.exports=function(i,e){if(CE(e,i))return i;throw DE("Incorrect invocation")}});var so=m((EC,nh)=>{"use strict";var ME=ne(),OE=G(),ao=va(),BE=ME(Function.toString);OE(ao.inspectSource)||(ao.inspectSource=function(i){return BE(i)});nh.exports=ao.inspectSource});var ph=m((xC,dh)=>{"use strict";var VE=ne(),_E=me(),oh=G(),NE=lr(),FE=We(),qE=so(),uh=function(){},UE=[],lh=FE("Reflect","construct"),no=/^\s*(?:class|function)\b/,HE=VE(no.exec),jE=!no.exec(uh),zr=function(e){if(!oh(e))return!1;try{return lh(uh,UE,e),!0}catch(t){return!1}},ch=function(e){if(!oh(e))return!1;switch(NE(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return jE||!!HE(no,qE(e))}catch(t){return!0}};ch.sham=!0;dh.exports=!lh||_E(function(){var i;return zr(zr.call)||!zr(Object)||!zr(function(){i=!0})||i})?ch:zr});var fh=m((PC,hh)=>{"use strict";var GE=ph(),YE=Nr(),WE=TypeError;hh.exports=function(i){if(GE(i))return i;throw WE(YE(i)+" is not a constructor")}});var oo=m((wC,bh)=>{"use strict";var mh=Le(),QE=fh(),zE=ir(),KE=te(),JE=KE("species");bh.exports=function(i,e){var t=mh(i).constructor,r;return t===void 0||zE(r=mh(t)[JE])?e:QE(r)}});var vh=m((AC,gh)=>{"use strict";var XE=ne();gh.exports=XE([].slice)});var yh=m((kC,Sh)=>{"use strict";var ZE=TypeError;Sh.exports=function(i,e){if(i<e)throw ZE("Not enough arguments");return i}});var uo=m((RC,Th)=>{"use strict";var ex=_r();Th.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(ex)});var vo=m((LC,Lh)=>{"use strict";var be=X(),tx=Dn(),rx=Gr(),Ih=G(),ix=De(),Rh=me(),Eh=qn(),ax=vh(),xh=fa(),sx=yh(),nx=uo(),ox=Qr(),mo=be.setImmediate,bo=be.clearImmediate,ux=be.process,lo=be.Dispatch,lx=be.Function,Ph=be.MessageChannel,cx=be.String,co=0,Kr={},wh="onreadystatechange",Jr,Dt,po,ho;Rh(function(){Jr=be.location});var go=function(i){if(ix(Kr,i)){var e=Kr[i];delete Kr[i],e()}},fo=function(i){return function(){go(i)}},Ah=function(i){go(i.data)},kh=function(i){be.postMessage(cx(i),Jr.protocol+"//"+Jr.host)};(!mo||!bo)&&(mo=function(e){sx(arguments.length,1);var t=Ih(e)?e:lx(e),r=ax(arguments,1);return Kr[++co]=function(){tx(t,void 0,r)},Dt(co),co},bo=function(e){delete Kr[e]},ox?Dt=function(i){ux.nextTick(fo(i))}:lo&&lo.now?Dt=function(i){lo.now(fo(i))}:Ph&&!nx?(po=new Ph,ho=po.port2,po.port1.onmessage=Ah,Dt=rx(ho.postMessage,ho)):be.addEventListener&&Ih(be.postMessage)&&!be.importScripts&&Jr&&Jr.protocol!=="file:"&&!Rh(kh)?(Dt=kh,be.addEventListener("message",Ah,!1)):wh in xh("script")?Dt=function(i){Eh.appendChild(xh("script"))[wh]=function(){Eh.removeChild(this),go(i)}}:Dt=function(i){setTimeout(fo(i),0)});Lh.exports={set:mo,clear:bo}});var So=m(($C,Ch)=>{"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}}};Ch.exports=$h});var Mh=m((CC,Dh)=>{"use strict";var dx=_r();Dh.exports=/ipad|iphone|ipod/i.test(dx)&&typeof Pebble!="undefined"});var Bh=m((DC,Oh)=>{"use strict";var px=_r();Oh.exports=/web0s(?!.*chrome)/i.test(px)});var jh=m((MC,Hh)=>{"use strict";var Mt=X(),Vh=Gr(),hx=On().f,yo=vo().set,fx=So(),mx=uo(),bx=Mh(),gx=Bh(),To=Qr(),_h=Mt.MutationObserver||Mt.WebKitMutationObserver,Nh=Mt.document,Fh=Mt.process,qa=Mt.Promise,qh=hx(Mt,"queueMicrotask"),xo=qh&&qh.value,cr,Io,Eo,Ua,Uh;xo||(Xr=new fx,Zr=function(){var i,e;for(To&&(i=Fh.domain)&&i.exit();e=Xr.get();)try{e()}catch(t){throw Xr.head&&cr(),t}i&&i.enter()},!mx&&!To&&!gx&&_h&&Nh?(Io=!0,Eo=Nh.createTextNode(""),new _h(Zr).observe(Eo,{characterData:!0}),cr=function(){Eo.data=Io=!Io}):!bx&&qa&&qa.resolve?(Ua=qa.resolve(void 0),Ua.constructor=qa,Uh=Vh(Ua.then,Ua),cr=function(){Uh(Zr)}):To?cr=function(){Fh.nextTick(Zr)}:(yo=Vh(yo,Mt),cr=function(){yo(Zr)}),xo=function(i){Xr.head||cr(),Xr.add(i)});var Xr,Zr;Hh.exports=xo});var Yh=m((OC,Gh)=>{"use strict";Gh.exports=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}}});var Ha=m((BC,Wh)=>{"use strict";Wh.exports=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}}});var Ot=m((VC,Qh)=>{"use strict";var vx=X();Qh.exports=vx.Promise});var Po=m((_C,zh)=>{"use strict";zh.exports=typeof Deno=="object"&&Deno&&typeof Deno.version=="object"});var Jh=m((NC,Kh)=>{"use strict";var Sx=Po(),yx=Qr();Kh.exports=!Sx&&!yx&&typeof window=="object"&&typeof document=="object"});var dr=m((FC,ef)=>{"use strict";var Tx=X(),ei=Ot(),Ix=G(),Ex=Bn(),xx=so(),Px=te(),wx=Jh(),Ax=Po(),kx=Ce(),wo=mn(),Xh=ei&&ei.prototype,Rx=Px("species"),Ao=!1,Zh=Ix(Tx.PromiseRejectionEvent),Lx=Ex("Promise",function(){var i=xx(ei),e=i!==String(ei);if(!e&&wo===66||kx&&!(Xh.catch&&Xh.finally))return!0;if(!wo||wo<51||!/native code/.test(i)){var t=new ei(function(s){s(1)}),r=function(s){s(function(){},function(){})},a=t.constructor={};if(a[Rx]=r,Ao=t.then(function(){})instanceof r,!Ao)return!0}return!e&&(wx||Ax)&&!Zh});ef.exports={CONSTRUCTOR:Lx,REJECTION_EVENT:Zh,SUBCLASSING:Ao}});var pr=m((qC,rf)=>{"use strict";var tf=Qe(),$x=TypeError,Cx=function(i){var e,t;this.promise=new i(function(r,a){if(e!==void 0||t!==void 0)throw $x("Bad Promise constructor");e=r,t=a}),this.resolve=tf(e),this.reject=tf(t)};rf.exports.f=function(i){return new Cx(i)}});var If=m(()=>{"use strict";var Dx=Te(),Mx=Ce(),Wa=Qr(),ct=X(),br=oe(),af=ur(),sf=Xn(),Ox=Ca(),Bx=ih(),Vx=Qe(),Ya=G(),_x=qe(),Nx=sh(),Fx=oo(),cf=vo().set,Co=jh(),qx=Yh(),Ux=Ha(),Hx=So(),df=Cn(),Qa=Ot(),Do=dr(),pf=pr(),za="Promise",hf=Do.CONSTRUCTOR,jx=Do.REJECTION_EVENT,Gx=Do.SUBCLASSING,ko=df.getterFor(za),Yx=df.set,hr=Qa&&Qa.prototype,Bt=Qa,ja=hr,ff=ct.TypeError,Ro=ct.document,Mo=ct.process,Lo=pf.f,Wx=Lo,Qx=!!(Ro&&Ro.createEvent&&ct.dispatchEvent),mf="unhandledrejection",zx="rejectionhandled",nf=0,bf=1,Kx=2,Oo=1,gf=2,Ga,of,Jx,uf,vf=function(i){var e;return _x(i)&&Ya(e=i.then)?e:!1},Sf=function(i,e){var t=e.value,r=e.state==bf,a=r?i.ok:i.fail,s=i.resolve,n=i.reject,o=i.domain,u,l,c;try{a?(r||(e.rejection===gf&&Zx(e),e.rejection=Oo),a===!0?u=t:(o&&o.enter(),u=a(t),o&&(o.exit(),c=!0)),u===i.promise?n(ff("Promise-chain cycle")):(l=vf(u))?br(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},yf=function(i,e){i.notified||(i.notified=!0,Co(function(){for(var t=i.reactions,r;r=t.get();)Sf(r,i);i.notified=!1,e&&!i.rejection&&Xx(i)}))},Tf=function(i,e,t){var r,a;Qx?(r=Ro.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),ct.dispatchEvent(r)):r={promise:e,reason:t},!jx&&(a=ct["on"+i])?a(r):i===mf&&qx("Unhandled promise rejection",t)},Xx=function(i){br(cf,ct,function(){var e=i.facade,t=i.value,r=lf(i),a;if(r&&(a=Ux(function(){Wa?Mo.emit("unhandledRejection",t,e):Tf(mf,e,t)}),i.rejection=Wa||lf(i)?gf:Oo,a.error))throw a.value})},lf=function(i){return i.rejection!==Oo&&!i.parent},Zx=function(i){br(cf,ct,function(){var e=i.facade;Wa?Mo.emit("rejectionHandled",e):Tf(zx,e,i.value)})},fr=function(i,e,t){return function(r){i(e,r,t)}},mr=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Kx,yf(i,!0))},$o=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw ff("Promise can't be resolved itself");var r=vf(e);r?Co(function(){var a={done:!1};try{br(r,e,fr($o,a,i),fr(mr,a,i))}catch(s){mr(a,s,i)}}):(i.value=e,i.state=bf,yf(i,!1))}catch(a){mr({done:!1},a,i)}}};if(hf&&(Bt=function(e){Nx(this,ja),Vx(e),br(Ga,this);var t=ko(this);try{e(fr($o,t),fr(mr,t))}catch(r){mr(t,r)}},ja=Bt.prototype,Ga=function(e){Yx(this,{type:za,done:!1,notified:!1,parent:!1,reactions:new Hx,rejection:!1,state:nf,value:void 0})},Ga.prototype=af(ja,"then",function(e,t){var r=ko(this),a=Lo(Fx(this,Bt));return r.parent=!0,a.ok=Ya(e)?e:!0,a.fail=Ya(t)&&t,a.domain=Wa?Mo.domain:void 0,r.state==nf?r.reactions.add(a):Co(function(){Sf(a,r)}),a.promise}),of=function(){var i=new Ga,e=ko(i);this.promise=i,this.resolve=fr($o,e),this.reject=fr(mr,e)},pf.f=Lo=function(i){return i===Bt||i===Jx?new of(i):Wx(i)},!Mx&&Ya(Qa)&&hr!==Object.prototype)){uf=hr.then,Gx||af(hr,"then",function(e,t){var r=this;return new Bt(function(a,s){br(uf,r,a,s)}).then(e,t)},{unsafe:!0});try{delete hr.constructor}catch(i){}sf&&sf(hr,ja)}Dx({global:!0,constructor:!0,wrap:!0,forced:hf},{Promise:Bt});Ox(Bt,za,!1,!0);Bx(za)});var Af=m((jC,wf)=>{"use strict";var eP=te(),xf=eP("iterator"),Pf=!1;try{Ef=0,Bo={next:function(){return{done:!!Ef++}},return:function(){Pf=!0}},Bo[xf]=function(){return this},Array.from(Bo,function(){throw 2})}catch(i){}var Ef,Bo;wf.exports=function(i,e){if(!e&&!Pf)return!1;var t=!1;try{var r={};r[xf]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(a){}return t}});var Vo=m((GC,kf)=>{"use strict";var tP=Ot(),rP=Af(),iP=dr().CONSTRUCTOR;kf.exports=iP||!rP(function(i){tP.all(i).then(void 0,function(){})})});var Rf=m(()=>{"use strict";var aP=Te(),sP=oe(),nP=Qe(),oP=pr(),uP=Ha(),lP=Va(),cP=Vo();aP({target:"Promise",stat:!0,forced:cP},{all:function(e){var t=this,r=oP.f(t),a=r.resolve,s=r.reject,n=uP(function(){var o=nP(t.resolve),u=[],l=0,c=1;lP(e,function(d){var p=l++,h=!1;c++,sP(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||a(u))},s)}),--c||a(u)});return n.error&&s(n.value),r.promise}})});var $f=m(()=>{"use strict";var dP=Te(),pP=Ce(),hP=dr().CONSTRUCTOR,No=Ot(),fP=We(),mP=G(),bP=ur(),Lf=No&&No.prototype;dP({target:"Promise",proto:!0,forced:hP,real:!0},{catch:function(i){return this.then(void 0,i)}});!pP&&mP(No)&&(_o=fP("Promise").prototype.catch,Lf.catch!==_o&&bP(Lf,"catch",_o,{unsafe:!0}));var _o});var Cf=m(()=>{"use strict";var gP=Te(),vP=oe(),SP=Qe(),yP=pr(),TP=Ha(),IP=Va(),EP=Vo();gP({target:"Promise",stat:!0,forced:EP},{race:function(e){var t=this,r=yP.f(t),a=r.reject,s=TP(function(){var n=SP(t.resolve);IP(e,function(o){vP(n,t,o).then(r.resolve,a)})});return s.error&&a(s.value),r.promise}})});var Df=m(()=>{"use strict";var xP=Te(),PP=oe(),wP=pr(),AP=dr().CONSTRUCTOR;xP({target:"Promise",stat:!0,forced:AP},{reject:function(e){var t=wP.f(this);return PP(t.reject,void 0,e),t.promise}})});var Fo=m((eD,Mf)=>{"use strict";var kP=Le(),RP=qe(),LP=pr();Mf.exports=function(i,e){if(kP(i),RP(e)&&e.constructor===i)return e;var t=LP.f(i),r=t.resolve;return r(e),t.promise}});var Vf=m(()=>{"use strict";var $P=Te(),CP=We(),Of=Ce(),DP=Ot(),Bf=dr().CONSTRUCTOR,MP=Fo(),OP=CP("Promise"),BP=Of&&!Bf;$P({target:"Promise",stat:!0,forced:Of||Bf},{resolve:function(e){return MP(BP&&this===OP?DP:this,e)}})});var _f=m(()=>{"use strict";If();Rf();$f();Cf();Df();Vf()});var Uf=m(()=>{"use strict";var VP=Te(),_P=Ce(),Ka=Ot(),NP=me(),Ff=We(),qf=G(),FP=oo(),Nf=Fo(),qP=ur(),Uo=Ka&&Ka.prototype,UP=!!Ka&&NP(function(){Uo.finally.call({then:function(){}},function(){})});VP({target:"Promise",proto:!0,real:!0,forced:UP},{finally:function(i){var e=FP(this,Ff("Promise")),t=qf(i);return this.then(t?function(r){return Nf(e,i()).then(function(){return r})}:i,t?function(r){return Nf(e,i()).then(function(){throw r})}:i)}});!_P&&qf(Ka)&&(qo=Ff("Promise").prototype.finally,Uo.finally!==qo&&qP(Uo,"finally",qo,{unsafe:!0}));var qo});var Ja=m((oD,Hf)=>{"use strict";var HP=We();Hf.exports=HP});var Gf=m((uD,jf)=>{"use strict";Jp();_f();Uf();var jP=Ja();jf.exports=jP("Promise","finally")});var Wf=m((lD,Yf)=>{"use strict";var GP=Gf();Yf.exports=GP});var Xa=m((cD,Qf)=>{"use strict";var YP=Wf();Qf.exports=YP});var vm=m(()=>{"use strict";var vw=Te(),Sw=qr(),yw=Aa(),Tw=wa(),Iw=nn();vw({target:"Array",proto:!0},{at:function(e){var t=Sw(this),r=yw(t),a=Tw(e),s=a>=0?a:r+a;return s<0||s>=r?void 0:t[s]}});Iw("at")});var ym=m((SM,Sm)=>{"use strict";vm();var Ew=Ja();Sm.exports=Ew("Array","at")});var Im=m((yM,Tm)=>{"use strict";var xw=ym();Tm.exports=xw});var ts=m((TM,Em)=>{"use strict";var Pw=Im();Em.exports=Pw});var tb=m(()=>{"use strict"});var rb=m(()=>{"use strict"});var ab=m((hV,ib)=>{"use strict";var LA=qe(),$A=rr(),CA=te(),DA=CA("match");ib.exports=function(i){var e;return LA(i)&&((e=i[DA])!==void 0?!!e:$A(i)=="RegExp")}});var nb=m((fV,sb)=>{"use strict";var MA=lr(),OA=String;sb.exports=function(i){if(MA(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return OA(i)}});var ub=m((mV,ob)=>{"use strict";var BA=Le();ob.exports=function(){var i=BA(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 db=m((bV,cb)=>{"use strict";var VA=oe(),_A=De(),NA=Vr(),FA=ub(),lb=RegExp.prototype;cb.exports=function(i){var e=i.flags;return e===void 0&&!("flags"in lb)&&!_A(i,"flags")&&NA(lb,i)?VA(FA,i):e}});var hb=m((gV,pb)=>{"use strict";var mu=ne(),qA=qr(),UA=Math.floor,hu=mu("".charAt),HA=mu("".replace),fu=mu("".slice),jA=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,GA=/\$([$&'`]|\d{1,2})/g;pb.exports=function(i,e,t,r,a,s){var n=t+i.length,o=r.length,u=GA;return a!==void 0&&(a=qA(a),u=jA),HA(s,u,function(l,c){var d;switch(hu(c,0)){case"$":return"$";case"&":return i;case"`":return fu(e,0,t);case"'":return fu(e,n);case"<":d=a[fu(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=UA(p/10);return h===0?l:h<=o?r[h-1]===void 0?hu(c,1):r[h-1]+hu(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var vb=m(()=>{"use strict";var YA=Te(),WA=oe(),bu=ne(),fb=pa(),QA=G(),zA=ir(),KA=ab(),Er=nb(),JA=Fr(),XA=db(),ZA=hb(),ek=te(),tk=Ce(),rk=ek("replace"),ik=TypeError,gb=bu("".indexOf),ak=bu("".replace),mb=bu("".slice),sk=Math.max,bb=function(i,e,t){return t>i.length?-1:e===""?t:gb(i,e,t)};YA({target:"String",proto:!0},{replaceAll:function(e,t){var r=fb(this),a,s,n,o,u,l,c,d,p,h=0,f=0,b="";if(!zA(e)){if(a=KA(e),a&&(s=Er(fb(XA(e))),!~gb(s,"g")))throw ik("`.replaceAll` does not allow non-global regexes");if(n=JA(e,rk),n)return WA(n,e,r,t);if(tk&&a)return ak(Er(r),e,t)}for(o=Er(r),u=Er(e),l=QA(t),l||(t=Er(t)),c=u.length,d=sk(1,c),h=bb(o,u,0);h!==-1;)p=l?Er(t(u,h,o)):ZA(u,o,h,[],void 0,t),b+=mb(o,f,h)+p,f=h+c,h=bb(o,u,h+d);return f<o.length&&(b+=mb(o,f)),b}})});var yb=m((yV,Sb)=>{"use strict";tb();rb();vb();var nk=Ja();Sb.exports=nk("String","replaceAll")});var Ib=m((TV,Tb)=>{"use strict";var ok=yb();Tb.exports=ok});var xb=m((IV,Eb)=>{"use strict";var uk=Ib();Eb.exports=uk});var fl="__VERSION__";var fe=(a=>(a.STOPPED="stopped",a.READY="ready",a.PLAYING="playing",a.PAUSED="paused",a))(fe||{}),kt=(g=>(g.MPEG="MPEG",g.DASH="DASH_SEP",g.DASH_SEP="DASH_SEP",g.DASH_SEP_VK="DASH_SEP",g.DASH_WEBM="DASH_WEBM",g.DASH_WEBM_AV1="DASH_WEBM_AV1",g.DASH_WEBM_VK="DASH_WEBM",g.DASH_ONDEMAND="DASH_ONDEMAND",g.DASH_ONDEMAND_VK="DASH_ONDEMAND",g.DASH_LIVE="DASH_LIVE",g.DASH_LIVE_CMAF="DASH_LIVE_CMAF",g.DASH_LIVE_WEBM="DASH_LIVE_WEBM",g.HLS="HLS",g.HLS_ONDEMAND="HLS_ONDEMAND",g.HLS_JS="HLS",g.HLS_LIVE="HLS_LIVE",g.HLS_LIVE_CMAF="HLS_LIVE_CMAF",g.WEB_RTC_LIVE="WEB_RTC_LIVE",g))(kt||{});var la=(a=>(a.NOT_AVAILABLE="NOT_AVAILABLE",a.AVAILABLE="AVAILABLE",a.CONNECTING="CONNECTING",a.CONNECTED="CONNECTED",a))(la||{}),Zs=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Zs||{});var en=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(en||{});import{assertNever as yl,assertNonNullable as kv,isNonNullable as ca,ValueSubject as tn,Subject as Rv,Subscription as Lv,merge as $v,observableFrom as Cv,fromEvent as bl,map as gl,tap as vl,filterChanged as Dv,isNullable as rn,ErrorCategory as Sl}from"@vkontakte/videoplayer-shared";var ml=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 da=class{constructor(e){this.connection$=new tn(void 0);this.castState$=new tn("NOT_AVAILABLE");this.errorEvent$=new Rv;this.realCastState$=new tn("NOT_AVAILABLE");this.subscription=new Lv;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=ca((s=window.chrome)==null?void 0:s.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||ml("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Sl.NETWORK,message:"Script loading failed!"})))}connect(){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(){ca(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();rn(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();rn(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(bl(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 yl(a.sessionState)}})).add($v(bl(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(vl(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),gl(a=>a.castState)),Cv([r.getCastState()])).pipe(Dv(),gl(Mv),vl(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var o;let s=a==="CONNECTED",n=ca(this.connection$.getValue());if(s&&!n){let u=r.getCurrentSession();kv(u);let l=u.getCastDevice(),c=(o=u.getMediaSession())==null?void 0:o.media.contentId;(rn(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:l}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a==="CONNECTED"?ca(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:Sl.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Mv=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 yl(i)}};var qg=Fe(Fa(),1);var am=Fe(Xa(),1);import{assertNever as zf}from"@vkontakte/videoplayer-shared";var re=(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:zf(t)}return i},Ho=(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:zf(e)}};var E=(i,e,t=!1)=>{let r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};import{isNonNullable as WP,Subject as Za,merge as Kf}from"@vkontakte/videoplayer-shared";var C=class{constructor(e){this.transitionStarted$=new Za;this.transitionEnded$=new Za;this.transitionUpdated$=new Za;this.forceChanged$=new Za;this.stateChangeStarted$=Kf(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Kf(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||WP(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 QP}from"@vkontakte/videoplayer-shared";var Jf=i=>{switch(i){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 QP(i)}};import{assertNever as gr,assertNonNullable as Vt,debounce as Xf,ErrorCategory as Zf,fromEvent as _t,isNonNullable as em,map as tm,merge as rm,observableFrom as zP,Subject as KP,Subscription as jo,timeout as JP,getHighestQuality as XP}from"@vkontakte/videoplayer-shared";var ZP=5,ew=5,tw=500,im=7e3,ti=class{constructor(e){this.subscription=new jo;this.loadMediaTimeoutSubscription=new jo;this.videoState=new C("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:gr(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:gr(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:gr(e)}break}default:gr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Jf(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 jo;this.subscription.add(e),this.subscription.add(rm(this.videoState.stateChangeStarted$.pipe(tm(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(tm(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 KP;e.add(a.pipe(Xf(tw)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(_t(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)>ZP)&&a.next(o),s=o})),e.add(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);let{remotePlayer:s}=this.params.connection,n=a.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<ew&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),E(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:gr(n)}}),t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(_t(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});let r=rm(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,zP(["init"])).pipe(Xf(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"),E(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),E(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"),E(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"),E(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"&&E(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 l;let t=this.params.source,r,a,s;switch(e){case"MPEG":{let c=t[e];Vt(c);let d=XP(Object.keys(c));Vt(d);let p=c[d];Vt(p),r=p,a="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];Vt(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":{let c=t[e];Vt(c),r=c.url,a="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];Vt(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];Vt(c),r=re(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:Zf.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return gr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,a);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return em(o)&&(n.metadata.title=o),em(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((a,s)=>{this.loadMediaTimeoutSubscription.add(JP(im).subscribe(()=>s(`timeout(${im})`)))});(0,am.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:Zf.VIDEO_PIPELINE,message:s,thrown:a})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ri=i=>{i.removeAttribute("src"),i.load()};var sm=i=>{try{i.pause(),i.playbackRate=0,ri(i),i.remove()}catch(e){console.error(e)}};var Go=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)}},Yo=window.WeakMap?new WeakMap:new Go,ue=i=>{let e=i.querySelector("video"),t=!!e;return e?ri(e):(e=document.createElement("video"),i.appendChild(e)),Yo.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},le=i=>{let e=Yo.get(i);Yo.delete(i),e?ri(i):sm(i)};import{assertNonNullable as ii,isNonNullable as je,isNullable as aw,fromEvent as vr,merge as nm,observableFrom as om,filterChanged as um,map as ai,Subject as lm,Subscription as sw,ValueSubject as nw,ErrorCategory as ow}from"@vkontakte/videoplayer-shared";import{isNonNullable as Wo,isNullable as rw,Subscription as iw}from"@vkontakte/videoplayer-shared";var es=(i,e,t,{equal:r=(n,o)=>n===o,changed$:a,onError:s}={})=>{let n=i.getState(),o=e(),u=rw(a),l=new iw;return a&&l.add(a.subscribe(c=>{let d=i.getState();r(c,d)&&i.setState(c)},s)),r(o,n)||(t(n),u&&i.setState(n)),l.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),u&&i.setState(c.to)},s)),l},He=(i,e,t)=>es(e,()=>i.loop,r=>{Wo(r)&&(i.loop=r)},{onError:t}),ce=(i,e,t,r)=>es(e,()=>({muted:i.muted,volume:i.volume}),a=>{Wo(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}),Ie=(i,e,t,r)=>es(e,()=>i.playbackRate,a=>{Wo(a)&&(i.playbackRate=a)},{changed$:t,onError:r}),dt=es;var uw=i=>["__",i.language,i.label].join("|"),lw=(i,e)=>{if(i.id===e)return!0;let[t,r,a]=e.split("|");return i.language===r&&i.label===a},Qo=class i{constructor(){this.available$=new lm;this.current$=new nw(void 0);this.error$=new lm;this.subscription=new sw;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:ow.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(dt(t.internalTextTracks,()=>Object.values(this.internalTracks),s=>{je(s)&&this.setInternal(s)},{equal:(s,n)=>je(s)&&je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ai(s=>s.filter(({type:n})=>n==="internal"))),onError:a})),this.subscription.add(dt(t.externalTextTracks,()=>Object.values(this.externalTracks),s=>{je(s)&&this.setExternal(s)},{equal:(s,n)=>je(s)&&je(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(ai(s=>s.filter(({type:n})=>n==="external"))),onError:a})),this.subscription.add(dt(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(dt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ii(this.video);let{textTracks:e}=this.video;this.subscription.add(vr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(nm(vr(e,"addtrack"),vr(e,"removetrack"),om(["init"])).pipe(ai(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),um((r,a)=>r.length===a.length&&r.every(({id:s},n)=>s===a[n].id))).subscribe(this.available$)),this.subscription.add(nm(vr(e,"change"),om(["init"])).pipe(ai(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),ai(r=>r&&this.htmlTextTrackToITextTrack(r).id),um()).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(vr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let a=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.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(vr(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;je(t.align)&&(a.align=t.align),je(t.position)&&(a.position=t.position),je(t.size)&&(a.size=t.size),je(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){ii(this.video);let t=[...this.video.textTracks];return e?t:t.filter(i.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u;let{language:t,label:r}=e,a=e.id?e.id:uw(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:(u=this.internalTracks.get(a))==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(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:a,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===a&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(a=>a.id===r)).forEach(([,r])=>this.detach(r))}select(e){ii(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(aw(e)||!lw(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(let e of Array.from(this.video.getElementsByTagName("track"))){let t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){ii(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){ii(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Ee=Qo;var Je=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 cm=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},zo=i=>{let e=cm(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},dm=i=>{let e=cm(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};import{fromEvent as xe,map as pt,merge as hm,filterChanged as dw,isNonNullable as fm,Subject as pw,filter as mm,mapTo as bm,combine as hw,once as fw,ErrorCategory as mw,ValueSubject as gm,getCurrentBrowser as bw,CurrentClientBrowser as gw}from"@vkontakte/videoplayer-shared";var cw=3,pm=(i,e,t=cw)=>{let r=0,a=0;for(let s=0;s<i.length;s++){let n=i.start(s),o=i.end(s);if(n<=e&&e<=o){if(r=n,a=o,!t)return{from:r,to:a};for(let u=s-1;u>=0;u--)i.end(u)+t>=r&&(r=i.start(u));for(let u=s+1;u<i.length;u++)i.start(u)-t<=a&&(a=i.end(u))}}return{from:r,to:a}};var de=i=>{let e=y=>xe(i,y).pipe(bm(void 0)),r=hm(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>xe(i,y))).pipe(pt(y=>y.type==="ended"?i.readyState<2:i.readyState<3),dw()),a=hm(xe(i,"progress"),xe(i,"timeupdate")).pipe(pt(()=>pm(i.buffered,i.currentTime))),n=bw().browser===gw.Safari?hw({play:e("play").pipe(fw()),playing:e("playing")}).pipe(bm(void 0)):e("playing"),o=xe(i,"volumechange").pipe(pt(()=>({muted:i.muted,volume:i.volume}))),u=xe(i,"ratechange").pipe(pt(()=>i.playbackRate)),l=xe(i,"error").pipe(mm(()=>!!(i.error||i.played.length)),pt(()=>{var T;let y=i.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:mw.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(T=i.error)!=null?T:void 0}})),c=xe(i,"timeupdate").pipe(pt(()=>i.currentTime)),d=new pw,p=.3,h;c.subscribe(y=>{i.loop&&fm(h)&&fm(y)&&h>=i.duration-p&&y<=p&&d.next(h),h=y});let f=xe(i,"enterpictureinpicture"),b=xe(i,"leavepictureinpicture"),v=new gm(dm(i));f.subscribe(()=>v.next(!0)),b.subscribe(()=>v.next(!1));let S=new gm(zo(i));return xe(i,"fullscreenchange").pipe(pt(()=>zo(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(mm(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:d,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:xe(i,"durationchange").pipe(pt(()=>i.duration)),isBuffering$:r,currentBuffer$:a,volumeState$:o,playbackRateState$:u,inPiP$:v,inFullscreen$:S}};import{VideoQuality as ht}from"@vkontakte/videoplayer-shared";var ft=i=>{switch(i){case"mobile":return ht.Q_144P;case"lowest":return ht.Q_240P;case"low":return ht.Q_360P;case"sd":case"medium":return ht.Q_480P;case"hd":case"high":return ht.Q_720P;case"fullhd":case"full":return ht.Q_1080P;case"quadhd":case"quad":return ht.Q_1440P;case"ultrahd":case"ultra":return ht.Q_2160P}};var eu=Fe(ts(),1);import{isNonNullable as mt,isNullable as Jo,now as Rm,isHigher as Xo,isHigherOrEqual as Am,isInvariantQuality as km,isLower as Zo,isLowerOrEqual as ww,videoSizeToQuality as Aw,assertNotEmptyArray as kw}from"@vkontakte/videoplayer-shared";var Ko=!1,Xe={},xm=i=>{Ko=i},Pm=()=>{Xe={}},wm=i=>{i(Xe)},si=(i,e)=>{var t;Ko&&(Xe.meta=(t=Xe.meta)!=null?t:{},Xe.meta[i]=e)},ae=class{constructor(e){this.name=e}next(e){var r,a;if(!Ko)return;Xe.series=(r=Xe.series)!=null?r:{};let t=(a=Xe.series[this.name])!=null?a:[];t.push([Date.now(),e]),Xe.series[this.name]=t}};var Rw=new ae("best_bitrate"),Lw=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t,rs=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Rm()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},$w='Assertion "ABR Tracks is empty array" failed',Cw=(i,{container:e,throughput:t,tuning:r,limits:a,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,droppedVideoMaxQualityLimit:c,abrLogger:d})=>{var H,L,w,U,z;kw(i,$w);let p=r.usePixelRatio&&(H=window.devicePixelRatio)!=null?H:1,h=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*r.containerSizeFactor,height:e.height*p*r.containerSizeFactor},f=h&&Aw(h),b=r.considerPlaybackRate&&mt(o)?o:1,v=i.filter(k=>!km(k.quality)).sort((k,x)=>Xo(k.quality,x.quality)?-1:1),S=(L=(0,eu.default)(v,-1))==null?void 0:L.quality,g=(w=(0,eu.default)(v,0))==null?void 0:w.quality,y=Jo(a)||mt(a.min)&&mt(a.max)&&Zo(a.max,a.min)||mt(a.min)&&g&&Xo(a.min,g)||mt(a.max)&&S&&Zo(a.max,S),T=b*Lw(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),I={},D=v.filter(k=>(f?Zo(k.quality,f):!0)?(mt(t)&&isFinite(t)&&mt(k.bitrate)?t-s>=k.bitrate*T:!0)?r.lazyQualitySwitch&&mt(r.minBufferToSwitchUp)&&u&&!km(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Xo(k.quality,u.quality)?(I[k.quality]="Buffer",!1):!!c&&Am(k.quality,c)?(I[k.quality]="DroppedFramesLimit",!1):y||(Jo(a.max)||ww(k.quality,a.max))&&(Jo(a.min)||Am(k.quality,a.min))?!0:(I[k.quality]="FitsQualityLimits",!1):(I[k.quality]="FitsThroughput",!1):(I[k.quality]="FitsContainer",!1))[0];D&&D.bitrate&&Rw.next(D.bitrate);let $=(U=D!=null?D:v[Math.ceil((v.length-1)/2)])!=null?U:i[0];$.quality!==((z=l==null?void 0:l.last)==null?void 0:z.quality)&&d({message:`
7
7
  [available tracks]
8
- ${i.map(A=>`{ id: ${A.id}, quality: ${A.quality}, bitrate: ${A.bitrate} }`).join(`
8
+ ${i.map(k=>`{ id: ${k.id}, quality: ${k.quality}, bitrate: ${k.bitrate} }`).join(`
9
9
  `)}
10
10
 
11
11
  [tuning]
12
- ${Object.entries(r!=null?r:{}).map(([A,x])=>`${A}: ${x}`).join(`
12
+ ${Object.entries(r!=null?r:{}).map(([k,x])=>`${k}: ${x}`).join(`
13
13
  `)}
14
14
 
15
15
  [limit params]
@@ -27,14 +27,14 @@ var mv=Object.create;var zs=Object.defineProperty,bv=Object.defineProperties,gv=
27
27
  minQualityLimit: ${a==null?void 0:a.min},
28
28
 
29
29
  [limited tracks]
30
- ${Object.entries(I).map(([A,x])=>`${A}: ${x}`).join(`
30
+ ${Object.entries(I).map(([k,x])=>`${k}: ${x}`).join(`
31
31
  `)||"All tracks are available"}
32
32
 
33
33
  [best track] ${D==null?void 0:D.quality}
34
34
  [selected track] ${$==null?void 0:$.quality}
35
- `});let _=$&&l&&l.history[$.id]&&Pm()-l.history[$.id]<=r.trackCooldown&&(!l.last||$.id!==l.last.id);if($!=null&&$.id&&l&&!_&&l.recordSelection($),_&&(l!=null&&l.last)){let A=l.last;return l==null||l.recordSwitch(A),d({message:`
36
- [last selected] ${A==null?void 0:A.quality}
37
- `}),A}return l==null||l.recordSwitch($),$},bt=Ak;var Z=i=>new URL(i).hostname;import{assertNever as $m,assertNonNullable as Cm,combine as Qk,debounce as zk,ErrorCategory as Dm,filter as Kk,filterChanged as Jk,isNonNullable as ru,map as ss,merge as Mm,observableFrom as Xk,Subscription as Zk,ValueSubject as iu,videoQualityToHeight as ew,videoSizeToQuality as tw}from"@vkontakte/videoplayer-shared";var km=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"))},pe=i=>R(void 0,null,function*(){let e=i.muted;try{yield i.play()}catch(t){if(!km(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return km(r)&&(i.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as rs,isNullable as $k,assertNonNullable as oi}from"@vkontakte/videoplayer-shared";import{isNonNullable as wm,assertNonNullable as ts,now as Rk}from"@vkontakte/videoplayer-shared";function ee(){return Rk()}function Xo(i){return ee()-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,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Am(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Sr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,v=()=>{if(u)return;ts(c);let k=Xo(c),U;if(k<b){U=b-k,setTimeout(v,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,O()},S=k=>(s=k,L),g=k=>(d=k,L),y=()=>(h="json",L),T=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},I=k=>(p=k,L),O=()=>{c=ee(),n=new a,n.open("get",i);let k=0,U,z=0,A=()=>(ts(c),Math.max(c,Math.max(U||0,z||0)));if(s&&n.addEventListener("progress",x=>{let q=ee();s.updateChunk&&x.loaded>k&&(s.updateChunk(A(),x.loaded-k),k=x.loaded,U=q)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;ts(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let q=n.response.byteLength-k;q&&s.updateChunk&&s.updateChunk(A(),q)}n.responseType==="json"&&!Object.values(n.response).length?T():(d&&d(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),p){let x=()=>{ts(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(z=ee(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),L},L={withBitrateReporting:S,withParallel:I,withJSONResponse:y,withRetryCount:k=>(l=k,L),withRetryInterval:(k,U)=>(wm(k)&&(b=k),wm(U)&&(f=U),L),withTimeout:k=>(o=k,L),withFinally:g,send:O,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return L}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 u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&r>0){let s=a*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var 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=ee(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ee()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Sr(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ee()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ee();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){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 is=1e4,eu=3;var Ck=6e4,Dk=10,Mk=1,Ok=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||rs(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=()=>{Am(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,is,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let T=s&&(!c||c===this.rep);return T||t("Not running!"),T},p=(T,I,O)=>{u&&u.abort(),u=Sr(this.urlResolver.resolve(T,!1),I,O,()=>this._retryCallback()).withTimeout(is).withBitrateReporting(this.bitrateSwitcher).withRetryCount(eu).withFinally(()=>{u=null}).send()},h=(T,I,O)=>{oi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),I,O,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=T=>{let I=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${I}=>${T}`),r.playbackRate=T)},b=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let O=ee()-1e4,D=0;for(let _=0;_<this.bufferStates.length;_++){let H=this.bufferStates[_];T=Math.min(T,H.buf),H.ts<O&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${T} drop=${D} jitter=${this.sourceJitter}`);let $=T-Mk;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},S=T=>{let I,O=()=>I&&I.start?I.start.length:0,D=x=>I.start[x]/1e3,$=x=>I.dur[x]/1e3,_=x=>I.fragIndex+x,H=(x,q)=>({chunkIdx:_(x),startTS:D(x),dur:$(x),discontinuity:q}),L=()=>{let x=0;if(I&&I.dur){let q=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,K=q;this.sourceJitter>1&&(K+=this.sourceJitter-1);let ie=I.dur.length-1;for(;ie>=0&&(K-=I.dur[ie],!(K<=0));--ie);x=Math.min(ie,I.dur.length-1-Y),x=Math.max(x,0)}return H(x,!0)},k=x=>{let q=O();if(!(q<=0)){if(rs(x)){for(let Y=0;Y<q;Y++)if(D(Y)>x)return H(Y)}return L()}},U=x=>{let q=O(),Y=x?x.chunkIdx+1:0,K=Y-I.fragIndex;if(!(q<=0)){if(!x||K<0||K-q>Dk)return t(`Resync: offset=${K} bChunks=${q} chunk=`+JSON.stringify(x)),L();if(!(K>=q))return H(Y-I.fragIndex,!1)}},z=(x,q,Y)=>{l&&l.abort(),l=Sr(this.urlResolver.resolve(x,!0,this.lowLatency),q,Y,()=>this._retryCallback()).withTimeout(is).withRetryCount(eu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,q)=>{z(T,Y=>{if(!d())return;I=Y;let K=!!I.lowLatency;K!==this.lowLatency&&b(K);let ie=0;for(let Ye=0;Ye<I.dur.length;++Ye)ie+=I.dur[Ye];ie>0&&(oi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/I.dur.length)),a({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,x(k(q))},()=>this._handleNetworkError())},nextChunk:U}},g=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),oi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{let{videoElement:I,logger:O}=this.params,D=S(e.jidxUrl),$,_,H,L,k=0,U,z,A,x=()=>{U&&(clearTimeout(U),U=void 0);let N=Math.max(Ok,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),se=k+N,he=ee(),Se=Math.min(1e4,se-he);k=he;let nt=()=>{l||d()&&D.seek(()=>{d()&&(k=ee(),q(),x())})};Se>0?U=window.setTimeout(()=>{this.paused?x():nt()},Se):nt()},q=()=>{let N;for(;N=D.nextChunk(L);)L=N,Zi(N);let se=D.nextChunk(H);if(se){if(H&&se.discontinuity){O("Detected discontinuity; restarting playback"),this.paused?x():(g(),this._initPlayerWith(e));return}Ye(se)}else x()},Y=(N,se)=>{if(!d()||!this.sourceBuffer)return;let he,Se,nt,Jt=ot=>{window.setTimeout(()=>{d()&&Y(N,se)},ot)};if(this.sourceBuffer.updating)O("Source buffer is updating; delaying appendBuffer"),Jt(100);else{let ot=ee(),Et=I.currentTime;!this.paused&&I.buffered.length>1&&z===Et&&ot-A>500&&(O("Stall suspected; trying to fix"),this._fixupStall()),z!==Et&&(z=Et,A=ot);let Xt=this._getBufferSizeSec();if(Xt>30)O(`Buffered ${Xt} seconds; delaying appendBuffer`),Jt(2e3);else try{this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(this.bufferStates.push({ts:ot,buf:Xt}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),se&&se()}catch(Cr){if(Cr.name==="QuotaExceededError")O("QuotaExceededError; delaying appendBuffer"),nt=this.sourceBuffer.buffered.length,nt!==0&&(he=this.sourceBuffer.buffered.start(0),Se=Et,Se-he>4&&this.sourceBuffer.remove(he,Se-3)),Jt(1e3);else throw Cr}}},K=()=>{_&&$&&(O([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(H)]),Y(_,function(){_=null,q()}))},ie=N=>e.fragUrlTemplate.replace("%%id%%",N.chunkIdx),Ye=N=>{d()&&h(ie(N),(se,he)=>{if(d()){if(he/=1e3,_=se,H=N,n=N.startTS,he){let Se=Math.min(10,N.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Se:Se}K()}},()=>this._handleNetworkError())},Zi=N=>{d()&&(oi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(N),!1)))},$r=N=>{d()&&(e.cachedHeader=N,Y(N,()=>{$=!0,K()}))};s=!0,D.seek(N=>{if(d()){if(k=ee(),!N){x();return}L=N,!$k(T)||N.startTS>T?Ye(N):(H=N,q())}},T),e.cachedHeader?$r(e.cachedHeader):p(e.headerUrl,$r,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),rs(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 rs(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(p,h)=>{let f=ee();if(this.chunkRateEstimator.addInterval(p,f,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&Xo(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ee();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Sr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(is).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;pe(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((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Ck))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Bk,filter as Rm,fromEvent as Vk,interval as _k,isHigher as Nk,isInvariantQuality as Fk,isLower as qk,merge as Uk,Subject as Lm,Subscription as Hk}from"@vkontakte/videoplayer-shared";var tu=class{constructor(){this.onDroopedVideoFramesLimit$=new Lm;this.subscription=new Hk;this.playing=!1;this.tracks=[];this.forceChecker$=new Lm;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&&!Fk(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&&Nk(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.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(Vk(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=_k(this.droppedFramesChecker.checkTime).pipe(Rm(()=>this.playing),Rm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(Bk(this.droppedFramesChecker.checkTime)),r=Uk(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])=>qk(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}},as=tu;import{map as jk,Observable as Gk}from"@vkontakte/videoplayer-shared";import{fromEvent as Yk}from"@vkontakte/videoplayer-shared";var li=()=>{var i;return!!((i=window.documentPictureInPicture)!=null&&i.window)||!!document.pictureInPictureElement};var Wk=(i,e)=>new Gk(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||li()))},w(w({},r),e));a.observe(i);let s=Yk(document,"visibilitychange").pipe(jk(n=>!document.hidden||li())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Pe=Wk;var rw=["paused","playing","ready"],iw=["paused","playing","ready"],ci=class{constructor(e){this.subscription=new Zk;this.videoState=new C("stopped");this.representations$=new iu([]);this.textTracksManager=new Ee;this.droppedFramesManager=new as;this.maxSeekBackTime$=new iu(1/0);this.zeroTime$=new iu(void 0);this.liveOffset=new Je;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:Dm.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=ft(u.name))!=null?r:tw(u.video),d=u.bitrate/1e3,p=w({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((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:u})=>u===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(iw.includes(e)&&(n||o)){this.prepare();return}if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&rw.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(re(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=a==null?void 0:a.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(re(this.params.source.url,u))}return;default:return $m(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Dm.WTF,message:"DashLiveProvider internal logic error",thrown:a})};Mm(this.videoState.stateChangeStarted$.pipe(ss(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ss(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ue(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(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=de(this.video);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$:this.representations$.pipe(ss(a=>a.map(({track:s})=>s)))}),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(Jk(),ss(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(Qk({zeroTime:this.zeroTime$.pipe(Kk(ru)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(He(this.video,this.params.desiredState.isLooped,t)).add(ce(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ie(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(Pe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&ew(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 $m(a.to)}},t)).add(Mm(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Xk(["init"])).pipe(zk(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),le(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 l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.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:bt(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,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:v})=>v.id===s))==null?void 0:f.representation;Cm(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;Cm(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(re(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Om=ci;var gt=(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 IA,assertNonNullable as zb,debounce as EA,ErrorCategory as ku,filter as xA,filterChanged as Kb,fromEvent as PA,isLowerOrEqual as Jb,isNonNullable as kA,videoSizeToQuality as Xb,map as wu,merge as vs,observableFrom as wA,observeElementSize as AA,once as RA,Subscription as LA,ValueSubject as Zb}from"@vkontakte/videoplayer-shared";var ns=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}},yr=class extends ns{constructor(){super(),this.listeners||ns.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 yr,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",yr.prototype[Symbol.toStringTag]="AbortSignal");function os(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(!os({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var pi=os({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Bm=pi?au({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=pi?Bm.fetch:window.fetch,F0=pi?Bm.Request:window.Request,et=pi?di:window.AbortController,q0=pi?yr:window.AbortSignal;var Yb=Fe(_a(),1);var hi=(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};import{abortable as Eu,assertNonNullable as Yt,combine as qb,ErrorCategory as St,filter as hs,filterChanged as mA,fromEvent as wr,interval as xu,isNonNullable as Ub,map as Pu,merge as Ar,Subject as Hb,Subscription as jb,tap as bA,throttle as gA,ValueSubject as ge}from"@vkontakte/videoplayer-shared";var kr=Fe(Za(),1);var aw=(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)},sw=i=>window.clearTimeout(i),Vm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",su=Vm?aw:window.requestIdleCallback,j0=Vm?sw:window.cancelIdleCallback;var Cb=Fe(Ka(),1);import{assertNever as nw,CurrentClientBrowser as ow,ErrorCategory as _m,getCurrentBrowser as uw,Subject as Nm}from"@vkontakte/videoplayer-shared";var lw=16,Um=!1,Fm,qm;try{Um=uw().browser===ow.Safari&&parseInt((qm=(Fm=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:Fm[1])!=null?qm:"",10)<=lw}catch(i){console.error(i)}var nu=class{constructor(e){this.bufferFull$=new Nm;this.error$=new Nm;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:_m.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})})}remove(e,t,r){return R(this,null,function*(){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()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let r;Um&&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:_m.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:nw(t)}}},Hm=nu;var ou=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 xr,assertNever as oA,assertNonNullable as tt,ErrorCategory as Pr,fromEvent as vu,getExponentialDelay as Su,once as uA,isNonNullable as $b,isNullable as rt,Subject as lA,Subscription as cA,ValueSubject as Oi}from"@vkontakte/videoplayer-shared";var F=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Tr=class extends F{};var fi=class extends F{};var mi=class extends F{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 bi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var gi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var vi=class extends F{constructor(t,r){super(t,r);this.data=this.content}};var W=class extends F{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Nt=class extends W{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,u=this.readUint32();s=this.readUint32();let l=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:u,SAPType:l,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var Si=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var yi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends W{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 Ii=class extends W{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var Ei=class extends W{constructor(t,r){super(t,r);this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var xi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Pi=class extends W{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 ki=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ai=class extends W{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var Ri=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Li=class extends W{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 $i=class extends W{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 Ci=class extends W{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 dw={ftyp:mi,moov:bi,moof:gi,mdat:vi,sidx:Nt,trak:Si,mdia:xi,mfhd:Ai,tkhd:Pi,traf:Ri,tfhd:Li,tfdt:$i,trun:Ci,minf:ki,sv3d:yi,st3d:Ti,prhd:Ii,proj:wi,equi:Ei,uuid:fi,unknown:Tr},Ft=class i{constructor(e={}){this.options=w({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=dw[e];return r?new r(t,new i):new Tr(t,new i)}};var Ir=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 hw=new TextDecoder("ascii"),fw=i=>hw.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",mw=i=>{let e=new Nt(i,new Ft),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})},bw=(i,e)=>{let r=new Ft().parse(i),a=new Ir(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,d)},gw=(i,e)=>{let r=new Ft().parse(i),s=new Ir(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},vw=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 Ft().parse(i),a=new Ir(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},jm={validateData:fw,parseInit:vw,getIndexRange:()=>{},parseSegments:mw,parseFeedableSegmentChunk:bw,getSegmentEndTime:gw};import{assertNonNullable as lu,isNonNullable as Qm,isNullable as yw}from"@vkontakte/videoplayer-shared";import{assertNever as Sw}from"@vkontakte/videoplayer-shared";var Gm={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"}},Ym=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 Gm,s=a?Gm[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,c=Di(u),d=l*Ne(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)*Ne(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Ne(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Ne(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},Oe=(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:Sw(e)}},qt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Ym(r);if(!e(a))return;a.type==="master"&&qt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Wm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Ym(i);return qt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Oe(o,n):s===17026?t=Oe(o,n):s===17029&&(r=Oe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var zm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],Tw=[231,22612,22743,167,171,163,160,175],Iw=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return qt(i,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let v=Oe(f,h);l=Di(v)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Oe(f,h):p===17545?a=Oe(f,h):p===21420&&l===475249515?u=Oe(f,h):p===374648427?qt(f,({tag:v,type:S,value:g})=>v===30321?(c=Oe(g,S)===1,!1):!0):s&&n&&zm.includes(p)&&(o=!0),!o}),lu(e,"Failed to parse webm Segment start"),lu(t,"Failed to parse webm Segment end"),lu(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:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Ew=i=>{if(yw(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},xw=(i,e)=>{let t=!1,r=!1,a=o=>Qm(o.time)&&Qm(o.position),s=[],n;return qt(i,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Oe(l,u));break;case 183:break;case 241:n&&(n.position=Oe(l,u));break;default:t&&zm.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},Pw=i=>{let e=0,t=!1;try{qt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Tw.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},Km={validateData:Wm,parseInit:Iw,getIndexRange:Ew,parseSegments:xw,parseFeedableSegmentChunk:Pw};var fu=Fe(yb(),1);import{isNonNullable as Ib,isNullable as Eb}from"@vkontakte/videoplayer-shared";var Tb=i=>{if(i.includes("/")){let e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var xb=i=>{if(!i.startsWith("P"))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=(r==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},Ut=(i,e)=>{let t=i;t=(0,fu.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,fu.default)(t,n,(o,u)=>Eb(s)?o:Eb(u)?s:s.padStart(parseInt(u,10),"0"))}return t},kb=(i,e)=>{var T,I,O,D,$,_,H,L,k,U,z,A,x,q,Y,K,ie,Ye,Zi,$r,N,se,he,Se,nt,Jt,ot,Et,Xt,Cr,Hu,ju,Gu,Yu,Wu,Qu,zu,Ku,Ju,Xu,Zu,el;let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(O=(I=(T=s.querySelector("BaseURL"))==null?void 0:T.textContent)==null?void 0:I.trim())!=null?O:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],v=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=xb(h);else if(f){let ye=xb(f);Ib(ye)&&(p=ye)}else v&&(p=parseInt(v,10));let S=0,g=($=(D=s.getAttribute("profiles"))==null?void 0:D.split(","))!=null?$:[],y=g.includes("urn:webm:dash:profile:webm-on-demand:2012")||g.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let ye of u){let ea=ye.getAttribute("mimeType"),tv=ye.getAttribute("codecs"),tl=(_=ye.getAttribute("contentType"))!=null?_:ea==null?void 0:ea.split("/")[0],rv=(L=(H=ye.getAttribute("profiles"))==null?void 0:H.split(","))!=null?L:[],rl=ye.querySelectorAll("Representation"),iv=ye.querySelector("SegmentTemplate");if(tl==="text"){for(let Q of rl){let ut=Q.getAttribute("id")||"",ta=ye.getAttribute("lang"),Zt=ye.getAttribute("label"),Ns=(z=(U=(k=Q.querySelector("BaseURL"))==null?void 0:k.textContent)==null?void 0:U.trim())!=null?z:"",Fs=new URL(Ns||o,e).toString(),ra=ut.includes("_auto");a.text.push({id:ut,lang:ta,label:Zt,isAuto:ra,kind:"text",url:Fs})}continue}for(let Q of rl){let ut=(A=Q.getAttribute("mimeType"))!=null?A:ea,ta=(q=(x=Q.getAttribute("codecs"))!=null?x:tv)!=null?q:"",Zt=(K=(Y=Q.getAttribute("contentType"))!=null?Y:ut==null?void 0:ut.split("/")[0])!=null?K:tl,Ns=(Ye=(ie=ye.getAttribute("profiles"))==null?void 0:ie.split(","))!=null?Ye:[],Fs=parseInt((Zi=Q.getAttribute("width"))!=null?Zi:"",10),ra=parseInt(($r=Q.getAttribute("height"))!=null?$r:"",10),il=parseInt((N=Q.getAttribute("bandwidth"))!=null?N:"",10)/1e3,al=(se=Q.getAttribute("frameRate"))!=null?se:"",av=(he=Q.getAttribute("quality"))!=null?he:void 0,sv=al?Tb(al):void 0,nv=(Se=Q.getAttribute("id"))!=null?Se:(S++).toString(10),ov=Zt==="video"?`${ra}p`:Zt==="audio"?`${il}Kbps`:ta,uv=`${nv}@${ov}`,lv=(ot=(Jt=(nt=Q.querySelector("BaseURL"))==null?void 0:nt.textContent)==null?void 0:Jt.trim())!=null?ot:"",sl=new URL(lv||o,e).toString(),cv=[...g,...rv,...Ns],qs,dv=Q.querySelector("SegmentBase"),xt=(Et=Q.querySelector("SegmentTemplate"))!=null?Et:iv;if(dv){let Pt=(Cr=(Xt=Q.querySelector("SegmentBase Initialization"))==null?void 0:Xt.getAttribute("range"))!=null?Cr:"",[kt,Hs]=Pt.split("-").map(er=>parseInt(er,10)),lt={from:kt,to:Hs},Dr=(Hu=Q.querySelector("SegmentBase"))==null?void 0:Hu.getAttribute("indexRange"),[js,ia]=Dr?Dr.split("-").map(er=>parseInt(er,10)):[],Mr=Dr?{from:js,to:ia}:void 0;qs={type:"byteRange",url:sl,initRange:lt,indexRange:Mr}}else if(xt){let Pt={representationId:(ju=Q.getAttribute("id"))!=null?ju:void 0,bandwidth:(Gu=Q.getAttribute("bandwidth"))!=null?Gu:void 0},kt=parseInt((Yu=xt.getAttribute("timescale"))!=null?Yu:"",10),Hs=(Wu=xt.getAttribute("initialization"))!=null?Wu:"",lt=xt.getAttribute("media"),Dr=(zu=parseInt((Qu=xt.getAttribute("startNumber"))!=null?Qu:"",10))!=null?zu:1,js=Ut(Hs,Pt);if(!lt)throw new ReferenceError("No media attribute in SegmentTemplate");let ia=(Ku=xt.querySelectorAll("SegmentTimeline S"))!=null?Ku:[],Mr=[],er=0,Gs="",Ys=0;if(ia.length){let aa=Dr,Re=0;for(let tr of ia){let _e=parseInt((Ju=tr.getAttribute("d"))!=null?Ju:"",10),wt=parseInt((Xu=tr.getAttribute("r"))!=null?Xu:"",10)||0,sa=parseInt((Zu=tr.getAttribute("t"))!=null?Zu:"",10);Re=Number.isFinite(sa)?sa:Re;let Ws=_e/kt*1e3,Qs=Re/kt*1e3;for(let na=0;na<wt+1;na++){let hv=Ut(lt,B(w({},Pt),{segmentNumber:aa.toString(10),segmentTime:(Re+na*_e).toString(10)})),nl=(Qs!=null?Qs:0)+na*Ws,fv=nl+Ws;aa++,Mr.push({time:{from:nl,to:fv},url:hv})}Re+=(wt+1)*_e,er+=(wt+1)*Ws}Ys=Re/kt*1e3,Gs=Ut(lt,B(w({},Pt),{segmentNumber:aa.toString(10),segmentTime:Re.toString(10)}))}else if(Ib(p)){let Re=parseInt((el=xt.getAttribute("duration"))!=null?el:"",10)/kt*1e3,tr=Math.ceil(p/Re),_e=0;for(let wt=1;wt<tr;wt++){let sa=Ut(lt,B(w({},Pt),{segmentNumber:wt.toString(10),segmentTime:_e.toString(10)}));Mr.push({time:{from:_e,to:_e+Re},url:sa}),_e+=Re}Ys=_e,Gs=Ut(lt,B(w({},Pt),{segmentNumber:tr.toString(10),segmentTime:_e.toString(10)}))}let pv={time:{from:Ys,to:1/0},url:Gs};qs={type:"template",baseUrl:sl,segmentTemplateUrl:lt,initUrl:js,totalSegmentsDurationMs:er,segments:Mr,nextSegmentBeyondManifest:pv,timescale:kt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Zt||!ut)continue;let Us={video:"video",audio:"audio",text:"text"}[Zt];Us&&a[Us].push({id:uv,kind:Us,segmentReference:qs,profiles:cv,duration:p,bitrate:il,mime:ut,codecs:ta,width:Fs,height:ra,fps:sv,quality:av})}}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,container:y,representations:a}};var bu=Fe(Za(),1);import{videoSizeToQuality as nA}from"@vkontakte/videoplayer-shared";var wb=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{var o;let n=(o=s?ft(s):void 0)!=null?o:nA({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Ab=({id:i,bitrate:e})=>({id:i,bitrate:e}),Rb=(i,e,t)=>{var a;let r=e.indexOf(t);return(a=(0,bu.default)(i,Math.round(i.length*r/e.length)))!=null?a:(0,bu.default)(i,-1)},Lb=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),gu=i=>"url"in i,Ht=i=>i.type==="template",Mi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Bi=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:l=!1,manifest:c}){this.currentSegmentLength$=new Oi(0);this.onLastSegment$=new Oi(!1);this.fullyBuffered$=new Oi(!1);this.playingRepresentation$=new Oi(void 0);this.playingRepresentationInit$=new Oi(void 0);this.error$=new lA;this.gaps=[];this.subscription=new cA;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new et;this.destroyAbortController=new et;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=xr(this.destroyAbortController.signal,function(e){return J(this,null,function*(){let t=this.representations.get(e);tt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Hm(this.sourceBuffer),this.subscription.add(vu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:Pr.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(vu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Pr.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,ou(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);tt(r,"No init buffer for starting representation"),tt(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=xr(this.destroyAbortController.signal,function(e){return J(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);tt(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(rt(a)||rt(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),tt(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();$b(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))})}.bind(this));this.seekLive=xr(this.destroyAbortController.signal,function(e){return J(this,null,function*(){var o;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let u of this.representations.keys()){let l=e.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!Ht(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let t=(o=this.switchingToRepresentationId)!=null?o:this.downloadingRepresentationId,r=this.representations.get(t);tt(r);let a=this.segments.get(t);tt(a,"No segments for starting representation");let s=this.initData.get(t);if(tt(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));switch(this.fetcher=s,this.tuning=n,this.compatibilityMode=l,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(c!=null&&c.dynamic),this.container=r,r){case"mp4":this.containerParser=jm;break;case"webm":this.containerParser=Km;break;default:oA(r)}this.initData=new Map(a.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(d=>[d.id,d])),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 et,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(rt(e)||rt(this.downloadingRepresentationId)||rt(this.playingRepresentationId)||rt(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(tt(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=a==null?void 0:a.time.to)!=null?l:0)-((c=a==null?void 0:a.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=gt(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)&&ou(this.sourceBuffer.buffered)>=this.bufferLimit){let d=gt(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,kr.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&&gt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,kr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}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;$b(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.representations[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 t,r,a,s;for(let n of(t=e==null?void 0:e.representations[this.kind].values())!=null?t:[]){if(!n||!Ht(n.segmentReference))return;let o=n.segmentReference.segments.map(d=>B(w({},d),{status:"none",size:void 0})),u=(r=this.segments.get(n.id))!=null?r:[],l=(s=(a=(0,kr.default)(u,-1))==null?void 0:a.time.to)!=null?s:0,c=o==null?void 0:o.findIndex(d=>Math.floor(l)>=Math.floor(d.time.from)&&Math.floor(l)<=Math.floor(d.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,d)}else{let d=o.slice(c+1);this.segments.set(n.id,[...u,...d])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(let r of this.representations.values()){let a=r.segmentReference;if(!Ht(a))return;let s=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),n=Ut(a.segmentTemplateUrl,{segmentTime:s}),o=(t=this.segments.get(r.id))!=null?t:[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));u&&(u.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(u=>u.time.from<=e&&u.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}},f)=>{let b=p<=r&&h>=r,v=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&v&&g&&this.sourceBuffer&&!hi(this.sourceBuffer.buffered,r))&&v&&g});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return R(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return R(this,null,function*(){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield xr(o,function(){return J(this,null,function*(){let c=Su(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(this.isActiveLowLatency()){let p=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,p)}u&&a.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Mi(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return R(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield xr(n,function(){return J(this,null,function*(){let u=Su(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),vu(window,"online").pipe(uA()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Mi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(Ht(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,kr.default)(e,0).byte.from,to:(0,kr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Pr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ht(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Pr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){a();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=this.containerParser.parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.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 u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:l;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,v=p?d.byte.to-r:e.byteLength,S=b<a,g=v<=a;if(d.status==="downloading"&&S&&g){d.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(y,s).then(T=>T&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(h,a-b),c.loadedBytes>c.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===h?y:this.containerParser.parseFeedableSegmentChunk(y);T!=null&&T.byteLength&&(d.status="partially_fed",c.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,s).then(I=>{if(s.aborted)n();else if(I)c.fedBytes+=T.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",gu(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=su(()=>(0,Cb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return R(this,null,function*(){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?xr(this.destroyAbortController.signal,function(){return J(this,null,function*(){let o=Su(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(o=>R(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ht(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Pr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||rt(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=gu(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;a+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*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 l=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+l&&d.status==="fed"&&u(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=su(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Pr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(rt(this.sourceBuffer)||rt(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),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(l.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var Vi=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Db=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 _i,assertNever as Mb,fromEvent as Ob,merge as dA,now as yu,Subscription as pA,ValueSubject as Tu}from"@vkontakte/videoplayer-shared";var us=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new Tu(void 0);this.lastConnectionReused$=new Tu(void 0);this.lastRequestFirstBytes$=new Tu(void 0);this.abortAllController=new et;this.subscription=new pA;this.fetchManifest=_i(this.abortAllController.signal,function(e){return J(this,null,function*(){let t=e;this.requestQuic&&(t=Vi(t));let r=yield Ze(t,{signal:this.abortAllController.signal}).catch(Ni);return r?(this.onHeadersReceived(r.headers),r.text()):null})}.bind(this));this.fetch=_i(this.abortAllController.signal,function(l){return J(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var _,H;let c=e,d=new Headers;if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:Mb(t)}this.requestQuic&&(c=Vi(c));let p=this.abortAllController.signal,h;if(n){let L=new et;if(h=dA(Ob(this.abortAllController.signal,"abort"),Ob(n,"abort")).subscribe(()=>{try{L.abort()}catch(k){Ni(k)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(k){Ni(k)}p=L.signal}let f=yu(),b=yield Ze(c,{priority:s,headers:d,signal:p}).catch(Ni),v=yu();if(!b)return h==null||h.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(v-f),!b.ok||!b.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!a&&!o)return h==null||h.unsubscribe(),b.arrayBuffer();let[S,g]=b.body.tee(),y=S.getReader();o&&((H=this.throughputEstimator)==null||H.trackStream(g,u));let T=0,I=new Uint8Array(0),O=!1,D=L=>{h==null||h.unsubscribe(),O=!0,Ni(L)},$=_i(p,function(U){return J(this,arguments,function*({done:L,value:k}){if(T===0&&this.lastRequestFirstBytes$.next(yu()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&k){let z=new Uint8Array(I.length+k.length);z.set(I),z.set(k,I.length),I=z,T+=k.byteLength,a==null||a(new DataView(I.buffer),T),yield y==null?void 0:y.read().then($,D)}})}.bind(this));return yield y==null?void 0:y.read().then($,D),h==null||h.unsubscribe(),O?null:I.buffer})}.bind(this));this.fetchByteRangeRepresentation=_i(this.abortAllController.signal,function(e,t,r){return J(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(S=e.indexRange)!=null?S:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let v=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:v}})}.bind(this));this.fetchTemplateRepresentation=_i(this.abortAllController.signal,function(e,t){return J(this,null,function*(){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=>B(w({},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}=Db(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return R(this,null,function*(){var s,n;let{type:a}=e;switch(a){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Mb(a)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Ni=i=>{if(!Mi(i))throw i};var jt=(i,e,t)=>t*e+(1-t)*i,Iu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Bb=(i,e,t,r)=>{let a=0,s=t,n=Iu(i,e),o=e<r?e:r;for(let u=0;u<o;u++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as hA,ValueSubject as Vb}from"@vkontakte/videoplayer-shared";var vt=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 Vb(e.initial),this.debounced$=new Vb(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ae(`raw_${t}`),this.smoothedSeries$=new ae(`smoothed_${t}`),this.reportedSeries$=new ae(`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+=Ne(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)&&(hA(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 ls=class extends vt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=jt(this.slow,t,this.params.emaAlphaSlow),this.fast=jt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var cs=class extends vt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=Iu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=jt(this.emaSmoothed,t,this.params.emaAlpha);let a=Bb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var ds=class extends vt{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?jt(this.smoothed,t,this.params.emaAlpha):t}};var Gt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ls({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new cs({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 ds(w({initial:e,label:"liveEdgeDelay"},t))}};var _b=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var it=()=>window.ManagedMediaSource||window.MediaSource,ps=()=>{var i,e;return!!(window.ManagedMediaSource&&((e=(i=window.ManagedSourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Nb=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(i=window.SourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Fb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var Gb=["timeupdate","progress","play","seeked","stalled","waiting"];var fs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new jb;this.representationSubscription=new jb;this.state$=new C("none");this.currentVideoRepresentation$=new ge(void 0);this.currentVideoRepresentationInit$=new ge(void 0);this.currentVideoSegmentLength$=new ge(0);this.currentAudioSegmentLength$=new ge(0);this.error$=new Hb;this.lastConnectionType$=new ge(void 0);this.lastConnectionReused$=new ge(void 0);this.lastRequestFirstBytes$=new ge(void 0);this.isLive$=new ge(!1);this.liveDuration$=new ge(0);this.liveAvailabilityStartTime$=new ge(void 0);this.bufferLength$=new ge(0);this.liveLoadBufferLength$=new ge(0);this.livePositionFromPlayer$=new ge(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Hb;this.gapWatchdogActive=!1;this.destroyController=new et;this.initManifest=Eu(this.destroyController.signal,function(e,t,r){return J(this,null,function*(){var a;this.element=e,this.manifestUrlString=re(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(a=this.manifest)!=null&&a.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:St.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Eu(this.destroyController.signal,function(){return J(this,null,function*(){var a;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:St.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=kb(e!=null?e:"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:St.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;let r=({kind:s,mime:n,codecs:o})=>{var u,l,c,d;return!!((l=(u=this.element)==null?void 0:u.canPlayType)!=null&&l.call(u,n)&&((d=(c=it())==null?void 0:c.isTypeSupported)!=null&&d.call(c,`${n}; codecs="${o}"`))||s==="text")};return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((a=t.duration)!=null?a:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),B(w({},t),{representations:(0,Yb.default)(Object.entries(t.representations).map(([s,n])=>[s,n.filter(r)]))})})}.bind(this));this.initRepresentations=Eu(this.destroyController.signal,function(e,t,r){return J(this,null,function*(){var h;Yt(this.manifest),Yt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=f=>{this.representationSubscription.add(wr(f,"error").pipe(hs(b=>{var v;return!!((v=this.element)!=null&&v.played.length)})).subscribe(b=>{this.error$.next({id:"VideoSource",category:St.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?Fb():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ps())if(r){let f=document.createElement("source");a(f),f.type="application/x-mpegurl",f.src=r.url,this.element.appendChild(f)}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};if(this.videoBufferManager=new Bi("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],Ub(t)&&(this.audioBufferManager=new Bi("audio",this.source,this.manifest.container,this.manifest.representations.audio,n),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(xu(1e3).subscribe(f=>{var b;if((b=this.element)!=null&&b.paused){let v=Fo(this.manifestUrlString,2);this.manifestUrlString=re(this.manifestUrlString,v+1e3,2)}})),this.representationSubscription.add(Ar(...Gb.filter(f=>f!=="waiting").map(f=>wr(this.element,f))).pipe(Pu(f=>this.element?gt(this.element.buffered,this.element.currentTime*1e3):0),mA(),hs(f=>!!f),bA(f=>{var b;(b=this.stallWatchdogSubscription)==null||b.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(hs(b=>this.isActiveLowLatency&&!!b)).subscribe(b=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(b=>{if(!this.isActiveLowLatency)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=b-v,T=1+Math.sign(y)*g;Math.abs(y)<S?T=1:Math.abs(y)>S*2&&(T=1+Math.sign(y)*g*2),_b(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{var S,g;let v=0;if(b){let y=((g=(S=this.element)==null?void 0:S.currentTime)!=null?g:0)*1e3;v=Math.min(...this.bufferManagers.map(I=>{var O,D;return(D=(O=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:O.to)!=null?D:y}))-y}this.liveLoadBufferLength$.getValue()!==v&&this.liveLoadBufferLength$.next(v)}));let f=0;this.representationSubscription.add(qb({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(gA(1e3)).subscribe(S=>R(this,[S],function*({liveLoadBufferLength:b,bufferLength:v}){if(Yt(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,y=Fo(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),O=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,D=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=this.isActiveLowLatency?v:b,_=3;if(this.isActiveLowLatency?_=0:$<I+D&&$>=I?_=1:y!==0&&$<I&&(_=2),isFinite(b)&&(f=b>f?b:f),_===2||_===1){let H=f-(I+O),L=this.normolizeLiveOffset(Math.trunc(y+H/g)),k=Math.abs(L-y),U;!b||k<=this.tuning.dashCmafLive.offsetCalculationError?U=y:L>0&&k>this.tuning.dashCmafLive.offsetCalculationError?U=L:U=0,this.manifestUrlString=re(this.manifestUrlString,U,2)}_!==3&&_!==0&&(f=0,this.updateLive())})))}let o=Ar(...this.bufferManagers.map(f=>f.fullyBuffered$)).pipe(Pu(()=>this.bufferManagers.every(f=>f.fullyBuffered$.getValue()))),u=Ar(...this.bufferManagers.map(f=>f.onLastSegment$)).pipe(Pu(()=>this.bufferManagers.some(f=>f.onLastSegment$.getValue())));this.representationSubscription.add(Ar(this.forceEnded$,qb({allBuffersFull:o,someBufferEnded:u}).pipe(hs(({allBuffersFull:f,someBufferEnded:b})=>f&&b))).subscribe(()=>{var f;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(b=>!b.updating))try{(f=this.source)==null||f.endOfStream()}catch(b){this.error$.next({id:"EndOfStream",category:St.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:b})}})),this.representationSubscription.add(Ar(...this.bufferManagers.map(f=>f.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(f=>{var b;return(b=this.source)==null?void 0:b.addEventListener("sourceopen",f)}));let l=(h=this.manifest.duration)!=null?h:0,c=(f,b)=>{var v;return Math.max(f,(v=b.duration)!=null?v:0)},d=this.manifest.representations.audio.reduce(c,l),p=this.manifest.representations.video.reduce(c,l);(d||p)&&(this.source.duration=Math.max(d,p)/1e3),this.audioBufferManager&&Ub(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=xu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:St.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new us({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Gt.getLiveEstimatedDelaySmoothedValue(0,w({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return R(this,null,function*(){var r,a,s,n;Yt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=re(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(a=this.videoBufferManager)==null?void 0:a.seekLive((r=this.manifest)==null?void 0:r.representations.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.representations.audio))})}initBuffer(){Yt(this.element),this.state$.setState("running"),this.subscription.add(Ar(...Gb.map(e=>wr(this.element,e)),wr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:St.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(wr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(wr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&hi(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=xu(1e3).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:St.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t){return R(this,null,function*(){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,u;Yt(this.element),Yt(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),hi(this.element.buffered,r)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)==null||o.abort()),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.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)}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}updateLive(){return R(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield 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 ms=class{constructor(e,t){this.fov=e,this.orientation=t}};var bs=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/Ne(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=w({},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*Ne(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 Wb=`attribute vec2 a_vertex;
35
+ `});let _=$&&l&&l.history[$.id]&&Rm()-l.history[$.id]<=r.trackCooldown&&(!l.last||$.id!==l.last.id);if($!=null&&$.id&&l&&!_&&l.recordSelection($),_&&(l!=null&&l.last)){let k=l.last;return l==null||l.recordSwitch(k),d({message:`
36
+ [last selected] ${k==null?void 0:k.quality}
37
+ `}),k}return l==null||l.recordSwitch($),$},bt=Cw;var Z=i=>new URL(i).hostname;import{assertNever as Om,assertNonNullable as Bm,combine as Xw,debounce as Zw,ErrorCategory as Vm,filter as eA,filterChanged as tA,isNonNullable as su,map as os,merge as _m,observableFrom as rA,Subscription as iA,ValueSubject as nu,videoQualityToHeight as aA,videoSizeToQuality as sA}from"@vkontakte/videoplayer-shared";var Lm=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"))},pe=i=>R(void 0,null,function*(){let e=i.muted;try{yield i.play()}catch(t){if(!Lm(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return Lm(r)&&(i.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as as,isNullable as Ow,assertNonNullable as ui}from"@vkontakte/videoplayer-shared";import{isNonNullable as $m,assertNonNullable as is,now as Dw}from"@vkontakte/videoplayer-shared";function ee(){return Dw()}function tu(i){return ee()-i}function ru(i){let e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,a=n=>r.test(n);return{resolve:(n,o,u=!1)=>{a(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Cm(i,e,t){let r=(...a)=>{t.apply(null,a),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Sr(i,e,t,r){let a=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,v=()=>{if(u)return;is(c);let w=tu(c),U;if(w<b){U=b-w,setTimeout(v,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new a,O()},S=w=>(s=w,L),g=w=>(d=w,L),y=()=>(h="json",L),T=()=>{if(!u){if(--l>=0){v(),r&&r();return}u=!0,d&&d(),t&&t()}},I=w=>(p=w,L),O=()=>{c=ee(),n=new a,n.open("get",i);let w=0,U,z=0,k=()=>(is(c),Math.max(c,Math.max(U||0,z||0)));if(s&&n.addEventListener("progress",x=>{let q=ee();s.updateChunk&&x.loaded>w&&(s.updateChunk(k(),x.loaded-w),w=x.loaded,U=q)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>T())),n.addEventListener("load",()=>{if(u)return;is(n);let x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&s){let q=n.response.byteLength-w;q&&s.updateChunk&&s.updateChunk(k(),q)}n.responseType==="json"&&!Object.values(n.response).length?T():(d&&d(),e(n.response))}else T()}),n.addEventListener("error",()=>{T()}),p){let x=()=>{is(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(z=ee(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=h,n.send(),L},L={withBitrateReporting:S,withParallel:I,withJSONResponse:y,withRetryCount:w=>(l=w,L),withRetryInterval:(w,U)=>($m(w)&&(b=w),$m(U)&&(f=U),L),withTimeout:w=>(o=w,L),withFinally:g,send:O,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return L}var ni=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,a=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,a+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;a+=u,s.start=t,s.bytes-=u}}}if(a>0&&r>0){let s=a*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var oi=class{constructor(e,t,r,a,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=a,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=ee(),a=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=ee()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Sr(t,s,()=>a("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ee()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=ee();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){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 ss=1e4,iu=3;var Bw=6e4,Vw=10,_w=1,Nw=500,li=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 ni(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ru(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=ru(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||as(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=()=>{Cm(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 oi(iu,ss,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:a}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let T=s&&(!c||c===this.rep);return T||t("Not running!"),T},p=(T,I,O)=>{u&&u.abort(),u=Sr(this.urlResolver.resolve(T,!1),I,O,()=>this._retryCallback()).withTimeout(ss).withBitrateReporting(this.bitrateSwitcher).withRetryCount(iu).withFinally(()=>{u=null}).send()},h=(T,I,O)=>{ui(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),I,O,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=T=>{let I=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${I}=>${T}`),r.playbackRate=T)},b=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let O=ee()-1e4,D=0;for(let _=0;_<this.bufferStates.length;_++){let H=this.bufferStates[_];T=Math.min(T,H.buf),H.ts<O&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${T} drop=${D} jitter=${this.sourceJitter}`);let $=T-_w;this.sourceJitter>=0?$-=this.sourceJitter/2:this.sourceJitter-=1,$>3?f(1.15):$>1?f(1.1):$>.3?f(1.05):f(1)}},S=T=>{let I,O=()=>I&&I.start?I.start.length:0,D=x=>I.start[x]/1e3,$=x=>I.dur[x]/1e3,_=x=>I.fragIndex+x,H=(x,q)=>({chunkIdx:_(x),startTS:D(x),dur:$(x),discontinuity:q}),L=()=>{let x=0;if(I&&I.dur){let q=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Y=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,K=q;this.sourceJitter>1&&(K+=this.sourceJitter-1);let ie=I.dur.length-1;for(;ie>=0&&(K-=I.dur[ie],!(K<=0));--ie);x=Math.min(ie,I.dur.length-1-Y),x=Math.max(x,0)}return H(x,!0)},w=x=>{let q=O();if(!(q<=0)){if(as(x)){for(let Y=0;Y<q;Y++)if(D(Y)>x)return H(Y)}return L()}},U=x=>{let q=O(),Y=x?x.chunkIdx+1:0,K=Y-I.fragIndex;if(!(q<=0)){if(!x||K<0||K-q>Vw)return t(`Resync: offset=${K} bChunks=${q} chunk=`+JSON.stringify(x)),L();if(!(K>=q))return H(Y-I.fragIndex,!1)}},z=(x,q,Y)=>{l&&l.abort(),l=Sr(this.urlResolver.resolve(x,!0,this.lowLatency),q,Y,()=>this._retryCallback()).withTimeout(ss).withRetryCount(iu).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(x,q)=>{z(T,Y=>{if(!d())return;I=Y;let K=!!I.lowLatency;K!==this.lowLatency&&b(K);let ie=0;for(let Ye=0;Ye<I.dur.length;++Ye)ie+=I.dur[Ye];ie>0&&(ui(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/I.dur.length)),a({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,x(w(q))},()=>this._handleNetworkError())},nextChunk:U}},g=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),ui(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{let{videoElement:I,logger:O}=this.params,D=S(e.jidxUrl),$,_,H,L,w=0,U,z,k,x=()=>{U&&(clearTimeout(U),U=void 0);let N=Math.max(Nw,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),se=w+N,he=ee(),Se=Math.min(1e4,se-he);w=he;let nt=()=>{l||d()&&D.seek(()=>{d()&&(w=ee(),q(),x())})};Se>0?U=window.setTimeout(()=>{this.paused?x():nt()},Se):nt()},q=()=>{let N;for(;N=D.nextChunk(L);)L=N,ta(N);let se=D.nextChunk(H);if(se){if(H&&se.discontinuity){O("Detected discontinuity; restarting playback"),this.paused?x():(g(),this._initPlayerWith(e));return}Ye(se)}else x()},Y=(N,se)=>{if(!d()||!this.sourceBuffer)return;let he,Se,nt,Jt=ot=>{window.setTimeout(()=>{d()&&Y(N,se)},ot)};if(this.sourceBuffer.updating)O("Source buffer is updating; delaying appendBuffer"),Jt(100);else{let ot=ee(),Et=I.currentTime;!this.paused&&I.buffered.length>1&&z===Et&&ot-k>500&&(O("Stall suspected; trying to fix"),this._fixupStall()),z!==Et&&(z=Et,k=ot);let Xt=this._getBufferSizeSec();if(Xt>30)O(`Buffered ${Xt} seconds; delaying appendBuffer`),Jt(2e3);else try{this.sourceBuffer.appendBuffer(N),this.videoPlayStarted?(this.bufferStates.push({ts:ot,buf:Xt}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),se&&se()}catch(Dr){if(Dr.name==="QuotaExceededError")O("QuotaExceededError; delaying appendBuffer"),nt=this.sourceBuffer.buffered.length,nt!==0&&(he=this.sourceBuffer.buffered.start(0),Se=Et,Se-he>4&&this.sourceBuffer.remove(he,Se-3)),Jt(1e3);else throw Dr}}},K=()=>{_&&$&&(O([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(H)]),Y(_,function(){_=null,q()}))},ie=N=>e.fragUrlTemplate.replace("%%id%%",N.chunkIdx),Ye=N=>{d()&&h(ie(N),(se,he)=>{if(d()){if(he/=1e3,_=se,H=N,n=N.startTS,he){let Se=Math.min(10,N.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Se:Se}K()}},()=>this._handleNetworkError())},ta=N=>{d()&&(ui(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(N),!1)))},Cr=N=>{d()&&(e.cachedHeader=N,Y(N,()=>{$=!0,K()}))};s=!0,D.seek(N=>{if(d()){if(w=ee(),!N){x();return}L=N,!Ow(T)||N.startTS>T?Ye(N):(H=N,q())}},T),e.cachedHeader?Cr(e.cachedHeader):p(e.headerUrl,Cr,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),as(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,ui(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return as(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s=(()=>({updateChunk:(p,h)=>{let f=ee();if(this.chunkRateEstimator.addInterval(p,f,h)){let v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:v}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))(),n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&tu(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ee();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Sr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(ss).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;pe(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((u,l)=>{u.video&&a.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Bw))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};import{debounce as Fw,filter as Dm,fromEvent as qw,interval as Uw,isHigher as Hw,isInvariantQuality as jw,isLower as Gw,merge as Yw,Subject as Mm,Subscription as Ww}from"@vkontakte/videoplayer-shared";var au=class{constructor(){this.onDroopedVideoFramesLimit$=new Mm;this.subscription=new Ww;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&&!jw(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&&Hw(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.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(qw(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=Uw(this.droppedFramesChecker.checkTime).pipe(Dm(()=>this.playing),Dm(()=>{let a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(Fw(this.droppedFramesChecker.checkTime)),r=Yw(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])=>Gw(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}},ns=au;import{map as Qw,Observable as zw}from"@vkontakte/videoplayer-shared";import{fromEvent as Kw}from"@vkontakte/videoplayer-shared";var ci=()=>{var i;return!!((i=window.documentPictureInPicture)!=null&&i.window)||!!document.pictureInPictureElement};var Jw=(i,e)=>new zw(t=>{if(!window.IntersectionObserver)return;let r={root:null},a=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||ci()))},A(A({},r),e));a.observe(i);let s=Kw(document,"visibilitychange").pipe(Qw(n=>!document.hidden||ci())).subscribe(n=>t.next(n));return()=>{a.unobserve(i),s.unsubscribe}}),Pe=Jw;var nA=["paused","playing","ready"],oA=["paused","playing","ready"],di=class{constructor(e){this.subscription=new iA;this.videoState=new C("stopped");this.representations$=new nu([]);this.textTracksManager=new Ee;this.droppedFramesManager=new ns;this.maxSeekBackTime$=new nu(1/0);this.zeroTime$=new nu(void 0);this.liveOffset=new Je;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:Vm.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=ft(u.name))!=null?r:sA(u.video),d=u.bitrate/1e3,p=A({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((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:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),su(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(oA.includes(e)&&(n||o)){this.prepare();return}if((a==null?void 0:a.to)!=="paused"&&s.state==="requested"&&nA.includes(e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(re(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=a==null?void 0:a.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(re(this.params.source.url,u))}return;default:return Om(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=a=>{e.output.error$.next({id:"DashLiveProvider",category:Vm.WTF,message:"DashLiveProvider internal logic error",thrown:a})};_m(this.videoState.stateChangeStarted$.pipe(os(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(os(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(a)}`})}),this.video=ue(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(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=de(this.video);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$:this.representations$.pipe(os(a=>a.map(({track:s})=>s)))}),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(tA(),os(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(Xw({zeroTime:this.zeroTime$.pipe(eA(su)),position:r.timeUpdate$}).subscribe(({zeroTime:a,position:s})=>this.params.output.liveTime$.next(a+s*1e3),t)).add(He(this.video,this.params.desiredState.isLooped,t)).add(ce(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ie(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(Pe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:a}})=>{let s=a&&aA(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 Om(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$,rA(["init"])).pipe(Zw(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),le(this.video)}createLiveDashPlayer(){let e=new li({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 l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.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&&su(t)?t:bt(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,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a&&(n||s!==o)&&this.setVideoTrack(a),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:v})=>v.id===s))==null?void 0:f.representation;Bm(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;Bm(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(re(this.params.source.url,n)),a&&this.dash.pause(),this.liveOffset.resetTo(n,a)}};var Nm=di;var gt=(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 wk,assertNonNullable as Zb,debounce as Ak,ErrorCategory as Ru,filter as kk,filterChanged as eg,fromEvent as Rk,isLowerOrEqual as tg,isNonNullable as Lk,videoSizeToQuality as rg,map as Lu,merge as ys,observableFrom as $k,observeElementSize as Ck,once as Dk,Subscription as Mk,ValueSubject as ig}from"@vkontakte/videoplayer-shared";var us=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}},yr=class extends us{constructor(){super(),this.listeners||us.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)}},pi=class{constructor(){Object.defineProperty(this,"signal",{value:new yr,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&&(pi.prototype[Symbol.toStringTag]="AbortController",yr.prototype[Symbol.toStringTag]="AbortSignal");function ls(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function ou(i){typeof i=="function"&&(i={fetch:i});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!ls({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||a)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var hi=ls({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Fm=hi?ou({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=hi?Fm.fetch:window.fetch,Y0=hi?Fm.Request:window.Request,et=hi?pi:window.AbortController,W0=hi?yr:window.AbortSignal;var Kb=Fe(Fa(),1);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};import{abortable as wu,assertNonNullable as Yt,combine as Gb,ErrorCategory as St,filter as ms,filterChanged as Sk,fromEvent as Ar,interval as Au,isNonNullable as Yb,map as ku,merge as kr,Subject as Wb,Subscription as Qb,tap as yk,throttle as Tk,ValueSubject as ge}from"@vkontakte/videoplayer-shared";var wr=Fe(ts(),1);var uA=(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)},lA=i=>window.clearTimeout(i),qm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",uu=qm?uA:window.requestIdleCallback,K0=qm?lA:window.cancelIdleCallback;var Bb=Fe(Xa(),1);import{assertNever as cA,CurrentClientBrowser as dA,ErrorCategory as Um,getCurrentBrowser as pA,Subject as Hm}from"@vkontakte/videoplayer-shared";var hA=16,Ym=!1,jm,Gm;try{Ym=pA().browser===dA.Safari&&parseInt((Gm=(jm=navigator.userAgent.match(/Version\/(\d+)/))==null?void 0:jm[1])!=null?Gm:"",10)<=hA}catch(i){console.error(i)}var lu=class{constructor(e){this.bufferFull$=new Hm;this.error$=new Hm;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:Um.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return R(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let a={operation:"append",data:e,signal:t,callback:r};this.queue.push(a),this.pull()})})}remove(e,t,r){return R(this,null,function*(){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()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let r;Ym&&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:Um.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:cA(t)}}},Wm=lu;var cu=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 xr,assertNever as dk,assertNonNullable as tt,ErrorCategory as Pr,fromEvent as Tu,getExponentialDelay as Iu,once as pk,isNonNullable as Ob,isNullable as rt,Subject as hk,Subscription as fk,ValueSubject as Bi}from"@vkontakte/videoplayer-shared";var F=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let a=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,a),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var Tr=class extends F{};var mi=class extends F{};var bi=class extends F{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 gi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var vi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Si=class extends F{constructor(t,r){super(t,r);this.data=this.content}};var W=class extends F{constructor(t,r){super(t,r);let a=this.readUint32();this.version=a>>>24,this.flags=a&16777215}};var Nt=class extends W{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,u=this.readUint32();s=this.readUint32();let l=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:n,referencedSize:o,subsegmentDuration:u,SAPType:l,SAPDeltaTime:c})}}get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}};var yi=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ti=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ii=class extends W{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 W{constructor(t,r){super(t,r);this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var xi=class extends W{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 F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var wi=class extends W{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 Ai=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ki=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ri=class extends W{constructor(t,r){super(t,r);this.sequenceNumber=this.readUint32()}};var Li=class extends F{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var $i=class extends W{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 W{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 Di=class extends W{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 mA={ftyp:bi,moov:gi,moof:vi,mdat:Si,sidx:Nt,trak:yi,mdia:Pi,mfhd:Ri,tkhd:wi,traf:Li,tfhd:$i,tfdt:Ci,trun:Di,minf:Ai,sv3d:Ti,st3d:Ii,prhd:Ei,proj:ki,equi:xi,uuid:mi,unknown:Tr},Ft=class i{constructor(e={}){this.options=A({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=mA[e];return r?new r(t,new i):new Tr(t,new i)}};var Ir=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 gA=new TextDecoder("ascii"),vA=i=>gA.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",SA=i=>{let e=new Nt(i,new Ft),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})},yA=(i,e)=>{let r=new Ft().parse(i),a=new Ir(r),s=a.findAll("moof"),n=e?a.findAll("uuid"):a.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(i.buffer,l,d)},TA=(i,e)=>{let r=new Ft().parse(i),s=new Ir(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},IA=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 Ft().parse(i),a=new Ir(r);if(a.find("sv3d")){e.is3dVideo=!0;let n=a.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=a.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=a.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},Qm={validateData:vA,parseInit:IA,getIndexRange:()=>{},parseSegments:SA,parseFeedableSegmentChunk:yA,getSegmentEndTime:TA};import{assertNonNullable as pu,isNonNullable as Xm,isNullable as xA}from"@vkontakte/videoplayer-shared";import{assertNever as EA}from"@vkontakte/videoplayer-shared";var zm={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"}},Km=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=Mi(i,t),a=r in zm,s=a?zm[r].type:"binary",n=i.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(i.buffer,i.byteOffset+t+1,o-1),l=n&255>>o,c=Mi(u),d=l*Ne(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}},Mi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Ne(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Ne(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Ne(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},Oe=(i,e)=>{switch(e){case"int":return i.getInt8(0);case"uint":return Mi(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:EA(e)}},qt=(i,e)=>{let t=0;for(;t<i.byteLength;){let r=new DataView(i.buffer,i.byteOffset+t),a=Km(r);if(!e(a))return;a.type==="master"&&qt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},Jm=i=>{if(i.getUint32(0)!==440786851)return!1;let e,t,r,a=Km(i);return qt(a.value,({tag:s,type:n,value:o})=>(s===17143?e=Oe(o,n):s===17026?t=Oe(o,n):s===17029&&(r=Oe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var Zm=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],PA=[231,22612,22743,167,171,163,160,175],wA=i=>{let e,t,r,a,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return qt(i,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let v=Oe(f,h);l=Mi(v)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Oe(f,h):p===17545?a=Oe(f,h):p===21420&&l===475249515?u=Oe(f,h):p===374648427?qt(f,({tag:v,type:S,value:g})=>v===30321?(c=Oe(g,S)===1,!1):!0):s&&n&&Zm.includes(p)&&(o=!0),!o}),pu(e,"Failed to parse webm Segment start"),pu(t,"Failed to parse webm Segment end"),pu(a,"Failed to parse webm Segment duration"),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:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},AA=i=>{if(xA(i.cuesSeekPosition))return;let e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},kA=(i,e)=>{let t=!1,r=!1,a=o=>Xm(o.time)&&Xm(o.position),s=[],n;return qt(i,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&a(n)&&s.push(n),n={};break;case 179:n&&(n.time=Oe(l,u));break;case 183:break;case 241:n&&(n.position=Oe(l,u));break;default:t&&Zm.includes(o)&&(r=!0)}return!(t&&r)}),n&&a(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},RA=i=>{let e=0,t=!1;try{qt(i,r=>r.tag===524531317?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):PA.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},eb={validateData:Jm,parseInit:wA,getIndexRange:AA,parseSegments:kA,parseFeedableSegmentChunk:RA};var gu=Fe(xb(),1);import{isNonNullable as wb,isNullable as Ab}from"@vkontakte/videoplayer-shared";var Pb=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 u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),a=(r==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},Ut=(i,e)=>{let t=i;t=(0,gu.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,gu.default)(t,n,(o,u)=>Ab(s)?o:Ab(u)?s:s.padStart(parseInt(u,10),"0"))}return t},Lb=(i,e)=>{var T,I,O,D,$,_,H,L,w,U,z,k,x,q,Y,K,ie,Ye,ta,Cr,N,se,he,Se,nt,Jt,ot,Et,Xt,Dr,Wu,Qu,zu,Ku,Ju,Xu,Zu,el,tl,rl,il,al;let r=new DOMParser().parseFromString(i,"application/xml"),a={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=(O=(I=(T=s.querySelector("BaseURL"))==null?void 0:T.textContent)==null?void 0:I.trim())!=null?O:"",u=n.children,l=s.getAttribute("type")==="dynamic",c=s.getAttribute("availabilityStartTime"),d=c?new Date(c).getTime():void 0,p,h=s.getAttribute("mediaPresentationDuration"),f=n.getAttribute("duration"),b=s.getElementsByTagName("vk:Attrs")[0],v=b==null?void 0:b.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(h)p=kb(h);else if(f){let ye=kb(f);wb(ye)&&(p=ye)}else v&&(p=parseInt(v,10));let S=0,g=($=(D=s.getAttribute("profiles"))==null?void 0:D.split(","))!=null?$:[],y=g.includes("urn:webm:dash:profile:webm-on-demand:2012")||g.includes("urn:mpeg:dash:profile:webm-on-demand:2012")?"webm":"mp4";for(let ye of u){let ra=ye.getAttribute("mimeType"),sv=ye.getAttribute("codecs"),sl=(_=ye.getAttribute("contentType"))!=null?_:ra==null?void 0:ra.split("/")[0],nv=(L=(H=ye.getAttribute("profiles"))==null?void 0:H.split(","))!=null?L:[],nl=ye.querySelectorAll("Representation"),ov=ye.querySelector("SegmentTemplate");if(sl==="text"){for(let Q of nl){let ut=Q.getAttribute("id")||"",ia=ye.getAttribute("lang"),Zt=ye.getAttribute("label"),Us=(z=(U=(w=Q.querySelector("BaseURL"))==null?void 0:w.textContent)==null?void 0:U.trim())!=null?z:"",Hs=new URL(Us||o,e).toString(),aa=ut.includes("_auto");a.text.push({id:ut,lang:ia,label:Zt,isAuto:aa,kind:"text",url:Hs})}continue}for(let Q of nl){let ut=(k=Q.getAttribute("mimeType"))!=null?k:ra,ia=(q=(x=Q.getAttribute("codecs"))!=null?x:sv)!=null?q:"",Zt=(K=(Y=Q.getAttribute("contentType"))!=null?Y:ut==null?void 0:ut.split("/")[0])!=null?K:sl,Us=(Ye=(ie=ye.getAttribute("profiles"))==null?void 0:ie.split(","))!=null?Ye:[],Hs=parseInt((ta=Q.getAttribute("width"))!=null?ta:"",10),aa=parseInt((Cr=Q.getAttribute("height"))!=null?Cr:"",10),ol=parseInt((N=Q.getAttribute("bandwidth"))!=null?N:"",10)/1e3,ul=(se=Q.getAttribute("frameRate"))!=null?se:"",uv=(he=Q.getAttribute("quality"))!=null?he:void 0,lv=ul?Pb(ul):void 0,cv=(Se=Q.getAttribute("id"))!=null?Se:(S++).toString(10),dv=Zt==="video"?`${aa}p`:Zt==="audio"?`${ol}Kbps`:ia,pv=`${cv}@${dv}`,hv=(ot=(Jt=(nt=Q.querySelector("BaseURL"))==null?void 0:nt.textContent)==null?void 0:Jt.trim())!=null?ot:"",ll=new URL(hv||o,e).toString(),fv=[...g,...nv,...Us],js,mv=Q.querySelector("SegmentBase"),xt=(Et=Q.querySelector("SegmentTemplate"))!=null?Et:ov;if(mv){let Pt=(Dr=(Xt=Q.querySelector("SegmentBase Initialization"))==null?void 0:Xt.getAttribute("range"))!=null?Dr:"",[wt,Ys]=Pt.split("-").map(er=>parseInt(er,10)),lt={from:wt,to:Ys},Mr=(Wu=Q.querySelector("SegmentBase"))==null?void 0:Wu.getAttribute("indexRange"),[Ws,sa]=Mr?Mr.split("-").map(er=>parseInt(er,10)):[],Or=Mr?{from:Ws,to:sa}:void 0;js={type:"byteRange",url:ll,initRange:lt,indexRange:Or}}else if(xt){let Pt={representationId:(Qu=Q.getAttribute("id"))!=null?Qu:void 0,bandwidth:(zu=Q.getAttribute("bandwidth"))!=null?zu:void 0},wt=parseInt((Ku=xt.getAttribute("timescale"))!=null?Ku:"",10),Ys=(Ju=xt.getAttribute("initialization"))!=null?Ju:"",lt=xt.getAttribute("media"),Mr=(Zu=parseInt((Xu=xt.getAttribute("startNumber"))!=null?Xu:"",10))!=null?Zu:1,Ws=Ut(Ys,Pt);if(!lt)throw new ReferenceError("No media attribute in SegmentTemplate");let sa=(el=xt.querySelectorAll("SegmentTimeline S"))!=null?el:[],Or=[],er=0,Qs="",zs=0;if(sa.length){let na=Mr,Re=0;for(let tr of sa){let _e=parseInt((tl=tr.getAttribute("d"))!=null?tl:"",10),At=parseInt((rl=tr.getAttribute("r"))!=null?rl:"",10)||0,oa=parseInt((il=tr.getAttribute("t"))!=null?il:"",10);Re=Number.isFinite(oa)?oa:Re;let Ks=_e/wt*1e3,Js=Re/wt*1e3;for(let ua=0;ua<At+1;ua++){let gv=Ut(lt,B(A({},Pt),{segmentNumber:na.toString(10),segmentTime:(Re+ua*_e).toString(10)})),cl=(Js!=null?Js:0)+ua*Ks,vv=cl+Ks;na++,Or.push({time:{from:cl,to:vv},url:gv})}Re+=(At+1)*_e,er+=(At+1)*Ks}zs=Re/wt*1e3,Qs=Ut(lt,B(A({},Pt),{segmentNumber:na.toString(10),segmentTime:Re.toString(10)}))}else if(wb(p)){let Re=parseInt((al=xt.getAttribute("duration"))!=null?al:"",10)/wt*1e3,tr=Math.ceil(p/Re),_e=0;for(let At=1;At<tr;At++){let oa=Ut(lt,B(A({},Pt),{segmentNumber:At.toString(10),segmentTime:_e.toString(10)}));Or.push({time:{from:_e,to:_e+Re},url:oa}),_e+=Re}zs=_e,Qs=Ut(lt,B(A({},Pt),{segmentNumber:tr.toString(10),segmentTime:_e.toString(10)}))}let bv={time:{from:zs,to:1/0},url:Qs};js={type:"template",baseUrl:ll,segmentTemplateUrl:lt,initUrl:Ws,totalSegmentsDurationMs:er,segments:Or,nextSegmentBeyondManifest:bv,timescale:wt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Zt||!ut)continue;let Gs={video:"video",audio:"audio",text:"text"}[Zt];Gs&&a[Gs].push({id:pv,kind:Gs,segmentReference:js,profiles:fv,duration:p,bitrate:ol,mime:ut,codecs:ia,width:Hs,height:aa,fps:lv,quality:uv})}}return{dynamic:l,liveAvailabilityStartTime:d,duration:p,container:y,representations:a}};var Su=Fe(ts(),1);import{videoSizeToQuality as ck}from"@vkontakte/videoplayer-shared";var $b=({id:i,width:e,height:t,bitrate:r,fps:a,quality:s})=>{var o;let n=(o=s?ft(s):void 0)!=null?o:ck({width:e,height:t});return n&&{id:i,quality:n,bitrate:r,size:{width:e,height:t},fps:a}},Cb=({id:i,bitrate:e})=>({id:i,bitrate:e}),Db=(i,e,t)=>{var a;let r=e.indexOf(t);return(a=(0,Su.default)(i,Math.round(i.length*r/e.length)))!=null?a:(0,Su.default)(i,-1)},Mb=({id:i,lang:e,label:t,url:r,isAuto:a})=>({id:i,url:r,isAuto:a,type:"internal",language:e,label:t}),yu=i=>"url"in i,Ht=i=>i.type==="template",Oi=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);var Vi=class{constructor(e,t,r,a,{fetcher:s,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:l=!1,manifest:c}){this.currentSegmentLength$=new Bi(0);this.onLastSegment$=new Bi(!1);this.fullyBuffered$=new Bi(!1);this.playingRepresentation$=new Bi(void 0);this.playingRepresentationInit$=new Bi(void 0);this.error$=new hk;this.gaps=[];this.subscription=new fk;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new et;this.destroyAbortController=new et;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=xr(this.destroyAbortController.signal,function(e){return J(this,null,function*(){let t=this.representations.get(e);tt(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new Wm(this.sourceBuffer),this.subscription.add(Tu(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>this.error$.next({id:"SegmentEjection",category:Pr.WTF,message:"Error when trying to clear segments ejected by browser",thrown:n}))),this.subscription.add(Tu(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Pr.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,cu(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);tt(r,"No init buffer for starting representation"),tt(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=xr(this.destroyAbortController.signal,function(e){return J(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let t=this.representations.get(e);tt(t,`No such representation ${e}`);let r=this.segments.get(e),a=this.initData.get(e);if(rt(a)||rt(r)?yield this.loadInit(t,"high",!1):a instanceof Promise&&(yield a),r=this.segments.get(e),tt(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();Ob(s)&&(this.isLive||(r.forEach(n=>n.status="none"),this.pruneBuffer(s,1/0,!0)),this.maintain(s))})}.bind(this));this.seekLive=xr(this.destroyAbortController.signal,function(e){return J(this,null,function*(){var o;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!e)return;for(let u of this.representations.keys()){let l=e.find(p=>p.id===u);l&&this.representations.set(u,l);let c=this.representations.get(u);if(!c||!Ht(c.segmentReference))return;let d=this.getActualLiveStartingSegments(c.segmentReference);this.segments.set(c.id,d)}let t=(o=this.switchingToRepresentationId)!=null?o:this.downloadingRepresentationId,r=this.representations.get(t);tt(r);let a=this.segments.get(t);tt(a,"No segments for starting representation");let s=this.initData.get(t);if(tt(s,"No init buffer for starting representation"),!(s instanceof ArrayBuffer))return;let n=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),n&&(yield this.sourceBufferTaskQueue.remove(n.from*1e3,n.to*1e3,this.destroyAbortController.signal)),this.searchGaps(a,r),yield this.sourceBufferTaskQueue.append(s,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));switch(this.fetcher=s,this.tuning=n,this.compatibilityMode=l,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(c!=null&&c.dynamic),this.container=r,r){case"mp4":this.containerParser=Qm;break;case"webm":this.containerParser=eb;break;default:dk(r)}this.initData=new Map(a.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(d=>[d.id,d])),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 et,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(rt(e)||rt(this.downloadingRepresentationId)||rt(this.playingRepresentationId)||rt(this.sourceBuffer)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(tt(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let a=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=a==null?void 0:a.time.to)!=null?l:0)-((c=a==null?void 0:a.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let p=gt(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)&&cu(this.sourceBuffer.buffered)>=this.bufferLimit){let d=gt(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,wr.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&&gt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,wr.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===u))}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;Ob(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.representations[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 t,r,a,s;for(let n of(t=e==null?void 0:e.representations[this.kind].values())!=null?t:[]){if(!n||!Ht(n.segmentReference))return;let o=n.segmentReference.segments.map(d=>B(A({},d),{status:"none",size:void 0})),u=(r=this.segments.get(n.id))!=null?r:[],l=(s=(a=(0,wr.default)(u,-1))==null?void 0:a.time.to)!=null?s:0,c=o==null?void 0:o.findIndex(d=>Math.floor(l)>=Math.floor(d.time.from)&&Math.floor(l)<=Math.floor(d.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;let d=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,d)}else{let d=o.slice(c+1);this.segments.set(n.id,[...u,...d])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(let r of this.representations.values()){let a=r.segmentReference;if(!Ht(a))return;let s=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),n=Ut(a.segmentTemplateUrl,{segmentTime:s}),o=(t=this.segments.get(r.id))!=null?t:[],u=o.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));u&&(u.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(u=>u.time.from<=e&&u.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}},f)=>{let b=p<=r&&h>=r,v=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&v&&g&&this.sourceBuffer&&!fi(this.sourceBuffer.buffered,r))&&v&&g});if(a===-1)return[];if(t!=="byteRange")return e.slice(a,a+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=a;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return R(this,null,function*(){t.segmentReference.type==="template"?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return R(this,null,function*(){e.status="downloading";let a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield xr(o,function(){return J(this,null,function*(){let c=Iu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(!c)return;let d=new DataView(c);if(this.isActiveLowLatency()){let p=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(d,p)}u&&a.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o),a.segment.status="downloaded",this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Oi(c)||this.failedDownloads++}})}loadByteRangeSegments(e,t,r="auto"){return R(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:a,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield xr(n,function(){return J(this,null,function*(){let u=Iu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Tu(window,"online").pipe(pk()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:a,onProgress:o,signal:n,priority:r}),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Oi(u)||this.failedDownloads++}})}prepareByteRangeFetchSegmentParams(e,t){if(Ht(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,a={from:(0,wr.default)(e,0).byte.from,to:(0,wr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:a,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:a?a.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Pr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ht(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let a=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{let d=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:s,onSegmentAppendFailed:()=>this.abort(),representationId:t.id});n.push(d)}catch(d){this.error$.next({id:"SegmentFeeding",category:Pr.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:a,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:a,signal:s}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){a();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=this.containerParser.parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.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 u=o.segmentReference.type,l=e.byteLength;for(let c of this.activeSegments){let{segment:d}=c,p=u==="byteRange",h=p?d.byte.to-d.byte.from+1:l;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,v=p?d.byte.to-r:e.byteLength,S=b<a,g=v<=a;if(d.status==="downloading"&&S&&g){d.status="downloaded";let y=new DataView(e.buffer,e.byteOffset+b,h);this.sourceBufferTaskQueue.append(y,s).then(T=>T&&!s.aborted?this.onSegmentFullyAppended(c,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(h,a-b),c.loadedBytes>c.feedingBytes)){let y=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===h?y:this.containerParser.parseFeedableSegmentChunk(y);T!=null&&T.byteLength&&(d.status="partially_fed",c.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,s).then(I=>{if(s.aborted)n();else if(I)c.fedBytes+=T.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",yu(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=uu(()=>(0,Bb.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return R(this,null,function*(){let a=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?xr(this.destroyAbortController.signal,function(){return J(this,null,function*(){let o=Iu(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(o=>R(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Ht(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Pr.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||rt(e)||this.sourceBuffer.updating)return!1;let a=0,s=1/0,n=-1/0,o=!1,u=l=>{var d;s=Math.min(s,l.time.from),n=Math.max(n,l.time.to);let c=yu(l)?(d=l.size)!=null?d:0:l.byte.to-l.byte.from;a+=c};for(let l of this.segments.values())for(let c of l){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status==="fed"&&u(c)}if(o=isFinite(s)&&isFinite(n),!o){a=0,s=1/0,n=-1/0;for(let l of this.segments.values())for(let c of l){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;c.status==="fed"&&u(c)}}if(o=isFinite(s)&&isFinite(n),!o)for(let l=0;l<this.sourceBuffer.buffered.length;l++){let c=this.sourceBuffer.buffered.start(l)*1e3,d=this.sourceBuffer.buffered.end(l)*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 l=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+l&&d.status==="fed"&&u(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=uu(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Pr.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(rt(this.sourceBuffer)||rt(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),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from-t&&n<=c.to+t||o>=c.from-t&&o<=c.to+t);u||(l.length===1?a.status="partially_ejected":this.gaps.some(c=>c.from===a.time.from||c.to===a.time.to)?a.status="partially_ejected":a.status="none")}}};var _i=i=>{let e=new URL(i);return e.searchParams.set("quic","1"),e.toString()};var Vb=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 Ni,assertNever as _b,fromEvent as Nb,merge as mk,now as Eu,Subscription as bk,ValueSubject as xu}from"@vkontakte/videoplayer-shared";var cs=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new xu(void 0);this.lastConnectionReused$=new xu(void 0);this.lastRequestFirstBytes$=new xu(void 0);this.abortAllController=new et;this.subscription=new bk;this.fetchManifest=Ni(this.abortAllController.signal,function(e){return J(this,null,function*(){let t=e;this.requestQuic&&(t=_i(t));let r=yield Ze(t,{signal:this.abortAllController.signal}).catch(Fi);return r?(this.onHeadersReceived(r.headers),r.text()):null})}.bind(this));this.fetch=Ni(this.abortAllController.signal,function(l){return J(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:a,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var _,H;let c=e,d=new Headers;if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let L=new URL(c,location.href);L.searchParams.append("bytes",`${r.from}-${r.to}`),c=L.toString();break}default:_b(t)}this.requestQuic&&(c=_i(c));let p=this.abortAllController.signal,h;if(n){let L=new et;if(h=mk(Nb(this.abortAllController.signal,"abort"),Nb(n,"abort")).subscribe(()=>{try{L.abort()}catch(w){Fi(w)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(w){Fi(w)}p=L.signal}let f=Eu(),b=yield Ze(c,{priority:s,headers:d,signal:p}).catch(Fi),v=Eu();if(!b)return h==null||h.unsubscribe(),null;if((_=this.throughputEstimator)==null||_.addRawRtt(v-f),!b.ok||!b.body)return h==null||h.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!a&&!o)return h==null||h.unsubscribe(),b.arrayBuffer();let[S,g]=b.body.tee(),y=S.getReader();o&&((H=this.throughputEstimator)==null||H.trackStream(g,u));let T=0,I=new Uint8Array(0),O=!1,D=L=>{h==null||h.unsubscribe(),O=!0,Fi(L)},$=Ni(p,function(U){return J(this,arguments,function*({done:L,value:w}){if(T===0&&this.lastRequestFirstBytes$.next(Eu()-f),p.aborted){h==null||h.unsubscribe();return}if(!L&&w){let z=new Uint8Array(I.length+w.length);z.set(I),z.set(w,I.length),I=z,T+=w.byteLength,a==null||a(new DataView(I.buffer),T),yield y==null?void 0:y.read().then($,D)}})}.bind(this));return yield y==null?void 0:y.read().then($,D),h==null||h.unsubscribe(),O?null:I.buffer})}.bind(this));this.fetchByteRangeRepresentation=Ni(this.abortAllController.signal,function(e,t,r){return J(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:a,to:s}=e.initRange,n=a,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,a),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,a-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(S=e.indexRange)!=null?S:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let g=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!g)return null;b=new DataView(g)}let v=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:v}})}.bind(this));this.fetchTemplateRepresentation=Ni(this.abortAllController.signal,function(e,t){return J(this,null,function*(){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=>B(A({},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}=Vb(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return R(this,null,function*(){var s,n;let{type:a}=e;switch(a){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:_b(a)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}},Fi=i=>{if(!Oi(i))throw i};var jt=(i,e,t)=>t*e+(1-t)*i,Pu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,Fb=(i,e,t,r)=>{let a=0,s=t,n=Pu(i,e),o=e<r?e:r;for(let u=0;u<o;u++)i[s]>n?a++:a--,s=(i.length+s-1)%i.length;return Math.abs(a)===o};import{isNullable as gk,ValueSubject as qb}from"@vkontakte/videoplayer-shared";var vt=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 qb(e.initial),this.debounced$=new qb(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ae(`raw_${t}`),this.smoothedSeries$=new ae(`smoothed_${t}`),this.reportedSeries$=new ae(`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+=Ne(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)&&(gk(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 ds=class extends vt{constructor(t){super(t);this.slow=this.fast=t.initial}updateSmoothedValue(t){this.slow=jt(this.slow,t,this.params.emaAlphaSlow),this.fast=jt(this.fast,t,this.params.emaAlphaFast);let r=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=r(this.slow,this.fast)}};var ps=class extends vt{constructor(t){super(t);this.emaSmoothed=t.initial}updateSmoothedValue(t){let r=Pu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=jt(this.emaSmoothed,t,this.params.emaAlpha);let a=Fb(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=a?this.emaSmoothed:r}};var hs=class extends vt{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?jt(this.smoothed,t,this.params.emaAlpha):t}};var Gt=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ds({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ps({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 hs(A({initial:e,label:"liveEdgeDelay"},t))}};var Ub=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)};var it=()=>window.ManagedMediaSource||window.MediaSource,fs=()=>{var i,e;return!!(window.ManagedMediaSource&&((e=(i=window.ManagedSourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},Hb=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&((e=(i=window.SourceBuffer)==null?void 0:i.prototype)!=null&&e.appendBuffer))},jb=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var zb=["timeupdate","progress","play","seeked","stalled","waiting"];var bs=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Qb;this.representationSubscription=new Qb;this.state$=new C("none");this.currentVideoRepresentation$=new ge(void 0);this.currentVideoRepresentationInit$=new ge(void 0);this.currentVideoSegmentLength$=new ge(0);this.currentAudioSegmentLength$=new ge(0);this.error$=new Wb;this.lastConnectionType$=new ge(void 0);this.lastConnectionReused$=new ge(void 0);this.lastRequestFirstBytes$=new ge(void 0);this.isLive$=new ge(!1);this.liveDuration$=new ge(0);this.liveAvailabilityStartTime$=new ge(void 0);this.bufferLength$=new ge(0);this.liveLoadBufferLength$=new ge(0);this.livePositionFromPlayer$=new ge(0);this.timeInWaiting=0;this.isActiveLowLatency=!1;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Wb;this.gapWatchdogActive=!1;this.destroyController=new et;this.initManifest=wu(this.destroyController.signal,function(e,t,r){return J(this,null,function*(){var a;this.element=e,this.manifestUrlString=re(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(a=this.manifest)!=null&&a.representations.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:St.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=wu(this.destroyController.signal,function(){return J(this,null,function*(){var a;let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(s=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:St.NETWORK,message:"Failed to load manifest",thrown:s})});if(!e)return null;let t;try{t=Lb(e!=null?e:"",this.manifestUrlString)}catch(s){this.error$.next({id:"ManifestParsing",category:St.PARSER,message:"Failed to parse MPD manifest",thrown:s})}if(!t)return null;let r=({kind:s,mime:n,codecs:o})=>{var u,l,c,d;return!!((l=(u=this.element)==null?void 0:u.canPlayType)!=null&&l.call(u,n)&&((d=(c=it())==null?void 0:c.isTypeSupported)!=null&&d.call(c,`${n}; codecs="${o}"`))||s==="text")};return t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((a=t.duration)!=null?a:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime)),B(A({},t),{representations:(0,Kb.default)(Object.entries(t.representations).map(([s,n])=>[s,n.filter(r)]))})})}.bind(this));this.initRepresentations=wu(this.destroyController.signal,function(e,t,r){return J(this,null,function*(){var h;Yt(this.manifest),Yt(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let a=f=>{this.representationSubscription.add(Ar(f,"error").pipe(ms(b=>{var v;return!!((v=this.element)!=null&&v.played.length)})).subscribe(b=>{this.error$.next({id:"VideoSource",category:St.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?jb():new MediaSource;let s=document.createElement("source");if(a(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&fs())if(r){let f=document.createElement("source");a(f),f.type="application/x-mpegurl",f.src=r.url,this.element.appendChild(f)}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};if(this.videoBufferManager=new Vi("video",this.source,this.manifest.container,this.manifest.representations.video,n),this.bufferManagers=[this.videoBufferManager],Yb(t)&&(this.audioBufferManager=new Vi("audio",this.source,this.manifest.container,this.manifest.representations.audio,n),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(Au(1e3).subscribe(f=>{var b;if((b=this.element)!=null&&b.paused){let v=Ho(this.manifestUrlString,2);this.manifestUrlString=re(this.manifestUrlString,v+1e3,2)}})),this.representationSubscription.add(kr(...zb.filter(f=>f!=="waiting").map(f=>Ar(this.element,f))).pipe(ku(f=>this.element?gt(this.element.buffered,this.element.currentTime*1e3):0),Sk(),ms(f=>!!f),yk(f=>{var b;(b=this.stallWatchdogSubscription)==null||b.unsubscribe(),this.timeInWaiting=0})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(ms(b=>this.isActiveLowLatency&&!!b)).subscribe(b=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(b=>{if(!this.isActiveLowLatency)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,g=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=b-v,T=1+Math.sign(y)*g;Math.abs(y)<S?T=1:Math.abs(y)>S*2&&(T=1+Math.sign(y)*g*2),Ub(this.element,T)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{var S,g;let v=0;if(b){let y=((g=(S=this.element)==null?void 0:S.currentTime)!=null?g:0)*1e3;v=Math.min(...this.bufferManagers.map(I=>{var O,D;return(D=(O=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:O.to)!=null?D:y}))-y}this.liveLoadBufferLength$.getValue()!==v&&this.liveLoadBufferLength$.next(v)}));let f=0;this.representationSubscription.add(Gb({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(Tk(1e3)).subscribe(S=>R(this,[S],function*({liveLoadBufferLength:b,bufferLength:v}){if(Yt(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,y=Ho(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),O=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,D=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=this.isActiveLowLatency?v:b,_=3;if(this.isActiveLowLatency?_=0:$<I+D&&$>=I?_=1:y!==0&&$<I&&(_=2),isFinite(b)&&(f=b>f?b:f),_===2||_===1){let H=f-(I+O),L=this.normolizeLiveOffset(Math.trunc(y+H/g)),w=Math.abs(L-y),U;!b||w<=this.tuning.dashCmafLive.offsetCalculationError?U=y:L>0&&w>this.tuning.dashCmafLive.offsetCalculationError?U=L:U=0,this.manifestUrlString=re(this.manifestUrlString,U,2)}_!==3&&_!==0&&(f=0,this.updateLive())})))}let o=kr(...this.bufferManagers.map(f=>f.fullyBuffered$)).pipe(ku(()=>this.bufferManagers.every(f=>f.fullyBuffered$.getValue()))),u=kr(...this.bufferManagers.map(f=>f.onLastSegment$)).pipe(ku(()=>this.bufferManagers.some(f=>f.onLastSegment$.getValue())));this.representationSubscription.add(kr(this.forceEnded$,Gb({allBuffersFull:o,someBufferEnded:u}).pipe(ms(({allBuffersFull:f,someBufferEnded:b})=>f&&b))).subscribe(()=>{var f;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(b=>!b.updating))try{(f=this.source)==null||f.endOfStream()}catch(b){this.error$.next({id:"EndOfStream",category:St.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:b})}})),this.representationSubscription.add(kr(...this.bufferManagers.map(f=>f.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(f=>{var b;return(b=this.source)==null?void 0:b.addEventListener("sourceopen",f)}));let l=(h=this.manifest.duration)!=null?h:0,c=(f,b)=>{var v;return Math.max(f,(v=b.duration)!=null?v:0)},d=this.manifest.representations.audio.reduce(c,l),p=this.manifest.representations.video.reduce(c,l);(d||p)&&(this.source.duration=Math.max(d,p)/1e3),this.audioBufferManager&&Yb(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready")})}.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:St.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new cs({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Gt.getLiveEstimatedDelaySmoothedValue(0,A({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){return R(this,null,function*(){var r,a,s,n;Yt(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&t===0,this.liveLastSeekOffset=t,this.manifestUrlString=re(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(a=this.videoBufferManager)==null?void 0:a.seekLive((r=this.manifest)==null?void 0:r.representations.video),yield(n=this.audioBufferManager)==null?void 0:n.seekLive((s=this.manifest)==null?void 0:s.representations.audio))})}initBuffer(){Yt(this.element),this.state$.setState("running"),this.subscription.add(kr(...zb.map(e=>Ar(this.element,e)),Ar(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:St.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:St.FATAL,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t){return R(this,null,function*(){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,u;Yt(this.element),Yt(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),(u=this.audioBufferManager)==null||u.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)}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}updateLive(){return R(this,null,function*(){var e;this.isUpdatingLive=!0,this.manifest=yield 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 gs=class{constructor(e,t){this.fov=e,this.orientation=t}};var vs=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/Ne(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=A({},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*Ne(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 Jb=`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 Qb=`#ifdef GL_ES
48
+ `;var Xb=`#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 gs=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 ms(this.params.fov,this.params.orientation),this.cameraRotationManager=new bs(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(Wb,this.gl.VERTEX_SHADER),r=this.createShader(Qb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,u=t-a,l=e+r,c=t+a,d=e-r,p=t+a;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Qt=class{constructor(e){this.subscription=new LA;this.videoState=new C("stopped");this.elementSize$=new Zb(void 0);this.textTracksManager=new Ee;this.droppedFramesManager=new as;this.videoTracks$=new Zb([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new es;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;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 l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(a.position-l,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"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(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"&&E(this.params.desiredState.playbackState,"paused");return;default:return IA(e)}}};this.init3DScene=e=>{var r,a,s;if(this.scene3D)return;this.scene3D=new gs(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=ue(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(Z(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new fs({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=de(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,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();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$:this.videoTracks$.pipe(wu(l=>l.map(({track:c})=>c)))}),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(xA(kA),RA()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(He(this.video,t.isLooped,a)),this.subscription.add(ce(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ie(this.video,t.playbackRate,r.playbackRateState$,a)),s(AA(this.video),this.elementSize$),s(Pe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{var c;if(l==="manifest_ready"){let d=[];this.audioTracks=[],this.textTracks=[];let p=this.player.getRepresentations();zb(p,"Manifest not loaded or empty");let h=Array.from(p.audio).sort((S,g)=>g.bitrate-S.bitrate),f=Array.from(p.video).sort((S,g)=>g.bitrate-S.bitrate),b=Array.from(p.text);if(!this.params.tuning.isAudioDisabled)for(let S of h){let g=Ab(S);g&&this.audioTracks.push({track:g,representation:S})}for(let S of f){let g=wb(S);if(g){d.push({track:g,representation:S});let y=!this.params.tuning.isAudioDisabled&&Rb(h,f,S);y&&this.audioRepresentations.set(S.id,y)}}this.videoTracks$.next(d);for(let S of b){let g=Lb(S);g&&this.textTracks.push({track:g,representation:S})}this.params.output.availableVideoTracks$.next(d.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));let v=this.selectVideoRepresentation();zb(v),this.player.initRepresentations(v.id,(c=this.audioRepresentations.get(v.id))==null?void 0:c.id,this.params.sourceHls)}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=l=>e.error$.next({id:"RepresentationSwitch",category:ku.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(vs(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$,PA(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(l!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);let h=this.params.desiredState.autoVideoTrackSwitching.getState(),f=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let b=d.id;!this.params.output.elementVisible$.getValue()&&h&&(b=this.videoTracks$.getValue().map(S=>S.representation).sort((S,g)=>g.bitrate-S.bitrate).filter(S=>{let g=Xb(S),y=Xb(d);if(g&&y)return Jb(g,y)&&Jb(g,f)}).map(S=>S.id)[0]),this.player.switchRepresentation("video",b).catch(n);let v=this.audioRepresentations.get(d.id);v&&this.player.switchRepresentation("audio",v.id).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Kb(),wu(l=>{var c;return l&&((c=this.videoTracks$.getValue().find(({representation:{id:d}})=>d===l))==null?void 0:c.track)})).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),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(wu(({to:l})=>l==="ready"),Kb());this.subscription.add(vs(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(vs(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=vs(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,wA(["init"])).pipe(EA(0));this.subscription.add(u.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var d,p,h,f,b,v,S;let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=(d=this.params.desiredState.videoTrack.getState())==null?void 0:d.id,r=(p=this.videoTracks$.getValue().find(({track:{id:g}})=>g===t))==null?void 0:p.track,a=this.params.output.currentVideoTrack$.getValue(),s=gt(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(s/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),u=Math.max(r&&!e&&(f=(h=this.audioRepresentations.get(r.id))==null?void 0:h.bitrate)!=null?f:0,a&&(v=(b=this.audioRepresentations.get(a.id))==null?void 0:b.bitrate)!=null?v:0),l=bt(this.videoTracks$.getValue().map(({track:g})=>g),{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:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?l!=null?l:r:r!=null?r:l;return c&&((S=this.videoTracks$.getValue().find(({track:g})=>g===c))==null?void 0:S.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){pe(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(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),le(this.video)}};var Fi=class extends Qt{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 eg,interval as $A,map as CA}from"@vkontakte/videoplayer-shared";var qi=class extends Qt{constructor(e){super(e),this.liveOffset=new Je}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(eg({interval:$A(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(eg({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(CA(({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 rg=Fe(Ka(),1);import{assertNever as Ui,assertNonNullable as tg,debounce as DA,ErrorCategory as Ss,filter as MA,isNonNullable as OA,isNullable as BA,map as Au,merge as VA,Observable as _A,observableFrom as NA,Subscription as FA,videoSizeToQuality as qA}from"@vkontakte/videoplayer-shared";var Be={};var Rr=(i,e)=>new _A(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),Hi=class{constructor(e){this.subscription=new FA;this.videoState=new C("initializing");this.textTracksManager=new Ee;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:Ui(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ui(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ui(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ui(e)}break;default:Ui(t)}};this.video=ue(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(Z(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),le(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ss.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,rg.default)(import("hls.js").then(a=>{e||(Be.Hls=a.default,Be.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){tg(Be.Hls,"hls.js not loaded"),this.hls=new Be.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){tg(Be.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Ss.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=de(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.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(He(this.video,e.isLooped,r)),this.subscription.add(ce(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ie(this.video,e.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),t.elementVisible$),this.subscription.add(Rr(this.hls,Be.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Ss.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Rr(this.hls,Be.Events.MANIFEST_PARSED).pipe(Au(({levels:l})=>l.reduce((c,d)=>{var g,y;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(y=ft((g=d.attrs.QUALITY)!=null?g:""))!=null?y:qA({width:h,height:f});if(!b)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:v};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(Rr(this.hls,Be.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang,b="internal";c.push({id:p,url:h,language:f,type:b})}e.internalTextTracks.startTransitionTo(c)}}),s(Rr(this.hls,Be.Events.LEVEL_LOADING).pipe(Au(({url:l})=>Z(l))),t.hostname$),s(Rr(this.hls,Be.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.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((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(dt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Rr(this.hls,Be.Events.LEVEL_SWITCHED).pipe(Au(({level:l})=>n(this.hls.levels[l])));o.pipe(MA(OA)).subscribe(t.currentVideoTrack$,r),this.subscription.add(dt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(BA(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=VA(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,NA(["init"])).pipe(DA(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return R(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield pe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ss.DOM,thrown:t})))||(this.videoState.setState("paused"),E(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"),E(this.params.desiredState.playbackState,"stopped",!0)}};var ig="X-Playback-Duration",Ru=i=>R(void 0,null,function*(){var a;let e=yield Ze(i),t=yield 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(ig)?parseInt(e.headers.get(ig),10):void 0});import{assertNever as WA,combine as QA,debounce as zA,ErrorCategory as Ts,filter as KA,filterChanged as JA,isNonNullable as sg,isNullable as Is,map as ng,merge as XA,observableFrom as ZA,Subscription as eR,ValueSubject as Cu,VideoQuality as tR}from"@vkontakte/videoplayer-shared";var $u=Fe(_a(),1);import{videoSizeToQuality as UA,getExponentialDelay as HA}from"@vkontakte/videoplayer-shared";var jA=i=>{let e=null;if(i.QUALITY&&(e=ft(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=UA({width:t,height:r})}return e!=null?e:null},GA=(i,e)=>{var s,n;let t=i.split(`
92
- `),r=[],a=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,$u.default)(l[1].split(",").map(g=>g.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=jA(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[g,y]=d.RESOLUTION.split("x").map(T=>parseInt(T,10));g&&y&&(v={width:g,height:y})}let S=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:S,bandwidth:f,size:v,fps:b})}if(c){let d=(0,$u.default)(c[1].split(",").map(b=>b.split("=")).map(([b,v])=>[b,v.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&a.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},YA=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Lu=0,ag=(r,...a)=>R(void 0,[r,...a],function*(i,e=i,t){let n=yield(yield Ze(i)).text();Lu+=1;try{let{qualityManifests:o,textTracks:u}=GA(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Lu<=t.manifestRetryMaxCount)return yield YA(HA(Lu-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),ag(i,e,t)}return{qualityManifests:[],textTracks:[]}}),ys=ag;var ji=class{constructor(e){this.subscription=new eR;this.videoState=new C("stopped");this.textTracksManager=new Ee;this.manifests$=new Cu([]);this.liveOffset=new Je;this.manifestStartTime$=new Cu(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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((a==null?void 0:a.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(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"&&E(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"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return WA(t)}};var t;this.params=e,this.video=ue(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:tR.INVARIANT,url:this.params.source.url},ys(re(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:Ts.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Ts.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(this.params.source.url)),this.maxSeekBackTime$=new Cu((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(u=a==null?void 0:a.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.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:Ts.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=de(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.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(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(JA(),ng(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&sg(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(QA({startTime:this.manifestStartTime$.pipe(KA(sg)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(ng(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=XA(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ZA(["init"])).pipe(zA(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),le(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Is(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:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"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=re(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Ru(n).then(l=>{var c;if(!Is(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Is(d)||!isFinite(d))try{Ze(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();Ru(b).then(v=>{Is(v)||this.maxSeekBackTime$.next(v)})}})}catch(p){}}})}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ts.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 rR,debounce as iR,ErrorCategory as Du,fromEvent as Mu,isNonNullable as aR,isNullable as sR,map as nR,merge as og,observableFrom as ug,Subscription as oR,ValueSubject as uR,VideoQuality as lR,isIOS as cR}from"@vkontakte/videoplayer-shared";var Gi=class{constructor(e){this.subscription=new oR;this.videoState=new C("stopped");this.textTracksManager=new Ee;this.manifests$=new uR([]);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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(a==null?void 0:a.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return rR(t)}};this.params=e,this.video=ue(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:lR.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ys(re(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:Du.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(u=a==null?void 0:a.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.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:Du.WTF,message:"HlsProvider internal logic error",thrown:o})},a=de(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.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(He(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&aR(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Z(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(f),v.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(nR(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!cR()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(og(Mu(o,"addtrack"),Mu(o,"removetrack"),Mu(o,"change"),ug(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=og(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ug(["init"])).pipe(iR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),le(this.video)}prepare(){var s,n;let e=this.selectManifest();if(sR(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Du.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as dR,assertNonNullable as lg,debounce as pR,ErrorCategory as cg,isHigher as hR,isHigherOrEqual as fR,isInvariantQuality as dg,isLowerOrEqual as mR,isNonNullable as bR,merge as gR,observableFrom as vR,Subscription as SR}from"@vkontakte/videoplayer-shared";var Yi=class{constructor(e){this.subscription=new SR;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Ee;this.syncPlayback=()=>{var u,l,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"),E(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&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.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"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return dR(e)}};this.params=e,this.video=ue(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:cg.WTF,message:"MpegProvider internal logic error",thrown:o})},a=de(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.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(He(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&bR(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=(l=this.params.output.element$.getValue())==null?void 0:l.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=gR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,vR(["init"])).pipe(pR(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),le(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;lg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];lg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Vi(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Z(t))}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cg.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 u=(s=Object.values(this.trackUrls).find(d=>!dg(d.track.quality)&&mR(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&fR(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!dg(h.track.quality)&&hR(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=bt(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:r})}};import{assertNever as hg,debounce as ER,merge as fg,observableFrom as xR,Subscription as PR,map as mg,ValueSubject as kR,ErrorCategory as Bu,VideoQuality as wR}from"@vkontakte/videoplayer-shared";import{ErrorCategory as yR}from"@vkontakte/videoplayer-shared";var pg=["stun:videostun.mycdn.me:80"],TR=1e3,IR=3,Ou=()=>null,Es=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=Ou;this.externalStopCallback=Ou;this.externalErrorCallback=Ou;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}}handleUpdateMessage(e){return R(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return R(this,null,function*(){try{let e={iceServers:[{urls:pg}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return R(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return R(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:yR.WTF,message:e.message})}onPeerConnectionStream(e){return R(this,null,function*(){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()))}}createOffer(){return R(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield 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),TR)}normalizeOptions(e={}){let t={stunServerList:pg,maxRetryNumber:IR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Wi=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new kR(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"),E(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"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return hg(e)}};this.subscription=new PR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ue(e.container),this.liveStreamClient=new Es(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),le(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Bu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};fg(this.videoState.stateChangeStarted$.pipe(mg(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(mg(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=de(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(Pe(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(ce(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 hg(n.to)}},r)).add(fg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,xR(["init"])).pipe(ER(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:wR.INVARIANT}),this.video.srcObject=e,E(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:Bu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Qi=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 Ki,assertNonNullable as Tt,ErrorCategory as $s,filter as FR,isNonNullable as Og,isNullable as qR,map as UR,merge as HR,once as jR,Subject as Ve,Subscription as Bg,ValueSubject as V}from"@vkontakte/videoplayer-shared";import{assertNever as Ls,CurrentClientDevice as LR,getCurrentBrowser as $R}from"@vkontakte/videoplayer-shared";var kg=$R().device===LR.Android,we=document.createElement("video"),CR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',DR='video/mp4; codecs="hev1.1.6.L93.B0"',wg='video/webm; codecs="vp09.00.10.08"',Ag='video/webm; codecs="av01.0.00M.08"',MR='audio/mp4; codecs="mp4a.40.2"',OR='audio/webm; codecs="opus"',bg,gg,zt={mms:ps(),mse:Nb(),hls:!!((bg=we.canPlayType)!=null&&bg.call(we,"application/x-mpegurl")||(gg=we.canPlayType)!=null&&gg.call(we,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},vg,Sg,ke={mp4:!!((vg=we.canPlayType)!=null&&vg.call(we,"video/mp4")),webm:!!((Sg=we.canPlayType)!=null&&Sg.call(we,"video/webm")),cmaf:!0},xs,yg,Ps,Tg,ks,Ig,ws,Eg,As,xg,Rs,Pg,Ge={h264:!!((yg=(xs=it())==null?void 0:xs.isTypeSupported)!=null&&yg.call(xs,CR)),h265:!!((Tg=(Ps=it())==null?void 0:Ps.isTypeSupported)!=null&&Tg.call(Ps,DR)),vp9:!!((Ig=(ks=it())==null?void 0:ks.isTypeSupported)!=null&&Ig.call(ks,wg)),av1:!!((Eg=(ws=it())==null?void 0:ws.isTypeSupported)!=null&&Eg.call(ws,Ag)),aac:!!((xg=(As=it())==null?void 0:As.isTypeSupported)!=null&&xg.call(As,MR)),opus:!!((Pg=(Rs=it())==null?void 0:Rs.isTypeSupported)!=null&&Pg.call(Rs,OR))},zi=(Ge.h264||Ge.h265)&&Ge.aac,Kt,BR=()=>R(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(B(w({},i),{video:B(w({},i.video),{contentType:Ag})})),window.navigator.mediaCapabilities.decodingInfo(B(w({},i),{video:B(w({},i.video),{contentType:wg})}))]);Kt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{BR()}catch(i){console.error(i)}var Lr=zt.hls&&ke.mp4,Rg=()=>Object.keys(Ge).filter(i=>Ge[i]),Lg=(i,e=!1,t=!1)=>{let r=zt.mse||zt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&ke.mp4&&zi;case"DASH_WEBM":return r&&ke.webm&&Ge.vp9&&Ge.opus;case"DASH_WEBM_AV1":return r&&ke.webm&&Ge.av1&&Ge.opus;case"DASH_LIVE":return zt.mse&&ke.mp4&&zi;case"DASH_LIVE_CMAF":return r&&ke.mp4&&zi&&ke.cmaf;case"DASH_ONDEMAND":return r&&ke.mp4&&zi;case"HLS":case"HLS_ONDEMAND":return Lr||e&&zt.mse&&ke.mp4&&zi;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Lr;case"MPEG":return ke.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return zt.webrtc&&zt.ws&&Ge.h264&&(ke.mp4||ke.webm);default:return Ls(a)}})},yt=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Kt?Kt[t].smooth?[t,e]:Kt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Kt?Kt[t].powerEfficient?[t,e]:Kt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Ls(i)}return[e,t]},$g=({webmCodec:i,androidPreferredFormat:e})=>{if(kg)switch(e){case"mpeg":return["MPEG",...yt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...yt(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...yt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...yt(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...yt(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...yt(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:Ls(e)}return Lr?[...yt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...yt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},Cg=({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(kg)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:Ls(i)}else Lr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Vu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];import{Observable as VR,map as Dg,Subscription as _R,Subject as NR}from"@vkontakte/videoplayer-shared";var Mg=i=>new VR(e=>{let t=new _R,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Dg(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Dg(({type:l})=>l!==void 0)),n=new NR,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var GR={chunkDuration:5e3,maxParallelRequests:5},Ji=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new Ve;this.noAvailableProvidersError$=new Ve;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),currentVideoTrack$:new V(void 0),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),availableVideoTracks$:new V([]),availableAudioTracks$:new V([]),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new Ve,warning$:new Ve,willSeekEvent$:new Ve,seekedEvent$:new Ve,loopedEvent$:new Ve,endedEvent$:new Ve,firstBytesEvent$:new Ve,firstFrameEvent$:new Ve,canplay$:new Ve,isLive$:new V(void 0),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1)};this.subscription=new Bg;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Lg([...Cg(this.params.tuning),...$g(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>Og(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 Qi(s);let n=[...Vu(!0),...Vu(!1)];this.chromecastFormatsIterator=new Qi(n.filter(o=>Og(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(qR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:$s.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 Ki(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":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Tt(o),new Fi(B(w({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Tt(o),new qi(B(w({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Tt(o),Lr||!this.params.tuning.useHlsJs?new Gi(B(w({},n),{source:o})):new Hi(B(w({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Tt(o),new ji(B(w({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Yi(B(w({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Om(B(w({},n),{source:o,config:B(w({},GR),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Wi({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return Ki(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 Tt(o),new ei({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 Ki(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ki(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 Ki(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 B(w({},e),{url:r(e.url)})}return(0,Vg.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Bg,t=!1,r=0;return e.add(HR(this.providerOutput.error$,Mg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(UR(a=>({id:`ProviderHangup:${a}`,category:$s.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(FR(({to:s})=>s==="playing"),jR()).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===$s.NETWORK,o=a.category===$s.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};import{fromEvent as Cs,once as YR,combine as WR,Subscription as _g,ValueSubject as _u,map as QR,filter as zR,isNonNullable as Ds,now as ve,safeStorage as Nu}from"@vkontakte/videoplayer-shared";var KR=5e3,Ng="one_video_throughput",Fg="one_video_rtt",at=window.navigator.connection,qg=()=>{let i=at==null?void 0:at.downlink;if(Ds(i)&&i!==10)return i*1e3},Ug=()=>{let i=at==null?void 0:at.rtt;if(Ds(i)&&i!==3e3)return i},Hg=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},Fu=class i{constructor(e){this.subscription=new _g;this.concurrentDownloads=new Set;var a,s;this.tuningConfig=e;let t=i.load(Ng)||(e.useBrowserEstimation?qg():void 0)||KR,r=(s=(a=i.load(Fg))!=null?a:e.useBrowserEstimation?Ug():void 0)!=null?s:0;if(this.throughput$=new _u(t),this.rtt$=new _u(r),this.rttAdjustedThroughput$=new _u(Hg(t,r,e.rttPenaltyRequestSize)),this.throughput=Gt.getSmoothedValue(t,-1,e),this.rtt=Gt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=qg();u&&this.throughput.next(u);let l=Ug();Ds(l)&&this.rtt.next(l)};at&&"onchange"in at&&this.subscription.add(Cs(at,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Nu.set(Ng,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Nu.set(Fg,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(WR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(QR(({throughput:n,rtt:o})=>Hg(n,o,e.rttPenaltyRequestSize)),zR(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=ve(),a=new _g;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(Cs(e,"progress").pipe(YR()).subscribe(s=>{t=s.loaded,r=ve()}));break;case 1:case 0:a.add(Cs(e,"loadstart").subscribe(()=>{t=0,r=ve()}));break}a.add(Cs(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ve(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=ve(),n=0,o=ve(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>R(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(a,ve()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if(ve()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=ve()}o=ve()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ve()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ve()-o,this.concurrentDownloads.size),n=0,o=ve());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Nu.get(e);if(Ds(t))return(r=parseInt(t,10))!=null?r:void 0}},jg=Fu;import{fillWithDefault as JR,VideoQuality as Gg}from"@vkontakte/videoplayer-shared";var Yg={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:Gg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Gg.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:500,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,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}},Wg=i=>{var e;return B(w({},JR(i,Yg)),{configName:[...(e=i.configName)!=null?e:[],...Yg.configName]})};import{assertNonNullable as Ms,combine as Os,ErrorCategory as Bs,filter as Xi,filterChanged as Ae,fromEvent as Uu,isNonNullable as aL,isNullable as sL,Logger as nL,map as M,mapTo as Jg,merge as It,now as Vs,once as st,Subject as j,Subscription as Xg,tap as Zg,ValueSubject as P,isHigher as oL,isInvariantQuality as ev}from"@vkontakte/videoplayer-shared";import{merge as XR,map as ZR,filter as Qg,isNonNullable as eL}from"@vkontakte/videoplayer-shared";var qu=({seekState:i,position$:e})=>XR(i.stateChangeEnded$.pipe(ZR(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),Qg(eL)),e.pipe(Qg(()=>i.getState().state==="none")));import{assertNonNullable as tL}from"@vkontakte/videoplayer-shared";var zg=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return tL(e,`Wrong container or containerId {${i.container}}`),e};import{filter as rL,once as iL}from"@vkontakte/videoplayer-shared";var Kg=(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(rL(a=>a.length>0),iL()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};var _s=class{constructor(e={configName:[]}){this.subscription=new Xg;this.logger=new nL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableQualities$:new P([]),availableQualitiesFps$:new P({}),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,firstBytes$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:Im};if(this.initLogs(),this.tuning=Wg(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new la({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new jg(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 u=n.map(d=>JSON.stringify(d,(p,h)=>{let f=typeof h;return["number","string","boolean"].includes(f)?h:h===null?null:`<${f}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:Bs.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,a;return this.config=e,this.domContainer=zg(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Ji({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()?Uu(document,"visibilitychange").pipe(st()).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}setQuality(e){Ms(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(Xi(r=>r.length>0),st()).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;Ms(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=>w({type:"external"},t))),this}selectTextTrack(e){var t;return Kg(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(sL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return aL(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(It(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Xi(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=Vs(),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(B(w({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Bs.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(M(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(M(n=>n.destination),Ae()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(M(n=>n.map(({quality:o})=>o).sort((o,u)=>ev(o)?1:ev(u)?-1:oL(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.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(M(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(Os({hasLiveOffsetByPaused:It(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(n=>n.to),Ae(),M(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(Os({atLiveEdge:Os({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:qu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(M(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Ae(),Zg(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(M(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Os({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(M(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Ae(),Zg(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(M(n=>n.muted),Ae()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(M(n=>n.volume),Ae()).subscribe(this.info.volume$)).add(qu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(It(e.providerOutput.endedEvent$.pipe(Jg(!0)),e.providerOutput.seekedEvent$.pipe(Jg(!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(M(n=>({id:n?`No${n}`:"NoProviders",category:Bs.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(st(),M(n=>n!=null?n:Vs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),M(()=>Vs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),M(()=>Vs()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Xi(({to:n})=>n==="playing"),st()).subscribe(()=>r.next(!1)));let a=0,s=It(e.providerOutput.isBuffering$,t,r).pipe(M(()=>{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(It(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 u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.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(It(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(M(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 Xg;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(Xi(r=>r.length>0),st()).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=bt(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(It(this.desiredState.videoTrack.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(M(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;Ms(this.providerContainer),Ms(e),Tm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>ym(r)),this.providerContainer.current$.subscribe(({type:r})=>ai("provider",r)),e.duration$.subscribe(r=>ai("duration",r)),e.availableVideoTracks$.pipe(Xi(r=>!!r.length),st()).subscribe(r=>ai("tracks",r)),this.events.fatalError$.subscribe(new ae("fatalError")),this.events.managedError$.subscribe(new ae("managedError")),e.position$.subscribe(new ae("position")),e.currentVideoTrack$.pipe(M(r=>r==null?void 0:r.quality)).subscribe(new ae("quality")),this.info.currentBuffer$.subscribe(new ae("buffer")),e.isBuffering$.subscribe(new ae("isBuffering"))].forEach(r=>this.subscription.add(r)),ai("codecs",Rg())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>R(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Bs.DOM,message:String(a)})})});this.subscription.add(It(Uu(document,"visibilitychange"),Uu(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 Lj,Observable as $j,Subject as Cj,ValueSubject as Dj,VideoQuality as Mj}from"@vkontakte/videoplayer-shared";var Oj=`@vkontakte/videoplayer-core@${cl}`;export{oa as ChromecastState,Ks as HttpConnectionType,$j as Observable,fe as PlaybackState,_s as Player,Oj as SDK_VERSION,Cj as Subject,Lj as Subscription,Js as Surface,cl as VERSION,Dj as ValueSubject,At as VideoFormat,Mj as VideoQuality};
91
+ `;var Ss=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 gs(this.params.fov,this.params.orientation),this.cameraRotationManager=new vs(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(Jb,this.gl.VERTEX_SHADER),r=this.createShader(Xb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:r=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,s=e-r,n=t-a,o=e+r,u=t-a,l=e+r,c=t+a,d=e-r,p=t+a;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};var Qt=class{constructor(e){this.subscription=new Mk;this.videoState=new C("stopped");this.elementSize$=new ig(void 0);this.textTracksManager=new Ee;this.droppedFramesManager=new ns;this.videoTracks$=new ig([]);this.audioTracks=[];this.audioRepresentations=new Map;this.videoTrackSwitchHistory=new rs;this.textTracks=[];this.syncPlayback=()=>{var n,o,u;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 l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(a.position-l,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"),E(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"),E(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&E(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.pause()):(r==null?void 0:r.to)==="playing"&&E(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"&&E(this.params.desiredState.playbackState,"paused");return;default:return wk(e)}}};this.init3DScene=e=>{var r,a,s;if(this.scene3D)return;this.scene3D=new Ss(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=ue(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(Z(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new bs({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=de(this.video),a=this.constructor.name,s=o=>{e.error$.next({id:a,category:Ru.WTF,message:`${a} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:a,connect:s}=this.getProviderSubscriptionInfo();this.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$:this.videoTracks$.pipe(Lu(l=>l.map(({track:c})=>c)))}),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(kk(Lk),Dk()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(He(this.video,t.isLooped,a)),this.subscription.add(ce(this.video,t.volume,r.volumeState$,a)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ie(this.video,t.playbackRate,r.playbackRateState$,a)),s(Ck(this.video),this.elementSize$),s(Pe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},a)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},a)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{var c;if(l==="manifest_ready"){let d=[];this.audioTracks=[],this.textTracks=[];let p=this.player.getRepresentations();Zb(p,"Manifest not loaded or empty");let h=Array.from(p.audio).sort((S,g)=>g.bitrate-S.bitrate),f=Array.from(p.video).sort((S,g)=>g.bitrate-S.bitrate),b=Array.from(p.text);if(!this.params.tuning.isAudioDisabled)for(let S of h){let g=Cb(S);g&&this.audioTracks.push({track:g,representation:S})}for(let S of f){let g=$b(S);if(g){d.push({track:g,representation:S});let y=!this.params.tuning.isAudioDisabled&&Db(h,f,S);y&&this.audioRepresentations.set(S.id,y)}}this.videoTracks$.next(d);for(let S of b){let g=Mb(S);g&&this.textTracks.push({track:g,representation:S})}this.params.output.availableVideoTracks$.next(d.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));let v=this.selectVideoRepresentation();Zb(v),this.player.initRepresentations(v.id,(c=this.audioRepresentations.get(v.id))==null?void 0:c.id,this.params.sourceHls)}else l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},a));let n=l=>e.error$.next({id:"RepresentationSwitch",category:Ru.WTF,message:"Switching representations threw",thrown:l});this.subscription.add(ys(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$,Rk(this.video,"progress")).subscribe(()=>{let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(l!=="running"||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();p&&this.params.output.autoVideoTrackLimits$.next(p.to);let h=this.params.desiredState.autoVideoTrackSwitching.getState(),f=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(d){let b=d.id;!this.params.output.elementVisible$.getValue()&&h&&(b=this.videoTracks$.getValue().map(S=>S.representation).sort((S,g)=>g.bitrate-S.bitrate).filter(S=>{let g=rg(S),y=rg(d);if(g&&y)return tg(g,y)&&tg(g,f)}).map(S=>S.id)[0]),this.player.switchRepresentation("video",b).catch(n);let v=this.audioRepresentations.get(d.id);v&&this.player.switchRepresentation("audio",v.id).catch(n)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSize$.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(eg(),Lu(l=>{var c;return l&&((c=this.videoTracks$.getValue().find(({representation:{id:d}})=>d===l))==null?void 0:c.track)})).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),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(Lu(({to:l})=>l==="ready"),eg());this.subscription.add(ys(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(ys(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=ys(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,$k(["init"])).pipe(Ak(0));this.subscription.add(u.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var d,p,h,f,b,v,S;let e=this.params.desiredState.autoVideoTrackSwitching.getState(),t=(d=this.params.desiredState.videoTrack.getState())==null?void 0:d.id,r=(p=this.videoTracks$.getValue().find(({track:{id:g}})=>g===t))==null?void 0:p.track,a=this.params.output.currentVideoTrack$.getValue(),s=gt(this.video.buffered,this.video.currentTime*1e3),n=e?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,o=Math.min(s/Math.min(n,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),u=Math.max(r&&!e&&(f=(h=this.audioRepresentations.get(r.id))==null?void 0:h.bitrate)!=null?f:0,a&&(v=(b=this.audioRepresentations.get(a.id))==null?void 0:b.bitrate)!=null?v:0),l=bt(this.videoTracks$.getValue().map(({track:g})=>g),{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:a,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=e?l!=null?l:r:r!=null?r:l;return c&&((S=this.videoTracks$.getValue().find(({track:g})=>g===c))==null?void 0:S.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){pe(this.video).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ru.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),le(this.video)}};var qi=class extends Qt{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 ag,interval as Ok,map as Bk}from"@vkontakte/videoplayer-shared";var Ui=class extends Qt{constructor(e){super(e),this.liveOffset=new Je}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(ag({interval:Ok(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(ag({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Bk(({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 ng=Fe(Xa(),1);import{assertNever as Hi,assertNonNullable as sg,debounce as Vk,ErrorCategory as Ts,filter as _k,isNonNullable as Nk,isNullable as Fk,map as $u,merge as qk,Observable as Uk,observableFrom as Hk,Subscription as jk,videoSizeToQuality as Gk}from"@vkontakte/videoplayer-shared";var Be={};var Rr=(i,e)=>new Uk(t=>{let r=(a,s)=>t.next(s);return i.on(e,r),()=>i.off(e,r)}),ji=class{constructor(e){this.subscription=new jk;this.videoState=new C("initializing");this.textTracksManager=new Ee;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:Hi(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Hi(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Hi(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Hi(e)}break;default:Hi(t)}};this.video=ue(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(Z(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),le(this.video)}loadHlsJs(){let e=!1,t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Ts.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,ng.default)(import("hls.js").then(a=>{e||(Be.Hls=a.default,Be.Events=a.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){sg(Be.Hls,"hls.js not loaded"),this.hls=new Be.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){sg(Be.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Ts.WTF,message:"HlsJsProvider internal logic error",thrown:l})},a=de(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(a.timeUpdate$,t.position$),s(a.durationChange$,t.duration$),s(a.ended$,t.endedEvent$),s(a.looped$,t.loopedEvent$),s(a.error$,t.error$),s(a.isBuffering$,t.isBuffering$),s(a.currentBuffer$,t.currentBuffer$),s(a.loadStart$,t.firstBytesEvent$),s(a.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(He(this.video,e.isLooped,r)),this.subscription.add(ce(this.video,e.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ie(this.video,e.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),t.elementVisible$),this.subscription.add(Rr(this.hls,Be.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Ts.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(e.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(e.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(Rr(this.hls,Be.Events.MANIFEST_PARSED).pipe($u(({levels:l})=>l.reduce((c,d)=>{var g,y;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(y=ft((g=d.attrs.QUALITY)!=null?g:""))!=null?y:Gk({width:h,height:f});if(!b)return c;let v=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:v};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(Rr(this.hls,Be.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang,b="internal";c.push({id:p,url:h,language:f,type:b})}e.internalTextTracks.startTransitionTo(c)}}),s(Rr(this.hls,Be.Events.LEVEL_LOADING).pipe($u(({url:l})=>Z(l))),t.hostname$),s(Rr(this.hls,Be.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.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((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(dt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=Rr(this.hls,Be.Events.LEVEL_SWITCHED).pipe($u(({level:l})=>n(this.hls.levels[l])));o.pipe(_k(Nk)).subscribe(t.currentVideoTrack$,r),this.subscription.add(dt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(Fk(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=qk(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Hk(["init"])).pipe(Vk(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return R(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield pe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ts.DOM,thrown:t})))||(this.videoState.setState("paused"),E(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"),E(this.params.desiredState.playbackState,"stopped",!0)}};var og="X-Playback-Duration",Cu=i=>R(void 0,null,function*(){var a;let e=yield Ze(i),t=yield 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(og)?parseInt(e.headers.get(og),10):void 0});import{assertNever as Jk,combine as Xk,debounce as Zk,ErrorCategory as Es,filter as eR,filterChanged as tR,isNonNullable as lg,isNullable as xs,map as cg,merge as rR,observableFrom as iR,Subscription as aR,ValueSubject as Ou,VideoQuality as sR}from"@vkontakte/videoplayer-shared";var Mu=Fe(Fa(),1);import{videoSizeToQuality as Yk,getExponentialDelay as Wk}from"@vkontakte/videoplayer-shared";var Qk=i=>{let e=null;if(i.QUALITY&&(e=ft(i.QUALITY)),!e&&i.RESOLUTION){let[t,r]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=Yk({width:t,height:r})}return e!=null?e:null},zk=(i,e)=>{var s,n;let t=i.split(`
92
+ `),r=[],a=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,Mu.default)(l[1].split(",").map(g=>g.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=Qk(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,v;if(d.RESOLUTION){let[g,y]=d.RESOLUTION.split("x").map(T=>parseInt(T,10));g&&y&&(v={width:g,height:y})}let S=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:S,bandwidth:f,size:v,fps:b})}if(c){let d=(0,Mu.default)(c[1].split(",").map(b=>b.split("=")).map(([b,v])=>[b,v.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&a.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:a}},Kk=i=>new Promise(e=>{setTimeout(()=>{e()},i)}),Du=0,ug=(r,...a)=>R(void 0,[r,...a],function*(i,e=i,t){let n=yield(yield Ze(i)).text();Du+=1;try{let{qualityManifests:o,textTracks:u}=zk(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Du<=t.manifestRetryMaxCount)return yield Kk(Wk(Du-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),ug(i,e,t)}return{qualityManifests:[],textTracks:[]}}),Is=ug;var Gi=class{constructor(e){this.subscription=new aR;this.videoState=new C("stopped");this.textTracksManager=new Ee;this.manifests$=new Ou([]);this.liveOffset=new Je;this.manifestStartTime$=new Ou(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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((a==null?void 0:a.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),E(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"&&E(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"&&(E(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return Jk(t)}};var t;this.params=e,this.video=ue(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:sR.INVARIANT,url:this.params.source.url},Is(re(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:Es.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Es.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(this.params.source.url)),this.maxSeekBackTime$=new Ou((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(u=a==null?void 0:a.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.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:Es.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},a=de(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(a.ended$,e.endedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.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(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(tR(),cg(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&lg(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Z(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(a.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(Xk({startTime:this.manifestStartTime$.pipe(eR(lg)),currentTime:a.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(cg(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=rR(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,iR(["init"])).pipe(Zk(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),le(this.video)}prepare(){var o,u;let e=this.selectManifest();if(xs(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:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"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=re(a.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Cu(n).then(l=>{var c;if(!xs(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(xs(d)||!isFinite(d))try{Ze(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();Cu(b).then(v=>{xs(v)||this.maxSeekBackTime$.next(v)})}})}catch(p){}}})}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Es.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 nR,debounce as oR,ErrorCategory as Bu,fromEvent as Vu,isNonNullable as uR,isNullable as lR,map as cR,merge as dg,observableFrom as pg,Subscription as dR,ValueSubject as pR,VideoQuality as hR,isIOS as fR}from"@vkontakte/videoplayer-shared";var Yi=class{constructor(e){this.subscription=new dR;this.videoState=new C("stopped");this.textTracksManager=new Ee;this.manifests$=new pR([]);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"),E(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?E(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(a==null?void 0:a.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return nR(t)}};this.params=e,this.video=ue(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:hR.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Is(re(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:Bu.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),a=t.getTransition(),s=(d=(c=(u=a==null?void 0:a.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.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:Bu.WTF,message:"HlsProvider internal logic error",thrown:o})},a=de(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.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(He(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(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(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&uR(l.to)){let p=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(f=>f.id===p);if(h){this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Z(h.url));let f=this.params.desiredState.playbackRate.getState(),b=(d=this.params.output.element$.getValue())==null?void 0:d.playbackRate;if(f!==b){let v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(f),v.playbackRate=f)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(cR(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!fR()||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(dg(Vu(o,"addtrack"),Vu(o,"removetrack"),Vu(o,"change"),pg(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=dg(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,pg(["init"])).pipe(oR(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),le(this.video)}prepare(){var s,n;let e=this.selectManifest();if(lR(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),a=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&a.searchParams.set(c,d)}}this.video.setAttribute("src",a.toString()),this.video.load()}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bu.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};import{assertNever as mR,assertNonNullable as hg,debounce as bR,ErrorCategory as fg,isHigher as gR,isHigherOrEqual as vR,isInvariantQuality as mg,isLowerOrEqual as SR,isNonNullable as yR,merge as TR,observableFrom as IR,Subscription as ER}from"@vkontakte/videoplayer-shared";var Wi=class{constructor(e){this.subscription=new ER;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Ee;this.syncPlayback=()=>{var u,l,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"),E(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&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.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"?E(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return mR(e)}};this.params=e,this.video=ue(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:fg.WTF,message:"MpegProvider internal logic error",thrown:o})},a=de(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(a.timeUpdate$,e.position$),s(a.durationChange$,e.duration$),s(a.ended$,e.endedEvent$),s(a.looped$,e.loopedEvent$),s(a.error$,e.error$),s(a.isBuffering$,e.isBuffering$),s(a.currentBuffer$,e.currentBuffer$),s(a.loadedMetadata$,e.firstBytesEvent$),s(a.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(He(this.video,t.isLooped,r)),this.subscription.add(ce(this.video,t.volume,a.volumeState$,r)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ie(this.video,t.playbackRate,a.playbackRateState$,r)),s(Pe(this.video),e.elementVisible$),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState("playing"),E(t.playbackState,"playing")},r)).add(a.pause$.subscribe(()=>{this.videoState.setState("paused"),E(t.playbackState,"paused")},r)).add(a.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&yR(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=(l=this.params.output.element$.getValue())==null?void 0:l.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=TR(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,IR(["init"])).pipe(bR(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),le(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;hg(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];hg(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=_i(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(Z(t))}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:fg.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 u=(s=Object.values(this.trackUrls).find(d=>!mg(d.track.quality)&&SR(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&vR(c.quality,u.quality)&&(t=u),!t){let d=Object.values(this.trackUrls).filter(h=>!mg(h.track.quality)&&gR(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=Object.values(this.trackUrls).map(l=>l.track);t=bt(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:r})}};import{assertNever as gg,debounce as AR,merge as vg,observableFrom as kR,Subscription as RR,map as Sg,ValueSubject as LR,ErrorCategory as Nu,VideoQuality as $R}from"@vkontakte/videoplayer-shared";import{ErrorCategory as xR}from"@vkontakte/videoplayer-shared";var bg=["stun:videostun.mycdn.me:80"],PR=1e3,wR=3,_u=()=>null,Ps=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=_u;this.externalStopCallback=_u;this.externalErrorCallback=_u;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}}handleUpdateMessage(e){return R(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return R(this,null,function*(){try{let e={iceServers:[{urls:bg}]};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=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return R(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return R(this,null,function*(){if(e)try{this.peerConnection&&(yield 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:xR.WTF,message:e.message})}onPeerConnectionStream(e){return R(this,null,function*(){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()))}}createOffer(){return R(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield 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),PR)}normalizeOptions(e={}){let t={stunServerList:bg,maxRetryNumber:wR,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Qi=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new LR(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"),E(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"),E(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"&&E(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&E(this.params.desiredState.playbackState,"paused");return;default:return gg(e)}};this.subscription=new RR,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ue(e.container),this.liveStreamClient=new Ps(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),le(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Nu.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};vg(this.videoState.stateChangeStarted$.pipe(Sg(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Sg(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let a=de(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(Pe(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(ce(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 gg(n.to)}},r)).add(vg(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,kR(["init"])).pipe(AR(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Z(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:$R.INVARIANT}),this.video.srcObject=e,E(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:Nu.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){pe(this.video).then(e=>{e||(this.videoState.setState("paused"),E(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nu.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var zi=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 Xi,assertNonNullable as Tt,ErrorCategory as Ms,filter as YR,isNonNullable as Ng,isNullable as WR,map as QR,merge as zR,once as KR,Subject as Ve,Subscription as Fg,ValueSubject as V}from"@vkontakte/videoplayer-shared";import{assertNever as Cs,CurrentClientDevice as MR,getCurrentBrowser as OR}from"@vkontakte/videoplayer-shared";var Lg=OR().device===MR.Android,Ae=document.createElement("video"),BR='video/mp4; codecs="avc1.42000a,mp4a.40.2"',VR='video/mp4; codecs="hev1.1.6.L93.B0"',$g='video/webm; codecs="vp09.00.10.08"',Cg='video/webm; codecs="av01.0.00M.08"',_R='audio/mp4; codecs="mp4a.40.2"',NR='audio/webm; codecs="opus"',yg,Tg,zt={mms:fs(),mse:Hb(),hls:!!((yg=Ae.canPlayType)!=null&&yg.call(Ae,"application/x-mpegurl")||(Tg=Ae.canPlayType)!=null&&Tg.call(Ae,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Ig,Eg,we={mp4:!!((Ig=Ae.canPlayType)!=null&&Ig.call(Ae,"video/mp4")),webm:!!((Eg=Ae.canPlayType)!=null&&Eg.call(Ae,"video/webm")),cmaf:!0},ws,xg,As,Pg,ks,wg,Rs,Ag,Ls,kg,$s,Rg,Ge={h264:!!((xg=(ws=it())==null?void 0:ws.isTypeSupported)!=null&&xg.call(ws,BR)),h265:!!((Pg=(As=it())==null?void 0:As.isTypeSupported)!=null&&Pg.call(As,VR)),vp9:!!((wg=(ks=it())==null?void 0:ks.isTypeSupported)!=null&&wg.call(ks,$g)),av1:!!((Ag=(Rs=it())==null?void 0:Rs.isTypeSupported)!=null&&Ag.call(Rs,Cg)),aac:!!((kg=(Ls=it())==null?void 0:Ls.isTypeSupported)!=null&&kg.call(Ls,_R)),opus:!!((Rg=($s=it())==null?void 0:$s.isTypeSupported)!=null&&Rg.call($s,NR))},Ki=(Ge.h264||Ge.h265)&&Ge.aac,Kt,FR=()=>R(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(B(A({},i),{video:B(A({},i.video),{contentType:Cg})})),window.navigator.mediaCapabilities.decodingInfo(B(A({},i),{video:B(A({},i.video),{contentType:$g})}))]);Kt={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{FR()}catch(i){console.error(i)}var Lr=zt.hls&&we.mp4,Dg=()=>Object.keys(Ge).filter(i=>Ge[i]),Mg=(i,e=!1,t=!1)=>{let r=zt.mse||zt.mms&&t;return i.filter(a=>{switch(a){case"DASH_SEP":return r&&we.mp4&&Ki;case"DASH_WEBM":return r&&we.webm&&Ge.vp9&&Ge.opus;case"DASH_WEBM_AV1":return r&&we.webm&&Ge.av1&&Ge.opus;case"DASH_LIVE":return zt.mse&&we.mp4&&Ki;case"DASH_LIVE_CMAF":return r&&we.mp4&&Ki&&we.cmaf;case"DASH_ONDEMAND":return r&&we.mp4&&Ki;case"HLS":case"HLS_ONDEMAND":return Lr||e&&zt.mse&&we.mp4&&Ki;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Lr;case"MPEG":return we.mp4;case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return zt.webrtc&&zt.ws&&Ge.h264&&(we.mp4||we.webm);default:return Cs(a)}})},yt=i=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(i){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return Kt?Kt[t].smooth?[t,e]:Kt[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return Kt?Kt[t].powerEfficient?[t,e]:Kt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Cs(i)}return[e,t]},Og=({webmCodec:i,androidPreferredFormat:e})=>{if(Lg)switch(e){case"mpeg":return["MPEG",...yt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...yt(i),"DASH_SEP","DASH_ONDEMAND","MPEG"];case"dash":return[...yt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return["DASH_SEP","DASH_ONDEMAND","MPEG",...yt(i),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...yt(i),"MPEG","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...yt(i),"DASH_ONDEMAND","HLS","HLS_ONDEMAND"];default:Cs(e)}return Lr?[...yt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]:[...yt(i),"DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"]},Bg=({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(Lg)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:Cs(i)}else Lr?o=n:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},Fu=i=>i?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"];import{Observable as qR,map as Vg,Subscription as UR,Subject as HR}from"@vkontakte/videoplayer-shared";var _g=i=>new qR(e=>{let t=new UR,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(Vg(({from:l,to:c})=>`${l}-${c}`)),a=i.desiredPlaybackState$.stateChangeEnded$,s=i.providerChanged$.pipe(Vg(({type:l})=>l!==void 0)),n=new HR,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});var $r=null,Ds=null;function qu(){return $r||($r=new(window.AudioContext||window.webkitAudioContext)),Ds||(Ds=new GainNode($r,{gain:1}),Ds.connect($r.destination)),$r.resume().catch(),{audioCtx:$r,gainNode:Ds}}import{getCurrentBrowser as jR,CurrentClientBrowser as GR}from"@vkontakte/videoplayer-shared";var Ji=class{constructor(e,t,r){this.video$=e;this.volumeMultiplier=t;!r||!this.isSupported()||t===1||this.video$.subscribe(a=>this.listener(a))}isSupported(){let{browser:e}=jR();return e!==GR.Safari&&"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}listener(e){if(!e)return;let{volumeMultiplier:t}=this,{audioCtx:r,gainNode:a}=qu();a.gain.value=t;try{new MediaElementAudioSourceNode(r,{mediaElement:e}).connect(a)}catch(s){}}destroy(){let{gainNode:e}=qu();e.gain.value=1}};var JR={chunkDuration:5e3,maxParallelRequests:5},Zi=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new Ve;this.noAvailableProvidersError$=new Ve;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),currentVideoTrack$:new V(void 0),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),availableVideoTracks$:new V([]),availableAudioTracks$:new V([]),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new Ve,warning$:new Ve,willSeekEvent$:new Ve,seekedEvent$:new Ve,loopedEvent$:new Ve,endedEvent$:new Ve,firstBytesEvent$:new Ve,firstFrameEvent$:new Ve,canplay$:new Ve,isLive$:new V(void 0),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1)};this.subscription=new Fg;var o;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");let t=Mg([...Bg(this.params.tuning),...Og(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(u=>Ng(e.sources[u])),{forceFormat:r,formatsToAvoid:a}=this.params.tuning,s=[];r?s=[r]:a.length?s=[...t.filter(u=>!a.includes(u)),...t.filter(u=>a.includes(u))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.screenFormatsIterator=new zi(s);let n=[...Fu(!0),...Fu(!1)];this.chromecastFormatsIterator=new zi(n.filter(u=>Ng(e.sources[u]))),this.providerOutput.availableSources$.next(e.sources),this.volumeMultiplierManager=new Ji(this.providerOutput.element$,(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(WR(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:Ms.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 Xi(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":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Tt(o),new qi(B(A({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Ui(B(A({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Tt(o),Lr||!this.params.tuning.useHlsJs?new Yi(B(A({},n),{source:o})):new ji(B(A({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Gi(B(A({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Wi(B(A({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Nm(B(A({},n),{source:o,config:B(A({},JR),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Tt(o),new Qi({container:r,source:o,desiredState:a,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH_LIVE_WEBM":throw new Error("DASH_LIVE_WEBM is no longer supported");default:return Xi(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 Tt(o),new ti({connection:o,meta:s,container:r,source:t,format:e,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Xi(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Xi(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 Xi(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 B(A({},e),{url:r(e.url)})}return(0,qg.default)(Object.entries(e).map(([a,s])=>[a,r(s)]))}initProviderErrorHandling(){let e=new Fg,t=!1,r=0;return e.add(zR(this.providerOutput.error$,_g({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(QR(a=>({id:`ProviderHangup:${a}`,category:Ms.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(YR(({to:s})=>s==="playing"),KR()).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===Ms.NETWORK,o=a.category===Ms.FATAL,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<this.params.tuning.providerErrorLimit&&!o;u&&!o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}})),e}};import{fromEvent as Os,once as XR,combine as ZR,Subscription as Ug,ValueSubject as Uu,map as eL,filter as tL,isNonNullable as Bs,now as ve,safeStorage as Hu}from"@vkontakte/videoplayer-shared";var rL=5e3,Hg="one_video_throughput",jg="one_video_rtt",at=window.navigator.connection,Gg=()=>{let i=at==null?void 0:at.downlink;if(Bs(i)&&i!==10)return i*1e3},Yg=()=>{let i=at==null?void 0:at.rtt;if(Bs(i)&&i!==3e3)return i},Wg=(i,e,t)=>{let r=t*8,a=r/i;return r/(a+e)},ju=class i{constructor(e){this.subscription=new Ug;this.concurrentDownloads=new Set;var a,s;this.tuningConfig=e;let t=i.load(Hg)||(e.useBrowserEstimation?Gg():void 0)||rL,r=(s=(a=i.load(jg))!=null?a:e.useBrowserEstimation?Yg():void 0)!=null?s:0;if(this.throughput$=new Uu(t),this.rtt$=new Uu(r),this.rttAdjustedThroughput$=new Uu(Wg(t,r,e.rttPenaltyRequestSize)),this.throughput=Gt.getSmoothedValue(t,-1,e),this.rtt=Gt.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=Gg();u&&this.throughput.next(u);let l=Yg();Bs(l)&&this.rtt.next(l)};at&&"onchange"in at&&this.subscription.add(Os(at,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Hu.set(Hg,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Hu.set(jg,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(ZR({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(eL(({throughput:n,rtt:o})=>Wg(n,o,e.rttPenaltyRequestSize)),tL(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=ve(),a=new Ug;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(Os(e,"progress").pipe(XR()).subscribe(s=>{t=s.loaded,r=ve()}));break;case 1:case 0:a.add(Os(e,"loadstart").subscribe(()=>{t=0,r=ve()}));break}a.add(Os(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=ve(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let a=0,s=ve(),n=0,o=ve(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>R(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(a,ve()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){if(ve()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=d.byteLength;else{let f=o-s;f&&this.addRawSpeed(n,f,1,t),n=d.byteLength,s=ve()}o=ve()}else a+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ve()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ve()-o,this.concurrentDownloads.size),n=0,o=ve());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,a=!1){if(i.sanityCheck(e,t,a)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=Hu.get(e);if(Bs(t))return(r=parseInt(t,10))!=null?r:void 0}},Qg=ju;import{fillWithDefault as iL,VideoQuality as zg}from"@vkontakte/videoplayer-shared";var Kg={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:zg.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:zg.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:500,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,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},useVolumeMultiplier:!1},Jg=i=>{var e;return B(A({},iL(i,Kg)),{configName:[...(e=i.configName)!=null?e:[],...Kg.configName]})};import{assertNonNullable as Vs,combine as _s,ErrorCategory as Ns,filter as ea,filterChanged as ke,fromEvent as Yu,isNonNullable as cL,isNullable as dL,Logger as pL,map as M,mapTo as tv,merge as It,now as Fs,once as st,Subject as j,Subscription as rv,tap as iv,ValueSubject as P,isHigher as hL,isInvariantQuality as av}from"@vkontakte/videoplayer-shared";import{merge as aL,map as sL,filter as Xg,isNonNullable as nL}from"@vkontakte/videoplayer-shared";var Gu=({seekState:i,position$:e})=>aL(i.stateChangeEnded$.pipe(sL(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),Xg(nL)),e.pipe(Xg(()=>i.getState().state==="none")));import{assertNonNullable as oL}from"@vkontakte/videoplayer-shared";var Zg=i=>{let e=typeof i.container=="string"?document.getElementById(i.container):i.container;return oL(e,`Wrong container or containerId {${i.container}}`),e};import{filter as uL,once as lL}from"@vkontakte/videoplayer-shared";var ev=(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(uL(a=>a.length>0),lL()).subscribe(a=>{a.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};var qs=class{constructor(e={configName:[]}){this.subscription=new rv;this.logger=new pL;this.abrLogger=this.logger.createComponentLog("ABR");this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),playbackRate:new C(1),externalTextTracks:new C([]),internalTextTracks:new C([]),currentTextTrack:new C(void 0),textTrackCuesSettings:new C({}),cameraOrientation:new C({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableQualities$:new P([]),availableQualitiesFps$:new P({}),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new j,ready$:new j,started$:new j,playing$:new j,paused$:new j,stopped$:new j,willStart$:new j,willResume$:new j,willPause$:new j,willStop$:new j,willDestruct$:new j,watchCoverageRecord$:new j,watchCoverageLive$:new j,managedError$:new j,fatalError$:new j,ended$:new j,looped$:new j,seeked$:new j,willSeek$:new j,firstBytes$:new j,firstFrame$:new j,canplay$:new j,log$:new j};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:wm};if(this.initLogs(),this.tuning=Jg(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new da({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Qg(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(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 u=n.map(d=>JSON.stringify(d,(p,h)=>{let f=typeof h;return["number","string","boolean"].includes(f)?h:h===null?null:`<${f}>`})),l=`Player.${String(r)}`,c=`Exception calling ${l} (${u.join(", ")})`;throw this.events.fatalError$.next({id:l,category:Ns.WTF,message:c,thrown:o}),o}}}})}initVideo(e){var t,r,a;return this.config=e,this.domContainer=Zg(e),this.chromecastInitializer.contentId=(t=e.meta)==null?void 0:t.videoId,this.providerContainer=new Zi({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,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&&!ci()?Yu(document,"visibilitychange").pipe(st()).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}setQuality(e){Vs(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(ea(r=>r.length>0),st()).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;Vs(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=>A({type:"external"},t))),this}selectTextTrack(e){var t;return ev(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(dL(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return cL(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(It(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(M(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ea(({from:e})=>e==="stopped"),st()).subscribe(()=>{this.initedAt=Fs(),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(B(A({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Ns.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(M(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(M(n=>n.destination),ke()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(M(n=>n.map(({quality:o})=>o).sort((o,u)=>av(o)?1:av(u)?-1:hL(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.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(ke()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ke()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ke()).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(M(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(_s({hasLiveOffsetByPaused:It(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(M(n=>n.to),ke(),M(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(_s({atLiveEdge:_s({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Gu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(M(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),ke(),iv(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(M(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(_s({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(M(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ke(),iv(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(M(n=>n.muted),ke()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(M(n=>n.volume),ke()).subscribe(this.info.volume$)).add(Gu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(It(e.providerOutput.endedEvent$.pipe(tv(!0)),e.providerOutput.seekedEvent$.pipe(tv(!1))).pipe(ke()).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(M(n=>({id:n?`No${n}`:"NoProviders",category:Ns.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(st(),M(n=>n!=null?n:Fs()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(st(),M(()=>Fs()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(st(),M(()=>Fs()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ea(({to:n})=>n==="playing"),st()).subscribe(()=>r.next(!1)));let a=0,s=It(e.providerOutput.isBuffering$,t,r).pipe(M(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),ke());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(It(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 u,l;let o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=n==null?void 0:n.size)==null?void 0:u.width,height:(l=n==null?void 0:n.size)==null?void 0:l.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(It(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,e.providerOutput.elementVisible$,this.chromecastInitializer.castState$).subscribe(()=>{let n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),l=e.providerOutput.elementVisible$.getValue(),c=this.chromecastInitializer.castState$.getValue(),d;c==="CONNECTED"?d="second_screen":u?l?n?d="pip":o?d="fullscreen":d="inline":d="invisible":d="none",this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(M(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 rv;this.subscription.add(t),this.subscription.add(e.current$.pipe(ke((r,a)=>r.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ea(r=>r.length>0),st()).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=bt(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(It(this.desiredState.videoTrack.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(M(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(M(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(M(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;Vs(this.providerContainer),Vs(e),Pm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>xm(r)),this.providerContainer.current$.subscribe(({type:r})=>si("provider",r)),e.duration$.subscribe(r=>si("duration",r)),e.availableVideoTracks$.pipe(ea(r=>!!r.length),st()).subscribe(r=>si("tracks",r)),this.events.fatalError$.subscribe(new ae("fatalError")),this.events.managedError$.subscribe(new ae("managedError")),e.position$.subscribe(new ae("position")),e.currentVideoTrack$.pipe(M(r=>r==null?void 0:r.quality)).subscribe(new ae("quality")),this.info.currentBuffer$.subscribe(new ae("buffer")),e.isBuffering$.subscribe(new ae("isBuffering"))].forEach(r=>this.subscription.add(r)),si("codecs",Dg())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>R(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Ns.DOM,message:String(a)})})});this.subscription.add(It(Yu(document,"visibilitychange"),Yu(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 Hj,Observable as jj,Subject as Gj,ValueSubject as Yj,VideoQuality as Wj}from"@vkontakte/videoplayer-shared";var Qj=`@vkontakte/videoplayer-core@${fl}`;export{la as ChromecastState,Zs as HttpConnectionType,jj as Observable,fe as PlaybackState,qs as Player,Qj as SDK_VERSION,Gj as Subject,Hj as Subscription,en as Surface,fl as VERSION,Yj as ValueSubject,kt as VideoFormat,Wj as VideoQuality};