@vkontakte/videoplayer-core 2.0.123-dev.499ebc9f.0 → 2.0.123-dev.8ba72ee5.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,51 +1,51 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.123-dev.499ebc9f.0
3
- * Tue, 17 Dec 2024 07:44:34 GMT
2
+ * @vkontakte/videoplayer-core v2.0.123-dev.8ba72ee5.0
3
+ * Wed, 18 Dec 2024 15:16:11 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-123/doc/
5
5
  */
6
- var FT=Object.create;var Yn=Object.defineProperty,qT=Object.defineProperties,UT=Object.getOwnPropertyDescriptor,HT=Object.getOwnPropertyDescriptors,jT=Object.getOwnPropertyNames,os=Object.getOwnPropertySymbols,QT=Object.getPrototypeOf,zn=Object.prototype.hasOwnProperty,Wc=Object.prototype.propertyIsEnumerable;var GT=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var et=Math.pow,Gc=(a,e,t)=>e in a?Yn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,P=(a,e)=>{for(var t in e||(e={}))zn.call(e,t)&&Gc(a,t,e[t]);if(os)for(var t of os(e))Wc.call(e,t)&&Gc(a,t,e[t]);return a},M=(a,e)=>qT(a,HT(e));var Yc=(a,e)=>{var t={};for(var r in a)zn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&os)for(var r of os(a))e.indexOf(r)<0&&Wc.call(a,r)&&(t[r]=a[r]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var WT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of jT(e))!zn.call(a,i)&&i!==t&&Yn(a,i,{get:()=>e[i],enumerable:!(r=UT(e,i))||r.enumerable});return a};var V=(a,e,t)=>(t=a!=null?FT(QT(a)):{},WT(e||!a||!a.__esModule?Yn(t,"default",{value:a,enumerable:!0}):t,a));var R=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Kn=function(a,e){this[0]=a,this[1]=e},re=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Kn,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?r(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>r("throw",p,u,l))}catch(p){l(p)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[GT("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var Z=f((Zn,Kc)=>{"use strict";var hi=function(a){return a&&a.Math===Math&&a};Kc.exports=hi(typeof globalThis=="object"&&globalThis)||hi(typeof window=="object"&&window)||hi(typeof self=="object"&&self)||hi(typeof global=="object"&&global)||hi(typeof Zn=="object"&&Zn)||function(){return this}()||Function("return this")()});var ce=f((gD,Jc)=>{"use strict";Jc.exports=function(a){try{return!!a()}catch(e){return!0}}});var mi=f((vD,Xc)=>{"use strict";var YT=ce();Xc.exports=!YT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var eo=f((SD,rd)=>{"use strict";var zT=mi(),td=Function.prototype,Zc=td.apply,ed=td.call;rd.exports=typeof Reflect=="object"&&Reflect.apply||(zT?ed.bind(Zc):function(){return ed.apply(Zc,arguments)})});var se=f((yD,sd)=>{"use strict";var id=mi(),ad=Function.prototype,to=ad.call,KT=id&&ad.bind.bind(to,to);sd.exports=id?KT:function(a){return function(){return to.apply(a,arguments)}}});var Jt=f((TD,od)=>{"use strict";var nd=se(),JT=nd({}.toString),XT=nd("".slice);od.exports=function(a){return XT(JT(a),8,-1)}});var ro=f((ID,ud)=>{"use strict";var ZT=Jt(),eI=se();ud.exports=function(a){if(ZT(a)==="Function")return eI(a)}});var X=f((ED,ld)=>{"use strict";var io=typeof document=="object"&&document.all;ld.exports=typeof io=="undefined"&&io!==void 0?function(a){return typeof a=="function"||a===io}:function(a){return typeof a=="function"}});var ke=f((xD,cd)=>{"use strict";var tI=ce();cd.exports=!tI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Re=f((PD,dd)=>{"use strict";var rI=mi(),ls=Function.prototype.call;dd.exports=rI?ls.bind(ls):function(){return ls.apply(ls,arguments)}});var ao=f(md=>{"use strict";var pd={}.propertyIsEnumerable,hd=Object.getOwnPropertyDescriptor,iI=hd&&!pd.call({1:2},1);md.f=iI?function(e){var t=hd(this,e);return!!t&&t.enumerable}:pd});var fi=f((wD,fd)=>{"use strict";fd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var gd=f((kD,bd)=>{"use strict";var aI=se(),sI=ce(),nI=Jt(),so=Object,oI=aI("".split);bd.exports=sI(function(){return!so("z").propertyIsEnumerable(0)})?function(a){return nI(a)==="String"?oI(a,""):so(a)}:so});var Ar=f((RD,vd)=>{"use strict";vd.exports=function(a){return a==null}});var kt=f(($D,Sd)=>{"use strict";var uI=Ar(),lI=TypeError;Sd.exports=function(a){if(uI(a))throw new lI("Can't call method on "+a);return a}});var Xt=f((LD,yd)=>{"use strict";var cI=gd(),dI=kt();yd.exports=function(a){return cI(dI(a))}});var $e=f((MD,Td)=>{"use strict";var pI=X();Td.exports=function(a){return typeof a=="object"?a!==null:pI(a)}});var wr=f((CD,Id)=>{"use strict";Id.exports={}});var lt=f((DD,xd)=>{"use strict";var no=wr(),oo=Z(),hI=X(),Ed=function(a){return hI(a)?a:void 0};xd.exports=function(a,e){return arguments.length<2?Ed(no[a])||Ed(oo[a]):no[a]&&no[a][e]||oo[a]&&oo[a][e]}});var bi=f((OD,Pd)=>{"use strict";var mI=se();Pd.exports=mI({}.isPrototypeOf)});var Zt=f((VD,kd)=>{"use strict";var fI=Z(),Ad=fI.navigator,wd=Ad&&Ad.userAgent;kd.exports=wd?String(wd):""});var lo=f((BD,Dd)=>{"use strict";var Cd=Z(),uo=Zt(),Rd=Cd.process,$d=Cd.Deno,Ld=Rd&&Rd.versions||$d&&$d.version,Md=Ld&&Ld.v8,Qe,cs;Md&&(Qe=Md.split("."),cs=Qe[0]>0&&Qe[0]<4?1:+(Qe[0]+Qe[1]));!cs&&uo&&(Qe=uo.match(/Edge\/(\d+)/),(!Qe||Qe[1]>=74)&&(Qe=uo.match(/Chrome\/(\d+)/),Qe&&(cs=+Qe[1])));Dd.exports=cs});var co=f((_D,Vd)=>{"use strict";var Od=lo(),bI=ce(),gI=Z(),vI=gI.String;Vd.exports=!!Object.getOwnPropertySymbols&&!bI(function(){var a=Symbol("symbol detection");return!vI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Od&&Od<41})});var po=f((ND,Bd)=>{"use strict";var SI=co();Bd.exports=SI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var ho=f((FD,_d)=>{"use strict";var yI=lt(),TI=X(),II=bi(),EI=po(),xI=Object;_d.exports=EI?function(a){return typeof a=="symbol"}:function(a){var e=yI("Symbol");return TI(e)&&II(e.prototype,xI(a))}});var gi=f((qD,Nd)=>{"use strict";var PI=String;Nd.exports=function(a){try{return PI(a)}catch(e){return"Object"}}});var tt=f((UD,Fd)=>{"use strict";var AI=X(),wI=gi(),kI=TypeError;Fd.exports=function(a){if(AI(a))return a;throw new kI(wI(a)+" is not a function")}});var vi=f((HD,qd)=>{"use strict";var RI=tt(),$I=Ar();qd.exports=function(a,e){var t=a[e];return $I(t)?void 0:RI(t)}});var Hd=f((jD,Ud)=>{"use strict";var mo=Re(),fo=X(),bo=$e(),LI=TypeError;Ud.exports=function(a,e){var t,r;if(e==="string"&&fo(t=a.toString)&&!bo(r=mo(t,a))||fo(t=a.valueOf)&&!bo(r=mo(t,a))||e!=="string"&&fo(t=a.toString)&&!bo(r=mo(t,a)))return r;throw new LI("Can't convert object to primitive value")}});var Ge=f((QD,jd)=>{"use strict";jd.exports=!0});var Wd=f((GD,Gd)=>{"use strict";var Qd=Z(),MI=Object.defineProperty;Gd.exports=function(a,e){try{MI(Qd,a,{value:e,configurable:!0,writable:!0})}catch(t){Qd[a]=e}return e}});var Si=f((WD,Kd)=>{"use strict";var CI=Ge(),DI=Z(),OI=Wd(),Yd="__core-js_shared__",zd=Kd.exports=DI[Yd]||OI(Yd,{});(zd.versions||(zd.versions=[])).push({version:"3.38.0",mode:CI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var go=f((YD,Xd)=>{"use strict";var Jd=Si();Xd.exports=function(a,e){return Jd[a]||(Jd[a]=e||{})}});var kr=f((zD,Zd)=>{"use strict";var VI=kt(),BI=Object;Zd.exports=function(a){return BI(VI(a))}});var We=f((KD,ep)=>{"use strict";var _I=se(),NI=kr(),FI=_I({}.hasOwnProperty);ep.exports=Object.hasOwn||function(e,t){return FI(NI(e),t)}});var vo=f((JD,tp)=>{"use strict";var qI=se(),UI=0,HI=Math.random(),jI=qI(1 .toString);tp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+jI(++UI+HI,36)}});var de=f((XD,ip)=>{"use strict";var QI=Z(),GI=go(),rp=We(),WI=vo(),YI=co(),zI=po(),Rr=QI.Symbol,So=GI("wks"),KI=zI?Rr.for||Rr:Rr&&Rr.withoutSetter||WI;ip.exports=function(a){return rp(So,a)||(So[a]=YI&&rp(Rr,a)?Rr[a]:KI("Symbol."+a)),So[a]}});var op=f((ZD,np)=>{"use strict";var JI=Re(),ap=$e(),sp=ho(),XI=vi(),ZI=Hd(),eE=de(),tE=TypeError,rE=eE("toPrimitive");np.exports=function(a,e){if(!ap(a)||sp(a))return a;var t=XI(a,rE),r;if(t){if(e===void 0&&(e="default"),r=JI(t,a,e),!ap(r)||sp(r))return r;throw new tE("Can't convert object to primitive value")}return e===void 0&&(e="number"),ZI(a,e)}});var yo=f((eO,up)=>{"use strict";var iE=op(),aE=ho();up.exports=function(a){var e=iE(a,"string");return aE(e)?e:e+""}});var ds=f((tO,cp)=>{"use strict";var sE=Z(),lp=$e(),To=sE.document,nE=lp(To)&&lp(To.createElement);cp.exports=function(a){return nE?To.createElement(a):{}}});var Io=f((rO,dp)=>{"use strict";var oE=ke(),uE=ce(),lE=ds();dp.exports=!oE&&!uE(function(){return Object.defineProperty(lE("div"),"a",{get:function(){return 7}}).a!==7})});var mp=f(hp=>{"use strict";var cE=ke(),dE=Re(),pE=ao(),hE=fi(),mE=Xt(),fE=yo(),bE=We(),gE=Io(),pp=Object.getOwnPropertyDescriptor;hp.f=cE?pp:function(e,t){if(e=mE(e),t=fE(t),gE)try{return pp(e,t)}catch(r){}if(bE(e,t))return hE(!dE(pE.f,e,t),e[t])}});var Eo=f((aO,fp)=>{"use strict";var vE=ce(),SE=X(),yE=/#|\.prototype\./,yi=function(a,e){var t=IE[TE(a)];return t===xE?!0:t===EE?!1:SE(e)?vE(e):!!e},TE=yi.normalize=function(a){return String(a).replace(yE,".").toLowerCase()},IE=yi.data={},EE=yi.NATIVE="N",xE=yi.POLYFILL="P";fp.exports=yi});var $r=f((sO,gp)=>{"use strict";var bp=ro(),PE=tt(),AE=mi(),wE=bp(bp.bind);gp.exports=function(a,e){return PE(a),e===void 0?a:AE?wE(a,e):function(){return a.apply(e,arguments)}}});var xo=f((nO,vp)=>{"use strict";var kE=ke(),RE=ce();vp.exports=kE&&RE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var rt=f((oO,Sp)=>{"use strict";var $E=$e(),LE=String,ME=TypeError;Sp.exports=function(a){if($E(a))return a;throw new ME(LE(a)+" is not an object")}});var er=f(Tp=>{"use strict";var CE=ke(),DE=Io(),OE=xo(),ps=rt(),yp=yo(),VE=TypeError,Po=Object.defineProperty,BE=Object.getOwnPropertyDescriptor,Ao="enumerable",wo="configurable",ko="writable";Tp.f=CE?OE?function(e,t,r){if(ps(e),t=yp(t),ps(r),typeof e=="function"&&t==="prototype"&&"value"in r&&ko in r&&!r[ko]){var i=BE(e,t);i&&i[ko]&&(e[t]=r.value,r={configurable:wo in r?r[wo]:i[wo],enumerable:Ao in r?r[Ao]:i[Ao],writable:!1})}return Po(e,t,r)}:Po:function(e,t,r){if(ps(e),t=yp(t),ps(r),DE)try{return Po(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new VE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Lr=f((lO,Ip)=>{"use strict";var _E=ke(),NE=er(),FE=fi();Ip.exports=_E?function(a,e,t){return NE.f(a,e,FE(1,t))}:function(a,e,t){return a[e]=t,a}});var te=f((cO,xp)=>{"use strict";var Ti=Z(),qE=eo(),UE=ro(),HE=X(),jE=mp().f,QE=Eo(),Mr=wr(),GE=$r(),Cr=Lr(),Ep=We();Si();var WE=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return qE(a,this,arguments)};return e.prototype=a.prototype,e};xp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Ti:i?Ti[t]:Ti[t]&&Ti[t].prototype,o=r?Mr:Mr[t]||Cr(Mr,t,{})[t],u=o.prototype,l,c,d,h,p,m,b,g,S;for(h in e)l=QE(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&Ep(n,h),m=o[h],c&&(a.dontCallGetSet?(S=jE(n,h),b=S&&S.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?g=GE(p,Ti):a.wrap&&c?g=WE(p):s&&HE(p)?g=UE(p):g=p,(a.sham||p&&p.sham||m&&m.sham)&&Cr(g,"sham",!0),Cr(o,h,g),s&&(d=t+"Prototype",Ep(Mr,d)||Cr(Mr,d,{}),Cr(Mr[d],h,p),a.real&&u&&(l||!u[h])&&Cr(u,h,p)))}});var Ap=f((dO,Pp)=>{"use strict";var YE=Math.ceil,zE=Math.floor;Pp.exports=Math.trunc||function(e){var t=+e;return(t>0?zE:YE)(t)}});var Ii=f((pO,wp)=>{"use strict";var KE=Ap();wp.exports=function(a){var e=+a;return e!==e||e===0?0:KE(e)}});var Rp=f((hO,kp)=>{"use strict";var JE=Ii(),XE=Math.max,ZE=Math.min;kp.exports=function(a,e){var t=JE(a);return t<0?XE(t+e,0):ZE(t,e)}});var Ro=f((mO,$p)=>{"use strict";var ex=Ii(),tx=Math.min;$p.exports=function(a){var e=ex(a);return e>0?tx(e,9007199254740991):0}});var Dr=f((fO,Lp)=>{"use strict";var rx=Ro();Lp.exports=function(a){return rx(a.length)}});var $o=f((bO,Cp)=>{"use strict";var ix=Xt(),ax=Rp(),sx=Dr(),Mp=function(a){return function(e,t,r){var i=ix(e),s=sx(i);if(s===0)return!a&&-1;var n=ax(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Cp.exports={includes:Mp(!0),indexOf:Mp(!1)}});var Ei=f((gO,Dp)=>{"use strict";Dp.exports=function(){}});var Op=f(()=>{"use strict";var nx=te(),ox=$o().includes,ux=ce(),lx=Ei(),cx=ux(function(){return!Array(1).includes()});nx({target:"Array",proto:!0,forced:cx},{includes:function(e){return ox(this,e,arguments.length>1?arguments[1]:void 0)}});lx("includes")});var Rt=f((yO,Vp)=>{"use strict";var dx=lt();Vp.exports=dx});var _p=f((TO,Bp)=>{"use strict";Op();var px=Rt();Bp.exports=px("Array","includes")});var Fp=f((IO,Np)=>{"use strict";var hx=_p();Np.exports=hx});var it=f((EO,qp)=>{"use strict";var mx=Fp();qp.exports=mx});var fs=f((OO,zp)=>{"use strict";var Ix=go(),Ex=vo(),Yp=Ix("keys");zp.exports=function(a){return Yp[a]||(Yp[a]=Ex(a))}});var Jp=f((VO,Kp)=>{"use strict";var xx=ce();Kp.exports=!xx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var bs=f((BO,Zp)=>{"use strict";var Px=We(),Ax=X(),wx=kr(),kx=fs(),Rx=Jp(),Xp=kx("IE_PROTO"),Co=Object,$x=Co.prototype;Zp.exports=Rx?Co.getPrototypeOf:function(a){var e=wx(a);if(Px(e,Xp))return e[Xp];var t=e.constructor;return Ax(t)&&e instanceof t?t.prototype:e instanceof Co?$x:null}});var gs=f((_O,eh)=>{"use strict";eh.exports={}});var ih=f((NO,rh)=>{"use strict";var Lx=se(),Do=We(),Mx=Xt(),Cx=$o().indexOf,Dx=gs(),th=Lx([].push);rh.exports=function(a,e){var t=Mx(a),r=0,i=[],s;for(s in t)!Do(Dx,s)&&Do(t,s)&&th(i,s);for(;e.length>r;)Do(t,s=e[r++])&&(~Cx(i,s)||th(i,s));return i}});var Oo=f((FO,ah)=>{"use strict";ah.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Vo=f((qO,sh)=>{"use strict";var Ox=ih(),Vx=Oo();sh.exports=Object.keys||function(e){return Ox(e,Vx)}});var Bo=f((UO,ch)=>{"use strict";var oh=ke(),Bx=ce(),uh=se(),_x=bs(),Nx=Vo(),Fx=Xt(),qx=ao().f,lh=uh(qx),Ux=uh([].push),Hx=oh&&Bx(function(){var a=Object.create(null);return a[2]=2,!lh(a,2)}),nh=function(a){return function(e){for(var t=Fx(e),r=Nx(t),i=Hx&&_x(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!oh||(i?u in t:lh(t,u)))&&Ux(o,a?[u,t[u]]:t[u]);return o}};ch.exports={entries:nh(!0),values:nh(!1)}});var dh=f(()=>{"use strict";var jx=te(),Qx=Bo().entries;jx({target:"Object",stat:!0},{entries:function(e){return Qx(e)}})});var hh=f((QO,ph)=>{"use strict";dh();var Gx=wr();ph.exports=Gx.Object.entries});var fh=f((GO,mh)=>{"use strict";var Wx=hh();mh.exports=Wx});var Or=f((WO,bh)=>{"use strict";var Yx=fh();bh.exports=Yx});var tr=f((YO,gh)=>{"use strict";gh.exports={}});var yh=f((zO,Sh)=>{"use strict";var zx=Z(),Kx=X(),vh=zx.WeakMap;Sh.exports=Kx(vh)&&/native code/.test(String(vh))});var qo=f((KO,Eh)=>{"use strict";var Jx=yh(),Ih=Z(),Xx=$e(),Zx=Lr(),_o=We(),No=Si(),eP=fs(),tP=gs(),Th="Object already initialized",Fo=Ih.TypeError,rP=Ih.WeakMap,vs,xi,Ss,iP=function(a){return Ss(a)?xi(a):vs(a,{})},aP=function(a){return function(e){var t;if(!Xx(e)||(t=xi(e)).type!==a)throw new Fo("Incompatible receiver, "+a+" required");return t}};Jx||No.state?(Ye=No.state||(No.state=new rP),Ye.get=Ye.get,Ye.has=Ye.has,Ye.set=Ye.set,vs=function(a,e){if(Ye.has(a))throw new Fo(Th);return e.facade=a,Ye.set(a,e),e},xi=function(a){return Ye.get(a)||{}},Ss=function(a){return Ye.has(a)}):(rr=eP("state"),tP[rr]=!0,vs=function(a,e){if(_o(a,rr))throw new Fo(Th);return e.facade=a,Zx(a,rr,e),e},xi=function(a){return _o(a,rr)?a[rr]:{}},Ss=function(a){return _o(a,rr)});var Ye,rr;Eh.exports={set:vs,get:xi,has:Ss,enforce:iP,getterFor:aP}});var jo=f((JO,Ph)=>{"use strict";var Uo=ke(),sP=We(),xh=Function.prototype,nP=Uo&&Object.getOwnPropertyDescriptor,Ho=sP(xh,"name"),oP=Ho&&function(){}.name==="something",uP=Ho&&(!Uo||Uo&&nP(xh,"name").configurable);Ph.exports={EXISTS:Ho,PROPER:oP,CONFIGURABLE:uP}});var wh=f(Ah=>{"use strict";var lP=ke(),cP=xo(),dP=er(),pP=rt(),hP=Xt(),mP=Vo();Ah.f=lP&&!cP?Object.defineProperties:function(e,t){pP(e);for(var r=hP(t),i=mP(t),s=i.length,n=0,o;s>n;)dP.f(e,o=i[n++],r[o]);return e}});var Qo=f((ZO,kh)=>{"use strict";var fP=lt();kh.exports=fP("document","documentElement")});var zo=f((eV,Oh)=>{"use strict";var bP=rt(),gP=wh(),Rh=Oo(),vP=gs(),SP=Qo(),yP=ds(),TP=fs(),$h=">",Lh="<",Wo="prototype",Yo="script",Ch=TP("IE_PROTO"),Go=function(){},Dh=function(a){return Lh+Yo+$h+a+Lh+"/"+Yo+$h},Mh=function(a){a.write(Dh("")),a.close();var e=a.parentWindow.Object;return a=null,e},IP=function(){var a=yP("iframe"),e="java"+Yo+":",t;return a.style.display="none",SP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Dh("document.F=Object")),t.close(),t.F},ys,Ts=function(){try{ys=new ActiveXObject("htmlfile")}catch(e){}Ts=typeof document!="undefined"?document.domain&&ys?Mh(ys):IP():Mh(ys);for(var a=Rh.length;a--;)delete Ts[Wo][Rh[a]];return Ts()};vP[Ch]=!0;Oh.exports=Object.create||function(e,t){var r;return e!==null?(Go[Wo]=bP(e),r=new Go,Go[Wo]=null,r[Ch]=e):r=Ts(),t===void 0?r:gP.f(r,t)}});var Vr=f((tV,Vh)=>{"use strict";var EP=Lr();Vh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:EP(a,e,t),a}});var Zo=f((rV,Nh)=>{"use strict";var xP=ce(),PP=X(),AP=$e(),wP=zo(),Bh=bs(),kP=Vr(),RP=de(),$P=Ge(),Xo=RP("iterator"),_h=!1,ct,Ko,Jo;[].keys&&(Jo=[].keys(),"next"in Jo?(Ko=Bh(Bh(Jo)),Ko!==Object.prototype&&(ct=Ko)):_h=!0);var LP=!AP(ct)||xP(function(){var a={};return ct[Xo].call(a)!==a});LP?ct={}:$P&&(ct=wP(ct));PP(ct[Xo])||kP(ct,Xo,function(){return this});Nh.exports={IteratorPrototype:ct,BUGGY_SAFARI_ITERATORS:_h}});var Is=f((iV,qh)=>{"use strict";var MP=de(),CP=MP("toStringTag"),Fh={};Fh[CP]="z";qh.exports=String(Fh)==="[object z]"});var Pi=f((aV,Uh)=>{"use strict";var DP=Is(),OP=X(),Es=Jt(),VP=de(),BP=VP("toStringTag"),_P=Object,NP=Es(function(){return arguments}())==="Arguments",FP=function(a,e){try{return a[e]}catch(t){}};Uh.exports=DP?Es:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=FP(e=_P(a),BP))=="string"?t:NP?Es(e):(r=Es(e))==="Object"&&OP(e.callee)?"Arguments":r}});var jh=f((sV,Hh)=>{"use strict";var qP=Is(),UP=Pi();Hh.exports=qP?{}.toString:function(){return"[object "+UP(this)+"]"}});var Ai=f((nV,Gh)=>{"use strict";var HP=Is(),jP=er().f,QP=Lr(),GP=We(),WP=jh(),YP=de(),Qh=YP("toStringTag");Gh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(GP(i,Qh)||jP(i,Qh,{configurable:!0,value:e}),r&&!HP&&QP(i,"toString",WP))}});var Yh=f((oV,Wh)=>{"use strict";var zP=Zo().IteratorPrototype,KP=zo(),JP=fi(),XP=Ai(),ZP=tr(),eA=function(){return this};Wh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=KP(zP,{next:JP(+!r,t)}),XP(a,i,!1,!0),ZP[i]=eA,a}});var Kh=f((uV,zh)=>{"use strict";var tA=se(),rA=tt();zh.exports=function(a,e,t){try{return tA(rA(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var Xh=f((lV,Jh)=>{"use strict";var iA=$e();Jh.exports=function(a){return iA(a)||a===null}});var em=f((cV,Zh)=>{"use strict";var aA=Xh(),sA=String,nA=TypeError;Zh.exports=function(a){if(aA(a))return a;throw new nA("Can't set "+sA(a)+" as a prototype")}});var eu=f((dV,tm)=>{"use strict";var oA=Kh(),uA=$e(),lA=kt(),cA=em();tm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=oA(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return lA(i),cA(s),uA(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var pm=f((pV,dm)=>{"use strict";var dA=te(),pA=Re(),xs=Ge(),lm=jo(),hA=X(),mA=Yh(),rm=bs(),im=eu(),fA=Ai(),bA=Lr(),tu=Vr(),gA=de(),am=tr(),cm=Zo(),vA=lm.PROPER,SA=lm.CONFIGURABLE,sm=cm.IteratorPrototype,Ps=cm.BUGGY_SAFARI_ITERATORS,wi=gA("iterator"),nm="keys",ki="values",om="entries",um=function(){return this};dm.exports=function(a,e,t,r,i,s,n){mA(t,e,r);var o=function(S){if(S===i&&h)return h;if(!Ps&&S&&S in c)return c[S];switch(S){case nm:return function(){return new t(this,S)};case ki:return function(){return new t(this,S)};case om:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[wi]||c["@@iterator"]||i&&c[i],h=!Ps&&d||o(i),p=e==="Array"&&c.entries||d,m,b,g;if(p&&(m=rm(p.call(new a)),m!==Object.prototype&&m.next&&(!xs&&rm(m)!==sm&&(im?im(m,sm):hA(m[wi])||tu(m,wi,um)),fA(m,u,!0,!0),xs&&(am[u]=um))),vA&&i===ki&&d&&d.name!==ki&&(!xs&&SA?bA(c,"name",ki):(l=!0,h=function(){return pA(d,this)})),i)if(b={values:o(ki),keys:s?h:o(nm),entries:o(om)},n)for(g in b)(Ps||l||!(g in c))&&tu(c,g,b[g]);else dA({target:e,proto:!0,forced:Ps||l},b);return(!xs||n)&&c[wi]!==h&&tu(c,wi,h,{name:i}),am[e]=h,b}});var mm=f((hV,hm)=>{"use strict";hm.exports=function(a,e){return{value:a,done:e}}});var iu=f((mV,Sm)=>{"use strict";var yA=Xt(),ru=Ei(),fm=tr(),gm=qo(),TA=er().f,IA=pm(),As=mm(),EA=Ge(),xA=ke(),vm="Array Iterator",PA=gm.set,AA=gm.getterFor(vm);Sm.exports=IA(Array,"Array",function(a,e){PA(this,{type:vm,target:yA(a),index:0,kind:e})},function(){var a=AA(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,As(void 0,!0);switch(a.kind){case"keys":return As(t,!1);case"values":return As(e[t],!1)}return As([t,e[t]],!1)},"values");var bm=fm.Arguments=fm.Array;ru("keys");ru("values");ru("entries");if(!EA&&xA&&bm.name!=="values")try{TA(bm,"name",{value:"values"})}catch(a){}});var Tm=f((fV,ym)=>{"use strict";var wA=de(),kA=tr(),RA=wA("iterator"),$A=Array.prototype;ym.exports=function(a){return a!==void 0&&(kA.Array===a||$A[RA]===a)}});var au=f((bV,Em)=>{"use strict";var LA=Pi(),Im=vi(),MA=Ar(),CA=tr(),DA=de(),OA=DA("iterator");Em.exports=function(a){if(!MA(a))return Im(a,OA)||Im(a,"@@iterator")||CA[LA(a)]}});var Pm=f((gV,xm)=>{"use strict";var VA=Re(),BA=tt(),_A=rt(),NA=gi(),FA=au(),qA=TypeError;xm.exports=function(a,e){var t=arguments.length<2?FA(a):e;if(BA(t))return _A(VA(t,a));throw new qA(NA(a)+" is not iterable")}});var km=f((vV,wm)=>{"use strict";var UA=Re(),Am=rt(),HA=vi();wm.exports=function(a,e,t){var r,i;Am(a);try{if(r=HA(a,"return"),!r){if(e==="throw")throw t;return t}r=UA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Am(r),t}});var ks=f((SV,Mm)=>{"use strict";var jA=$r(),QA=Re(),GA=rt(),WA=gi(),YA=Tm(),zA=Dr(),Rm=bi(),KA=Pm(),JA=au(),$m=km(),XA=TypeError,ws=function(a,e){this.stopped=a,this.result=e},Lm=ws.prototype;Mm.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=jA(e,r),l,c,d,h,p,m,b,g=function(v){return l&&$m(l,"normal",v),new ws(!0,v)},S=function(v){return i?(GA(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(s)l=a.iterator;else if(n)l=a;else{if(c=JA(a),!c)throw new XA(WA(a)+" is not iterable");if(YA(c)){for(d=0,h=zA(a);h>d;d++)if(p=S(a[d]),p&&Rm(Lm,p))return p;return new ws(!1)}l=KA(a,c)}for(m=s?a.next:l.next;!(b=QA(m,l)).done;){try{p=S(b.value)}catch(v){$m(l,"throw",v)}if(typeof p=="object"&&p&&Rm(Lm,p))return p}return new ws(!1)}});var Dm=f((yV,Cm)=>{"use strict";var ZA=ke(),ew=er(),tw=fi();Cm.exports=function(a,e,t){ZA?ew.f(a,e,tw(0,t)):a[e]=t}});var Om=f(()=>{"use strict";var rw=te(),iw=ks(),aw=Dm();rw({target:"Object",stat:!0},{fromEntries:function(e){var t={};return iw(e,function(r,i){aw(t,r,i)},{AS_ENTRIES:!0}),t}})});var Bm=f((EV,Vm)=>{"use strict";iu();Om();var sw=wr();Vm.exports=sw.Object.fromEntries});var Nm=f((xV,_m)=>{"use strict";_m.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 qm=f(()=>{"use strict";iu();var nw=Nm(),ow=Z(),uw=Ai(),Fm=tr();for(Rs in nw)uw(ow[Rs],Rs),Fm[Rs]=Fm.Array;var Rs});var Hm=f((wV,Um)=>{"use strict";var lw=Bm();qm();Um.exports=lw});var su=f((kV,jm)=>{"use strict";var cw=Hm();jm.exports=cw});var Qm=f(()=>{"use strict"});var nu=f((LV,Gm)=>{"use strict";var Ri=Z(),dw=Zt(),pw=Jt(),$s=function(a){return dw.slice(0,a.length)===a};Gm.exports=function(){return $s("Bun/")?"BUN":$s("Cloudflare-Workers")?"CLOUDFLARE":$s("Deno/")?"DENO":$s("Node.js/")?"NODE":Ri.Bun&&typeof Bun.version=="string"?"BUN":Ri.Deno&&typeof Deno.version=="object"?"DENO":pw(Ri.process)==="process"?"NODE":Ri.window&&Ri.document?"BROWSER":"REST"}()});var Ls=f((MV,Wm)=>{"use strict";var hw=nu();Wm.exports=hw==="NODE"});var zm=f((CV,Ym)=>{"use strict";var mw=er();Ym.exports=function(a,e,t){return mw.f(a,e,t)}});var Xm=f((DV,Jm)=>{"use strict";var fw=lt(),bw=zm(),gw=de(),vw=ke(),Km=gw("species");Jm.exports=function(a){var e=fw(a);vw&&e&&!e[Km]&&bw(e,Km,{configurable:!0,get:function(){return this}})}});var ef=f((OV,Zm)=>{"use strict";var Sw=bi(),yw=TypeError;Zm.exports=function(a,e){if(Sw(e,a))return a;throw new yw("Incorrect invocation")}});var uu=f((VV,tf)=>{"use strict";var Tw=se(),Iw=X(),ou=Si(),Ew=Tw(Function.toString);Iw(ou.inspectSource)||(ou.inspectSource=function(a){return Ew(a)});tf.exports=ou.inspectSource});var cu=f((BV,of)=>{"use strict";var xw=se(),Pw=ce(),rf=X(),Aw=Pi(),ww=lt(),kw=uu(),af=function(){},sf=ww("Reflect","construct"),lu=/^\s*(?:class|function)\b/,Rw=xw(lu.exec),$w=!lu.test(af),$i=function(e){if(!rf(e))return!1;try{return sf(af,[],e),!0}catch(t){return!1}},nf=function(e){if(!rf(e))return!1;switch(Aw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return $w||!!Rw(lu,kw(e))}catch(t){return!0}};nf.sham=!0;of.exports=!sf||Pw(function(){var a;return $i($i.call)||!$i(Object)||!$i(function(){a=!0})||a})?nf:$i});var lf=f((_V,uf)=>{"use strict";var Lw=cu(),Mw=gi(),Cw=TypeError;uf.exports=function(a){if(Lw(a))return a;throw new Cw(Mw(a)+" is not a constructor")}});var du=f((NV,df)=>{"use strict";var cf=rt(),Dw=lf(),Ow=Ar(),Vw=de(),Bw=Vw("species");df.exports=function(a,e){var t=cf(a).constructor,r;return t===void 0||Ow(r=cf(t)[Bw])?e:Dw(r)}});var hf=f((FV,pf)=>{"use strict";var _w=se();pf.exports=_w([].slice)});var ff=f((qV,mf)=>{"use strict";var Nw=TypeError;mf.exports=function(a,e){if(a<e)throw new Nw("Not enough arguments");return a}});var pu=f((UV,bf)=>{"use strict";var Fw=Zt();bf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(Fw)});var Tu=f((HV,Pf)=>{"use strict";var Le=Z(),qw=eo(),Uw=$r(),gf=X(),Hw=We(),xf=ce(),vf=Qo(),jw=hf(),Sf=ds(),Qw=ff(),Gw=pu(),Ww=Ls(),vu=Le.setImmediate,Su=Le.clearImmediate,Yw=Le.process,hu=Le.Dispatch,zw=Le.Function,yf=Le.MessageChannel,Kw=Le.String,mu=0,Li={},Tf="onreadystatechange",Mi,ir,fu,bu;xf(function(){Mi=Le.location});var yu=function(a){if(Hw(Li,a)){var e=Li[a];delete Li[a],e()}},gu=function(a){return function(){yu(a)}},If=function(a){yu(a.data)},Ef=function(a){Le.postMessage(Kw(a),Mi.protocol+"//"+Mi.host)};(!vu||!Su)&&(vu=function(e){Qw(arguments.length,1);var t=gf(e)?e:zw(e),r=jw(arguments,1);return Li[++mu]=function(){qw(t,void 0,r)},ir(mu),mu},Su=function(e){delete Li[e]},Ww?ir=function(a){Yw.nextTick(gu(a))}:hu&&hu.now?ir=function(a){hu.now(gu(a))}:yf&&!Gw?(fu=new yf,bu=fu.port2,fu.port1.onmessage=If,ir=Uw(bu.postMessage,bu)):Le.addEventListener&&gf(Le.postMessage)&&!Le.importScripts&&Mi&&Mi.protocol!=="file:"&&!xf(Ef)?(ir=Ef,Le.addEventListener("message",If,!1)):Tf in Sf("script")?ir=function(a){vf.appendChild(Sf("script"))[Tf]=function(){vf.removeChild(this),yu(a)}}:ir=function(a){setTimeout(gu(a),0)});Pf.exports={set:vu,clear:Su}});var kf=f((jV,wf)=>{"use strict";var Af=Z(),Jw=ke(),Xw=Object.getOwnPropertyDescriptor;wf.exports=function(a){if(!Jw)return Af[a];var e=Xw(Af,a);return e&&e.value}});var Iu=f((QV,$f)=>{"use strict";var Rf=function(){this.head=null,this.tail=null};Rf.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};$f.exports=Rf});var Mf=f((GV,Lf)=>{"use strict";var Zw=Zt();Lf.exports=/ipad|iphone|ipod/i.test(Zw)&&typeof Pebble!="undefined"});var Df=f((WV,Cf)=>{"use strict";var ek=Zt();Cf.exports=/web0s(?!.*chrome)/i.test(ek)});var qf=f((YV,Ff)=>{"use strict";var _r=Z(),tk=kf(),Of=$r(),Eu=Tu().set,rk=Iu(),ik=pu(),ak=Mf(),sk=Df(),xu=Ls(),Vf=_r.MutationObserver||_r.WebKitMutationObserver,Bf=_r.document,_f=_r.process,Ms=_r.Promise,wu=tk("queueMicrotask"),Br,Pu,Au,Cs,Nf;wu||(Ci=new rk,Di=function(){var a,e;for(xu&&(a=_f.domain)&&a.exit();e=Ci.get();)try{e()}catch(t){throw Ci.head&&Br(),t}a&&a.enter()},!ik&&!xu&&!sk&&Vf&&Bf?(Pu=!0,Au=Bf.createTextNode(""),new Vf(Di).observe(Au,{characterData:!0}),Br=function(){Au.data=Pu=!Pu}):!ak&&Ms&&Ms.resolve?(Cs=Ms.resolve(void 0),Cs.constructor=Ms,Nf=Of(Cs.then,Cs),Br=function(){Nf(Di)}):xu?Br=function(){_f.nextTick(Di)}:(Eu=Of(Eu,_r),Br=function(){Eu(Di)}),wu=function(a){Ci.head||Br(),Ci.add(a)});var Ci,Di;Ff.exports=wu});var Hf=f((zV,Uf)=>{"use strict";Uf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ds=f((KV,jf)=>{"use strict";jf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ar=f((JV,Qf)=>{"use strict";var nk=Z();Qf.exports=nk.Promise});var Nr=f((XV,zf)=>{"use strict";var ok=Z(),Oi=ar(),uk=X(),lk=Eo(),ck=uu(),dk=de(),Gf=nu(),pk=Ge(),ku=lo(),Wf=Oi&&Oi.prototype,hk=dk("species"),Ru=!1,Yf=uk(ok.PromiseRejectionEvent),mk=lk("Promise",function(){var a=ck(Oi),e=a!==String(Oi);if(!e&&ku===66||pk&&!(Wf.catch&&Wf.finally))return!0;if(!ku||ku<51||!/native code/.test(a)){var t=new Oi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[hk]=r,Ru=t.then(function(){})instanceof r,!Ru)return!0}return!e&&(Gf==="BROWSER"||Gf==="DENO")&&!Yf});zf.exports={CONSTRUCTOR:mk,REJECTION_EVENT:Yf,SUBCLASSING:Ru}});var Fr=f((ZV,Jf)=>{"use strict";var Kf=tt(),fk=TypeError,bk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new fk("Bad Promise constructor");e=r,t=i}),this.resolve=Kf(e),this.reject=Kf(t)};Jf.exports.f=function(a){return new bk(a)}});var bb=f(()=>{"use strict";var gk=te(),vk=Ge(),_s=Ls(),$t=Z(),jr=Re(),Xf=Vr(),Zf=eu(),Sk=Ai(),yk=Xm(),Tk=tt(),Bs=X(),Ik=$e(),Ek=ef(),xk=du(),ab=Tu().set,Du=qf(),Pk=Hf(),Ak=Ds(),wk=Iu(),sb=qo(),Ns=ar(),Ou=Nr(),nb=Fr(),Fs="Promise",ob=Ou.CONSTRUCTOR,kk=Ou.REJECTION_EVENT,Rk=Ou.SUBCLASSING,$u=sb.getterFor(Fs),$k=sb.set,qr=Ns&&Ns.prototype,sr=Ns,Os=qr,ub=$t.TypeError,Lu=$t.document,Vu=$t.process,Mu=nb.f,Lk=Mu,Mk=!!(Lu&&Lu.createEvent&&$t.dispatchEvent),lb="unhandledrejection",Ck="rejectionhandled",eb=0,cb=1,Dk=2,Bu=1,db=2,Vs,tb,Ok,rb,pb=function(a){var e;return Ik(a)&&Bs(e=a.then)?e:!1},hb=function(a,e){var t=e.value,r=e.state===cb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===db&&Bk(e),e.rejection=Bu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new ub("Promise-chain cycle")):(l=pb(u))?jr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},mb=function(a,e){a.notified||(a.notified=!0,Du(function(){for(var t=a.reactions,r;r=t.get();)hb(r,a);a.notified=!1,e&&!a.rejection&&Vk(a)}))},fb=function(a,e,t){var r,i;Mk?(r=Lu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),$t.dispatchEvent(r)):r={promise:e,reason:t},!kk&&(i=$t["on"+a])?i(r):a===lb&&Pk("Unhandled promise rejection",t)},Vk=function(a){jr(ab,$t,function(){var e=a.facade,t=a.value,r=ib(a),i;if(r&&(i=Ak(function(){_s?Vu.emit("unhandledRejection",t,e):fb(lb,e,t)}),a.rejection=_s||ib(a)?db:Bu,i.error))throw i.value})},ib=function(a){return a.rejection!==Bu&&!a.parent},Bk=function(a){jr(ab,$t,function(){var e=a.facade;_s?Vu.emit("rejectionHandled",e):fb(Ck,e,a.value)})},Ur=function(a,e,t){return function(r){a(e,r,t)}},Hr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Dk,mb(a,!0))},Cu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new ub("Promise can't be resolved itself");var r=pb(e);r?Du(function(){var i={done:!1};try{jr(r,e,Ur(Cu,i,a),Ur(Hr,i,a))}catch(s){Hr(i,s,a)}}):(a.value=e,a.state=cb,mb(a,!1))}catch(i){Hr({done:!1},i,a)}}};if(ob&&(sr=function(e){Ek(this,Os),Tk(e),jr(Vs,this);var t=$u(this);try{e(Ur(Cu,t),Ur(Hr,t))}catch(r){Hr(t,r)}},Os=sr.prototype,Vs=function(e){$k(this,{type:Fs,done:!1,notified:!1,parent:!1,reactions:new wk,rejection:!1,state:eb,value:void 0})},Vs.prototype=Xf(Os,"then",function(e,t){var r=$u(this),i=Mu(xk(this,sr));return r.parent=!0,i.ok=Bs(e)?e:!0,i.fail=Bs(t)&&t,i.domain=_s?Vu.domain:void 0,r.state===eb?r.reactions.add(i):Du(function(){hb(i,r)}),i.promise}),tb=function(){var a=new Vs,e=$u(a);this.promise=a,this.resolve=Ur(Cu,e),this.reject=Ur(Hr,e)},nb.f=Mu=function(a){return a===sr||a===Ok?new tb(a):Lk(a)},!vk&&Bs(Ns)&&qr!==Object.prototype)){rb=qr.then,Rk||Xf(qr,"then",function(e,t){var r=this;return new sr(function(i,s){jr(rb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete qr.constructor}catch(a){}Zf&&Zf(qr,Os)}gk({global:!0,constructor:!0,wrap:!0,forced:ob},{Promise:sr});Sk(sr,Fs,!1,!0);yk(Fs)});var Tb=f((rB,yb)=>{"use strict";var _k=de(),vb=_k("iterator"),Sb=!1;try{gb=0,_u={next:function(){return{done:!!gb++}},return:function(){Sb=!0}},_u[vb]=function(){return this},Array.from(_u,function(){throw 2})}catch(a){}var gb,_u;yb.exports=function(a,e){try{if(!e&&!Sb)return!1}catch(i){return!1}var t=!1;try{var r={};r[vb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Nu=f((iB,Ib)=>{"use strict";var Nk=ar(),Fk=Tb(),qk=Nr().CONSTRUCTOR;Ib.exports=qk||!Fk(function(a){Nk.all(a).then(void 0,function(){})})});var Eb=f(()=>{"use strict";var Uk=te(),Hk=Re(),jk=tt(),Qk=Fr(),Gk=Ds(),Wk=ks(),Yk=Nu();Uk({target:"Promise",stat:!0,forced:Yk},{all:function(e){var t=this,r=Qk.f(t),i=r.resolve,s=r.reject,n=Gk(function(){var o=jk(t.resolve),u=[],l=0,c=1;Wk(e,function(d){var h=l++,p=!1;c++,Hk(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Pb=f(()=>{"use strict";var zk=te(),Kk=Ge(),Jk=Nr().CONSTRUCTOR,qu=ar(),Xk=lt(),Zk=X(),eR=Vr(),xb=qu&&qu.prototype;zk({target:"Promise",proto:!0,forced:Jk,real:!0},{catch:function(a){return this.then(void 0,a)}});!Kk&&Zk(qu)&&(Fu=Xk("Promise").prototype.catch,xb.catch!==Fu&&eR(xb,"catch",Fu,{unsafe:!0}));var Fu});var Ab=f(()=>{"use strict";var tR=te(),rR=Re(),iR=tt(),aR=Fr(),sR=Ds(),nR=ks(),oR=Nu();tR({target:"Promise",stat:!0,forced:oR},{race:function(e){var t=this,r=aR.f(t),i=r.reject,s=sR(function(){var n=iR(t.resolve);nR(e,function(o){rR(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var wb=f(()=>{"use strict";var uR=te(),lR=Fr(),cR=Nr().CONSTRUCTOR;uR({target:"Promise",stat:!0,forced:cR},{reject:function(e){var t=lR.f(this),r=t.reject;return r(e),t.promise}})});var Uu=f((pB,kb)=>{"use strict";var dR=rt(),pR=$e(),hR=Fr();kb.exports=function(a,e){if(dR(a),pR(e)&&e.constructor===a)return e;var t=hR.f(a),r=t.resolve;return r(e),t.promise}});var Lb=f(()=>{"use strict";var mR=te(),fR=lt(),Rb=Ge(),bR=ar(),$b=Nr().CONSTRUCTOR,gR=Uu(),vR=fR("Promise"),SR=Rb&&!$b;mR({target:"Promise",stat:!0,forced:Rb||$b},{resolve:function(e){return gR(SR&&this===vR?bR:this,e)}})});var Mb=f(()=>{"use strict";bb();Eb();Pb();Ab();wb();Lb()});var Vb=f(()=>{"use strict";var yR=te(),TR=Ge(),qs=ar(),IR=ce(),Db=lt(),Ob=X(),ER=du(),Cb=Uu(),xR=Vr(),ju=qs&&qs.prototype,PR=!!qs&&IR(function(){ju.finally.call({then:function(){}},function(){})});yR({target:"Promise",proto:!0,real:!0,forced:PR},{finally:function(a){var e=ER(this,Db("Promise")),t=Ob(a);return this.then(t?function(r){return Cb(e,a()).then(function(){return r})}:a,t?function(r){return Cb(e,a()).then(function(){throw r})}:a)}});!TR&&Ob(qs)&&(Hu=Db("Promise").prototype.finally,ju.finally!==Hu&&xR(ju,"finally",Hu,{unsafe:!0}));var Hu});var _b=f((SB,Bb)=>{"use strict";Qm();Mb();Vb();var AR=Rt();Bb.exports=AR("Promise","finally")});var Fb=f((yB,Nb)=>{"use strict";var wR=_b();Nb.exports=wR});var Us=f((TB,qb)=>{"use strict";var kR=Fb();qb.exports=kR});var eg=f(()=>{"use strict";var UR=te(),HR=Bo().values;UR({target:"Object",stat:!0},{values:function(e){return HR(e)}})});var rg=f((s_,tg)=>{"use strict";eg();var jR=wr();tg.exports=jR.Object.values});var ag=f((n_,ig)=>{"use strict";var QR=rg();ig.exports=QR});var Bi=f((o_,sg)=>{"use strict";var GR=ag();sg.exports=GR});var vg=f(()=>{"use strict";var u$=te(),l$=kr(),c$=Dr(),d$=Ii(),p$=Ei();u$({target:"Array",proto:!0},{at:function(e){var t=l$(this),r=c$(t),i=d$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});p$("at")});var yg=f((O_,Sg)=>{"use strict";vg();var h$=Rt();Sg.exports=h$("Array","at")});var Ig=f((V_,Tg)=>{"use strict";var m$=yg();Tg.exports=m$});var Wr=f((B_,Eg)=>{"use strict";var f$=Ig();Eg.exports=f$});var hl=f((SF,Zg)=>{"use strict";var J$=Jt();Zg.exports=Array.isArray||function(e){return J$(e)==="Array"}});var tv=f((yF,ev)=>{"use strict";var X$=TypeError,Z$=9007199254740991;ev.exports=function(a){if(a>Z$)throw X$("Maximum allowed index exceeded");return a}});var av=f((TF,iv)=>{"use strict";var eL=hl(),tL=Dr(),rL=tv(),iL=$r(),rv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?iL(n,o):!1,d,h;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&eL(d)?(h=tL(d),u=rv(a,e,d,h,u,s-1)-1):(rL(u+1),a[u]=d),u++),l++;return u};iv.exports=rv});var uv=f((IF,ov)=>{"use strict";var sv=hl(),aL=cu(),sL=$e(),nL=de(),oL=nL("species"),nv=Array;ov.exports=function(a){var e;return sv(a)&&(e=a.constructor,aL(e)&&(e===nv||sv(e.prototype))?e=void 0:sL(e)&&(e=e[oL],e===null&&(e=void 0))),e===void 0?nv:e}});var cv=f((EF,lv)=>{"use strict";var uL=uv();lv.exports=function(a,e){return new(uL(a))(e===0?0:e)}});var dv=f(()=>{"use strict";var lL=te(),cL=av(),dL=tt(),pL=kr(),hL=Dr(),mL=cv();lL({target:"Array",proto:!0},{flatMap:function(e){var t=pL(this),r=hL(t),i;return dL(e),i=mL(t,0),i.length=cL(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var pv=f(()=>{"use strict";var fL=Ei();fL("flatMap")});var mv=f((kF,hv)=>{"use strict";dv();pv();var bL=Rt();hv.exports=bL("Array","flatMap")});var bv=f((RF,fv)=>{"use strict";var gL=mv();fv.exports=gL});var ml=f(($F,gv)=>{"use strict";var vL=bv();gv.exports=vL});var Ji=f((qF,Bv)=>{"use strict";var AL=Pi(),wL=String;Bv.exports=function(a){if(AL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return wL(a)}});var bl=f((UF,_v)=>{"use strict";_v.exports=`
7
- \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var qv=f((HF,Fv)=>{"use strict";var kL=se(),RL=kt(),$L=Ji(),vl=bl(),Nv=kL("".replace),LL=RegExp("^["+vl+"]+"),ML=RegExp("(^|[^"+vl+"])["+vl+"]+$"),gl=function(a){return function(e){var t=$L(RL(e));return a&1&&(t=Nv(t,LL,"")),a&2&&(t=Nv(t,ML,"$1")),t}};Fv.exports={start:gl(1),end:gl(2),trim:gl(3)}});var Qv=f((jF,jv)=>{"use strict";var CL=jo().PROPER,DL=ce(),Uv=bl(),Hv="\u200B\x85\u180E";jv.exports=function(a){return DL(function(){return!!Uv[a]()||Hv[a]()!==Hv||CL&&Uv[a].name!==a})}});var Sl=f((QF,Gv)=>{"use strict";var OL=qv().start,VL=Qv();Gv.exports=VL("trimStart")?function(){return OL(this)}:"".trimStart});var Yv=f(()=>{"use strict";var BL=te(),Wv=Sl();BL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Wv},{trimLeft:Wv})});var Kv=f(()=>{"use strict";Yv();var _L=te(),zv=Sl();_L({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==zv},{trimStart:zv})});var Xv=f((KF,Jv)=>{"use strict";Kv();var NL=Rt();Jv.exports=NL("String","trimLeft")});var eS=f((JF,Zv)=>{"use strict";var FL=Xv();Zv.exports=FL});var rS=f((XF,tS)=>{"use strict";var qL=eS();tS.exports=qL});var vS=f(()=>{"use strict"});var SS=f(()=>{"use strict"});var TS=f((P1,yS)=>{"use strict";var cM=$e(),dM=Jt(),pM=de(),hM=pM("match");yS.exports=function(a){var e;return cM(a)&&((e=a[hM])!==void 0?!!e:dM(a)==="RegExp")}});var ES=f((A1,IS)=>{"use strict";var mM=rt();IS.exports=function(){var a=mM(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var AS=f((w1,PS)=>{"use strict";var fM=Re(),bM=We(),gM=bi(),vM=ES(),xS=RegExp.prototype;PS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in xS)&&!bM(a,"flags")&&gM(xS,a)?fM(vM,a):e}});var kS=f((k1,wS)=>{"use strict";var kl=se(),SM=kr(),yM=Math.floor,Al=kl("".charAt),TM=kl("".replace),wl=kl("".slice),IM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,EM=/\$([$&'`]|\d{1,2})/g;wS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=EM;return i!==void 0&&(i=SM(i),u=IM),TM(s,u,function(l,c){var d;switch(Al(c,0)){case"$":return"$";case"&":return a;case"`":return wl(e,0,t);case"'":return wl(e,n);case"<":d=i[wl(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=yM(h/10);return p===0?l:p<=o?r[p-1]===void 0?Al(c,1):r[p-1]+Al(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var LS=f(()=>{"use strict";var xM=te(),PM=Re(),$l=se(),RS=kt(),AM=X(),wM=Ar(),kM=TS(),Zr=Ji(),RM=vi(),$M=AS(),LM=kS(),MM=de(),CM=Ge(),DM=MM("replace"),OM=TypeError,Rl=$l("".indexOf),VM=$l("".replace),$S=$l("".slice),BM=Math.max;xM({target:"String",proto:!0},{replaceAll:function(e,t){var r=RS(this),i,s,n,o,u,l,c,d,h,p,m=0,b="";if(!wM(e)){if(i=kM(e),i&&(s=Zr(RS($M(e))),!~Rl(s,"g")))throw new OM("`.replaceAll` does not allow non-global regexes");if(n=RM(e,DM),n)return PM(n,e,r,t);if(CM&&i)return VM(Zr(r),e,t)}for(o=Zr(r),u=Zr(e),l=AM(t),l||(t=Zr(t)),c=u.length,d=BM(1,c),h=Rl(o,u);h!==-1;)p=l?Zr(t(u,h,o)):LM(u,o,h,[],void 0,t),b+=$S(o,m,h)+p,m=h+c,h=h+d>o.length?-1:Rl(o,u,h+d);return m<o.length&&(b+=$S(o,m)),b}})});var CS=f((L1,MS)=>{"use strict";vS();SS();LS();var _M=Rt();MS.exports=_M("String","replaceAll")});var OS=f((M1,DS)=>{"use strict";var NM=CS();DS.exports=NM});var BS=f((C1,VS)=>{"use strict";var FM=OS();VS.exports=FM});var NS=f((D1,_S)=>{"use strict";var qM=Ii(),UM=Ji(),HM=kt(),jM=RangeError;_S.exports=function(e){var t=UM(HM(this)),r="",i=qM(e);if(i<0||i===1/0)throw new jM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var jS=f((O1,HS)=>{"use strict";var US=se(),QM=Ro(),FS=Ji(),GM=NS(),WM=kt(),YM=US(GM),zM=US("".slice),KM=Math.ceil,qS=function(a){return function(e,t,r){var i=FS(WM(e)),s=QM(t),n=i.length,o=r===void 0?" ":FS(r),u,l;return s<=n||o===""?i:(u=s-n,l=YM(o,KM(u/o.length)),l.length>u&&(l=zM(l,0,u)),a?i+l:l+i)}};HS.exports={start:qS(!1),end:qS(!0)}});var GS=f((V1,QS)=>{"use strict";var JM=Zt();QS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(JM)});var WS=f(()=>{"use strict";var XM=te(),ZM=jS().start,eC=GS();XM({target:"String",proto:!0,forced:eC},{padStart:function(e){return ZM(this,e,arguments.length>1?arguments[1]:void 0)}})});var zS=f((N1,YS)=>{"use strict";WS();var tC=Rt();YS.exports=tC("String","padStart")});var JS=f((F1,KS)=>{"use strict";var rC=zS();KS.exports=rC});var ZS=f((q1,XS)=>{"use strict";var iC=JS();XS.exports=iC});var zc="2.0.123-dev.499ebc9f.0";var ve=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ve||{}),wt=(T=>(T.MPEG="MPEG",T.DASH="DASH",T.DASH_SEP="DASH_SEP",T.DASH_SEP_VK="DASH_SEP",T.DASH_WEBM="DASH_WEBM",T.DASH_WEBM_AV1="DASH_WEBM_AV1",T.DASH_STREAMS="DASH_STREAMS",T.DASH_WEBM_VK="DASH_WEBM",T.DASH_ONDEMAND="DASH_ONDEMAND",T.DASH_ONDEMAND_VK="DASH_ONDEMAND",T.DASH_LIVE="DASH_LIVE",T.DASH_LIVE_CMAF="DASH_LIVE_CMAF",T.DASH_LIVE_WEBM="DASH_LIVE_WEBM",T.HLS="HLS",T.HLS_ONDEMAND="HLS_ONDEMAND",T.HLS_JS="HLS",T.HLS_LIVE="HLS_LIVE",T.HLS_LIVE_CMAF="HLS_LIVE_CMAF",T.WEB_RTC_LIVE="WEB_RTC_LIVE",T))(wt||{});var us=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(us||{}),Jn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Jn||{});var Xn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(Xn||{}),pi=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(pi||{});var kT=V(it(),1);import{assertNever as Wp,assertNonNullable as fx,isNonNullable as hs,ValueSubject as Lo,Subject as bx,Subscription as gx,merge as vx,observableFrom as Sx,fromEvent as Hp,map as jp,tap as Qp,filterChanged as yx,isNullable as Mo,ErrorCategory as Gp}from"@vkontakte/videoplayer-shared/es2015";var Up=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});var ms=class{constructor(e){this.connection$=new Lo(void 0);this.castState$=new Lo("NOT_AVAILABLE");this.errorEvent$=new bx;this.realCastState$=new Lo("NOT_AVAILABLE");this.subscription=new gx;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=hs((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},i||Up("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Gp.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,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){hs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Mo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Mo(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(Hp(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.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 Wp(i.sessionState)}})).add(vx(Hp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Qp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),jp(i=>i.castState)),Sx([r.getCastState()])).pipe(yx(),jp(Tx),Qp(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=hs(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();fx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Mo(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?hs(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;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:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Gp.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Tx=a=>{switch(a){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 Wp(a)}};var nc=V(it(),1),lT=V(Or(),1),cT=V(su(),1);var Jb=V(Us(),1);import{assertNever as Ub}from"@vkontakte/videoplayer-shared/es2015";var pe=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Ub(t)}return a},Hs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Ub(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as RR,Subject as js,merge as Hb}from"@vkontakte/videoplayer-shared/es2015";var C=class{constructor(e){this.transitionStarted$=new js;this.transitionEnded$=new js;this.transitionUpdated$=new js;this.forceChanged$=new js;this.stateChangeStarted$=Hb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Hb(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||RR(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 $R}from"@vkontakte/videoplayer-shared/es2015";var jb=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return $R(a)}};import{assertNever as Qr,assertNonNullable as nr,debounce as Qb,ErrorCategory as Gb,fromEvent as or,isNonNullable as Wb,map as Yb,merge as zb,observableFrom as LR,Subject as MR,Subscription as Qu,timeout as CR,getHighestQuality as DR}from"@vkontakte/videoplayer-shared/es2015";var OR=5,VR=5,BR=500,Kb=7e3,Vi=class{constructor(e){this.subscription=new Qu;this.loadMediaTimeoutSubscription=new Qu;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=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((i==null?void 0:i.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:Qr(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:Qr(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:Qr(e)}break}default:Qr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(jb(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 Qu;this.subscription.add(e),this.subscription.add(zb(this.videoState.stateChangeStarted$.pipe(Yb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Yb(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new MR;e.add(i.pipe(Qb(BR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(or(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)>OR)&&i.next(o),s=o})),e.add(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.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<VR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Qr(n)}}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=zb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,LR(["init"])).pipe(Qb(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"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(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"),x(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"),x(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"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i: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,i,s;switch(e){case"MPEG":{let c=t[e];nr(c);let d=DR(Object.keys(c));nr(d);let h=c[d];nr(h),r=h,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];nr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];nr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];nr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];nr(c),r=pe(c.url),i="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:Gb.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Qr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Wb(o)&&(n.metadata.title=o),Wb(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((i,s)=>{this.loadMediaTimeoutSubscription.add(CR(Kb).subscribe(()=>s(`timeout(${Kb})`)))});(0,Jb.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()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Gb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var dl=V(it(),1);import{clearVideoElement as Zb}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as _R}from"@vkontakte/videoplayer-shared/es2015";var Xb=a=>{try{a.pause(),a.playbackRate=0,_R(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as NR,Subscription as FR}from"@vkontakte/videoplayer-shared/es2015";var Gu=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)}},Wu=window.WeakMap?new WeakMap:new Gu,Yu=window.WeakMap?new WeakMap:new Map,qR=(a,e=20)=>{let t=0;return NR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Se=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Zb(t):(t=document.createElement("video"),a.appendChild(t)),Wu.set(t,r);let i=new FR;return i.add(qR(t,e)),Yu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},ye=a=>{let e=Yu.get(a);e==null||e.unsubscribe(),Yu.delete(a);let t=Wu.get(a);Wu.delete(a),t?Zb(a):Xb(a)};var Ku=V(Bi(),1);import{assertNonNullable as _i,isNonNullable as st,isNullable as zR,fromEvent as Gr,merge as ng,observableFrom as og,filterChanged as ug,map as Ni,Subject as lg,Subscription as KR,ValueSubject as JR,ErrorCategory as XR}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as zu,isNullable as WR,Subscription as YR}from"@vkontakte/videoplayer-shared/es2015";var Qs=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=WR(i),l=new YR;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},at=(a,e,t)=>Qs(e,()=>a.loop,r=>{zu(r)&&(a.loop=r)},{onError:t}),Te=(a,e,t,r)=>Qs(e,()=>({muted:a.muted,volume:a.volume}),i=>{zu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Be=(a,e,t,r)=>Qs(e,()=>a.playbackRate,i=>{zu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Lt=Qs;var ZR=a=>["__",a.language,a.label].join("|"),e$=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Ju=class a{constructor(){this.available$=new lg;this.current$=new JR(void 0);this.error$=new lg;this.subscription=new KR;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:XR.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(Lt(t.internalTextTracks,()=>(0,Ku.default)(this.internalTracks),s=>{st(s)&&this.setInternal(s)},{equal:(s,n)=>st(s)&&st(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ni(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Lt(t.externalTextTracks,()=>(0,Ku.default)(this.externalTracks),s=>{st(s)&&this.setExternal(s)},{equal:(s,n)=>st(s)&&st(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Ni(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Lt(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:i})),this.subscription.add(Lt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){_i(this.video);let{textTracks:e}=this.video;this.subscription.add(Gr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(ng(Gr(e,"addtrack"),Gr(e,"removetrack"),og(["init"])).pipe(Ni(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),ug((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(ng(Gr(e,"change"),og(["init"])).pipe(Ni(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Ni(r=>r&&this.htmlTextTrackToITextTrack(r).id),ug()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(Gr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Gr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;st(t.align)&&(i.align=t.align),st(t.position)&&(i.position=t.position),st(t.size)&&(i.size=t.size),st(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){_i(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:ZR(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.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:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){_i(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(zR(e)||!e$(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){_i(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){_i(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)}},_e=Ju;var pt=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 cg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},Xu=a=>{let e=cg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},dg=a=>{let e=cg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ne,map as Mt,merge as hg,filterChanged as r$,isNonNullable as mg,Subject as i$,filter as fg,mapTo as bg,combine as a$,once as s$,ErrorCategory as n$,ValueSubject as gg,clientChecker as o$}from"@vkontakte/videoplayer-shared/es2015";var t$=3,pg=(a,e,t=t$)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Ie=a=>{let e=T=>Ne(a,T).pipe(bg(void 0)),r=hg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(T=>Ne(a,T))).pipe(Mt(T=>T.type==="ended"?a.readyState<2:a.readyState<3),r$()),i=hg(Ne(a,"progress"),Ne(a,"timeupdate")).pipe(Mt(()=>pg(a.buffered,a.currentTime))),s=o$.isSafari?a$({play:e("play").pipe(s$()),playing:e("playing")}).pipe(bg(void 0)):e("playing"),n=Ne(a,"volumechange").pipe(Mt(()=>({muted:a.muted,volume:a.volume}))),o=Ne(a,"ratechange").pipe(Mt(()=>a.playbackRate)),u=Ne(a,"error").pipe(fg(()=>!!(a.error||a.played.length)),Mt(()=>{var I;let T=a.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:n$.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=Ne(a,"timeupdate").pipe(Mt(()=>a.currentTime)),c=new i$,d=.3,h;l.subscribe(T=>{a.loop&&mg(h)&&mg(T)&&h>=a.duration-d&&T<=d&&c.next(h),h=T});let p=e("pause").pipe(fg(()=>!a.error&&h!==a.duration)),m=Ne(a,"enterpictureinpicture"),b=Ne(a,"leavepictureinpicture"),g=new gg(dg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new gg(Xu(a));return Ne(a,"fullscreenchange").pipe(Mt(()=>Xu(a))).subscribe(S),{playing$:s,pause$:p,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ne(a,"durationchange").pipe(Mt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S,enterPip$:m,leavePip$:b}};import{VideoQuality as Ct}from"@vkontakte/videoplayer-shared/es2015";var Dt=a=>{switch(a){case"mobile":return Ct.Q_144P;case"lowest":return Ct.Q_240P;case"low":return Ct.Q_360P;case"sd":case"medium":return Ct.Q_480P;case"hd":case"high":return Ct.Q_720P;case"fullhd":case"full":return Ct.Q_1080P;case"quadhd":case"quad":return Ct.Q_1440P;case"ultrahd":case"ultra":return Ct.Q_2160P}};var Ot=V(Wr(),1),$g=V(it(),1),Ws=V(Or(),1);import{isNonNullable as ne,isNullable as el,now as Lg,isHigher as tl,isHigherOrEqual as rl,isInvariantQuality as wg,isLower as kg,isLowerOrEqual as il,videoSizeToQuality as b$,assertNotEmptyArray as Mg,assertNonNullable as g$}from"@vkontakte/videoplayer-shared/es2015";var Zu=!1,ht={},xg=a=>{Zu=a},Pg=()=>{ht={}},Ag=a=>{a(ht)},Fi=(a,e)=>{var t;Zu&&(ht.meta=(t=ht.meta)!=null?t:{},ht.meta[a]=e)},fe=class{constructor(e){this.name=e}next(e){var r,i;if(!Zu)return;ht.series=(r=ht.series)!=null?r:{};let t=(i=ht.series[this.name])!=null?i:[];t.push([Date.now(),e]),ht.series[this.name]=t}};function Gs({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}var v$=new fe("best_bitrate"),Cg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var al=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),qi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Lg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Dg='Assertion "ABR Tracks is empty array" failed',Ys=(a,e,t,r)=>{var u;let i=[...e].sort(al(1)),s=[...t].sort(al(1)),n=s.filter(l=>ne(l.bitrate)&&ne(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Ot.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Ot.default)(s,-1);return o&&(0,$g.default)(n,o)?o:n.length?(0,Ot.default)(n,-1):(0,Ot.default)(s,0)},Rg=a=>"quality"in a,Og=(a,e,t,r)=>{var n;let i=ne((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&ne(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Lg()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Rg(o)?"video":"audio",l=Rg(o)?o.quality:o.bitrate;return e({message:`
6
+ var _T=Object.create;var Gn=Object.defineProperty,NT=Object.defineProperties,FT=Object.getOwnPropertyDescriptor,qT=Object.getOwnPropertyDescriptors,UT=Object.getOwnPropertyNames,ns=Object.getOwnPropertySymbols,HT=Object.getPrototypeOf,Qn=Object.prototype.hasOwnProperty,jc=Object.prototype.propertyIsEnumerable;var jT=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var et=Math.pow,Hc=(a,e,t)=>e in a?Gn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,P=(a,e)=>{for(var t in e||(e={}))Qn.call(e,t)&&Hc(a,t,e[t]);if(ns)for(var t of ns(e))jc.call(e,t)&&Hc(a,t,e[t]);return a},M=(a,e)=>NT(a,qT(e));var Gc=(a,e)=>{var t={};for(var r in a)Qn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&ns)for(var r of ns(a))e.indexOf(r)<0&&jc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var GT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of UT(e))!Qn.call(a,i)&&i!==t&&Gn(a,i,{get:()=>e[i],enumerable:!(r=FT(e,i))||r.enumerable});return a};var F=(a,e,t)=>(t=a!=null?_T(HT(a)):{},GT(e||!a||!a.__esModule?Gn(t,"default",{value:a,enumerable:!0}):t,a));var k=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Wn=function(a,e){this[0]=a,this[1]=e},re=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Wn,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?r(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>r("throw",p,u,l))}catch(p){l(p)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[jT("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var Z=m((Kn,Wc)=>{"use strict";var pi=function(a){return a&&a.Math===Math&&a};Wc.exports=pi(typeof globalThis=="object"&&globalThis)||pi(typeof window=="object"&&window)||pi(typeof self=="object"&&self)||pi(typeof global=="object"&&global)||pi(typeof Kn=="object"&&Kn)||function(){return this}()||Function("return this")()});var pe=m((fD,Yc)=>{"use strict";Yc.exports=function(a){try{return!!a()}catch(e){return!0}}});var hi=m((mD,zc)=>{"use strict";var QT=pe();zc.exports=!QT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var Jn=m((bD,Zc)=>{"use strict";var WT=hi(),Xc=Function.prototype,Kc=Xc.apply,Jc=Xc.call;Zc.exports=typeof Reflect=="object"&&Reflect.apply||(WT?Jc.bind(Kc):function(){return Jc.apply(Kc,arguments)})});var se=m((gD,rd)=>{"use strict";var ed=hi(),td=Function.prototype,Xn=td.call,YT=ed&&td.bind.bind(Xn,Xn);rd.exports=ed?YT:function(a){return function(){return Xn.apply(a,arguments)}}});var Jt=m((vD,ad)=>{"use strict";var id=se(),zT=id({}.toString),KT=id("".slice);ad.exports=function(a){return KT(zT(a),8,-1)}});var Zn=m((SD,sd)=>{"use strict";var JT=Jt(),XT=se();sd.exports=function(a){if(JT(a)==="Function")return XT(a)}});var X=m((yD,nd)=>{"use strict";var eo=typeof document=="object"&&document.all;nd.exports=typeof eo=="undefined"&&eo!==void 0?function(a){return typeof a=="function"||a===eo}:function(a){return typeof a=="function"}});var ke=m((TD,od)=>{"use strict";var ZT=pe();od.exports=!ZT(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Re=m((ID,ud)=>{"use strict";var eI=hi(),us=Function.prototype.call;ud.exports=eI?us.bind(us):function(){return us.apply(us,arguments)}});var to=m(dd=>{"use strict";var ld={}.propertyIsEnumerable,cd=Object.getOwnPropertyDescriptor,tI=cd&&!ld.call({1:2},1);dd.f=tI?function(e){var t=cd(this,e);return!!t&&t.enumerable}:ld});var fi=m((xD,pd)=>{"use strict";pd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var fd=m((PD,hd)=>{"use strict";var rI=se(),iI=pe(),aI=Jt(),ro=Object,sI=rI("".split);hd.exports=iI(function(){return!ro("z").propertyIsEnumerable(0)})?function(a){return aI(a)==="String"?sI(a,""):ro(a)}:ro});var wr=m((AD,md)=>{"use strict";md.exports=function(a){return a==null}});var Rt=m((wD,bd)=>{"use strict";var nI=wr(),oI=TypeError;bd.exports=function(a){if(nI(a))throw new oI("Can't call method on "+a);return a}});var Xt=m((kD,gd)=>{"use strict";var uI=fd(),lI=Rt();gd.exports=function(a){return uI(lI(a))}});var $e=m((RD,vd)=>{"use strict";var cI=X();vd.exports=function(a){return typeof a=="object"?a!==null:cI(a)}});var kr=m(($D,Sd)=>{"use strict";Sd.exports={}});var lt=m((LD,Td)=>{"use strict";var io=kr(),ao=Z(),dI=X(),yd=function(a){return dI(a)?a:void 0};Td.exports=function(a,e){return arguments.length<2?yd(io[a])||yd(ao[a]):io[a]&&io[a][e]||ao[a]&&ao[a][e]}});var mi=m((MD,Id)=>{"use strict";var pI=se();Id.exports=pI({}.isPrototypeOf)});var Zt=m((CD,Pd)=>{"use strict";var hI=Z(),Ed=hI.navigator,xd=Ed&&Ed.userAgent;Pd.exports=xd?String(xd):""});var no=m((DD,Ld)=>{"use strict";var $d=Z(),so=Zt(),Ad=$d.process,wd=$d.Deno,kd=Ad&&Ad.versions||wd&&wd.version,Rd=kd&&kd.v8,Qe,ls;Rd&&(Qe=Rd.split("."),ls=Qe[0]>0&&Qe[0]<4?1:+(Qe[0]+Qe[1]));!ls&&so&&(Qe=so.match(/Edge\/(\d+)/),(!Qe||Qe[1]>=74)&&(Qe=so.match(/Chrome\/(\d+)/),Qe&&(ls=+Qe[1])));Ld.exports=ls});var oo=m((OD,Cd)=>{"use strict";var Md=no(),fI=pe(),mI=Z(),bI=mI.String;Cd.exports=!!Object.getOwnPropertySymbols&&!fI(function(){var a=Symbol("symbol detection");return!bI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Md&&Md<41})});var uo=m((VD,Dd)=>{"use strict";var gI=oo();Dd.exports=gI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var lo=m((BD,Od)=>{"use strict";var vI=lt(),SI=X(),yI=mi(),TI=uo(),II=Object;Od.exports=TI?function(a){return typeof a=="symbol"}:function(a){var e=vI("Symbol");return SI(e)&&yI(e.prototype,II(a))}});var bi=m((_D,Vd)=>{"use strict";var EI=String;Vd.exports=function(a){try{return EI(a)}catch(e){return"Object"}}});var tt=m((ND,Bd)=>{"use strict";var xI=X(),PI=bi(),AI=TypeError;Bd.exports=function(a){if(xI(a))return a;throw new AI(PI(a)+" is not a function")}});var gi=m((FD,_d)=>{"use strict";var wI=tt(),kI=wr();_d.exports=function(a,e){var t=a[e];return kI(t)?void 0:wI(t)}});var Fd=m((qD,Nd)=>{"use strict";var co=Re(),po=X(),ho=$e(),RI=TypeError;Nd.exports=function(a,e){var t,r;if(e==="string"&&po(t=a.toString)&&!ho(r=co(t,a))||po(t=a.valueOf)&&!ho(r=co(t,a))||e!=="string"&&po(t=a.toString)&&!ho(r=co(t,a)))return r;throw new RI("Can't convert object to primitive value")}});var We=m((UD,qd)=>{"use strict";qd.exports=!0});var jd=m((HD,Hd)=>{"use strict";var Ud=Z(),$I=Object.defineProperty;Hd.exports=function(a,e){try{$I(Ud,a,{value:e,configurable:!0,writable:!0})}catch(t){Ud[a]=e}return e}});var vi=m((jD,Wd)=>{"use strict";var LI=We(),MI=Z(),CI=jd(),Gd="__core-js_shared__",Qd=Wd.exports=MI[Gd]||CI(Gd,{});(Qd.versions||(Qd.versions=[])).push({version:"3.38.0",mode:LI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var fo=m((GD,zd)=>{"use strict";var Yd=vi();zd.exports=function(a,e){return Yd[a]||(Yd[a]=e||{})}});var Rr=m((QD,Kd)=>{"use strict";var DI=Rt(),OI=Object;Kd.exports=function(a){return OI(DI(a))}});var Ye=m((WD,Jd)=>{"use strict";var VI=se(),BI=Rr(),_I=VI({}.hasOwnProperty);Jd.exports=Object.hasOwn||function(e,t){return _I(BI(e),t)}});var mo=m((YD,Xd)=>{"use strict";var NI=se(),FI=0,qI=Math.random(),UI=NI(1 .toString);Xd.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+UI(++FI+qI,36)}});var he=m((zD,ep)=>{"use strict";var HI=Z(),jI=fo(),Zd=Ye(),GI=mo(),QI=oo(),WI=uo(),$r=HI.Symbol,bo=jI("wks"),YI=WI?$r.for||$r:$r&&$r.withoutSetter||GI;ep.exports=function(a){return Zd(bo,a)||(bo[a]=QI&&Zd($r,a)?$r[a]:YI("Symbol."+a)),bo[a]}});var ap=m((KD,ip)=>{"use strict";var zI=Re(),tp=$e(),rp=lo(),KI=gi(),JI=Fd(),XI=he(),ZI=TypeError,eE=XI("toPrimitive");ip.exports=function(a,e){if(!tp(a)||rp(a))return a;var t=KI(a,eE),r;if(t){if(e===void 0&&(e="default"),r=zI(t,a,e),!tp(r)||rp(r))return r;throw new ZI("Can't convert object to primitive value")}return e===void 0&&(e="number"),JI(a,e)}});var go=m((JD,sp)=>{"use strict";var tE=ap(),rE=lo();sp.exports=function(a){var e=tE(a,"string");return rE(e)?e:e+""}});var cs=m((XD,op)=>{"use strict";var iE=Z(),np=$e(),vo=iE.document,aE=np(vo)&&np(vo.createElement);op.exports=function(a){return aE?vo.createElement(a):{}}});var So=m((ZD,up)=>{"use strict";var sE=ke(),nE=pe(),oE=cs();up.exports=!sE&&!nE(function(){return Object.defineProperty(oE("div"),"a",{get:function(){return 7}}).a!==7})});var dp=m(cp=>{"use strict";var uE=ke(),lE=Re(),cE=to(),dE=fi(),pE=Xt(),hE=go(),fE=Ye(),mE=So(),lp=Object.getOwnPropertyDescriptor;cp.f=uE?lp:function(e,t){if(e=pE(e),t=hE(t),mE)try{return lp(e,t)}catch(r){}if(fE(e,t))return dE(!lE(cE.f,e,t),e[t])}});var yo=m((tO,pp)=>{"use strict";var bE=pe(),gE=X(),vE=/#|\.prototype\./,Si=function(a,e){var t=yE[SE(a)];return t===IE?!0:t===TE?!1:gE(e)?bE(e):!!e},SE=Si.normalize=function(a){return String(a).replace(vE,".").toLowerCase()},yE=Si.data={},TE=Si.NATIVE="N",IE=Si.POLYFILL="P";pp.exports=Si});var Lr=m((rO,fp)=>{"use strict";var hp=Zn(),EE=tt(),xE=hi(),PE=hp(hp.bind);fp.exports=function(a,e){return EE(a),e===void 0?a:xE?PE(a,e):function(){return a.apply(e,arguments)}}});var To=m((iO,mp)=>{"use strict";var AE=ke(),wE=pe();mp.exports=AE&&wE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var rt=m((aO,bp)=>{"use strict";var kE=$e(),RE=String,$E=TypeError;bp.exports=function(a){if(kE(a))return a;throw new $E(RE(a)+" is not an object")}});var er=m(vp=>{"use strict";var LE=ke(),ME=So(),CE=To(),ds=rt(),gp=go(),DE=TypeError,Io=Object.defineProperty,OE=Object.getOwnPropertyDescriptor,Eo="enumerable",xo="configurable",Po="writable";vp.f=LE?CE?function(e,t,r){if(ds(e),t=gp(t),ds(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Po in r&&!r[Po]){var i=OE(e,t);i&&i[Po]&&(e[t]=r.value,r={configurable:xo in r?r[xo]:i[xo],enumerable:Eo in r?r[Eo]:i[Eo],writable:!1})}return Io(e,t,r)}:Io:function(e,t,r){if(ds(e),t=gp(t),ds(r),ME)try{return Io(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new DE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Mr=m((nO,Sp)=>{"use strict";var VE=ke(),BE=er(),_E=fi();Sp.exports=VE?function(a,e,t){return BE.f(a,e,_E(1,t))}:function(a,e,t){return a[e]=t,a}});var te=m((oO,Tp)=>{"use strict";var yi=Z(),NE=Jn(),FE=Zn(),qE=X(),UE=dp().f,HE=yo(),Cr=kr(),jE=Lr(),Dr=Mr(),yp=Ye();vi();var GE=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return NE(a,this,arguments)};return e.prototype=a.prototype,e};Tp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?yi:i?yi[t]:yi[t]&&yi[t].prototype,o=r?Cr:Cr[t]||Dr(Cr,t,{})[t],u=o.prototype,l,c,d,h,p,f,b,g,S;for(h in e)l=HE(r?h:t+(i?".":"#")+h,a.forced),c=!l&&n&&yp(n,h),f=o[h],c&&(a.dontCallGetSet?(S=UE(n,h),b=S&&S.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof f==typeof p)&&(a.bind&&c?g=jE(p,yi):a.wrap&&c?g=GE(p):s&&qE(p)?g=FE(p):g=p,(a.sham||p&&p.sham||f&&f.sham)&&Dr(g,"sham",!0),Dr(o,h,g),s&&(d=t+"Prototype",yp(Cr,d)||Dr(Cr,d,{}),Dr(Cr[d],h,p),a.real&&u&&(l||!u[h])&&Dr(u,h,p)))}});var Ep=m((uO,Ip)=>{"use strict";var QE=Math.ceil,WE=Math.floor;Ip.exports=Math.trunc||function(e){var t=+e;return(t>0?WE:QE)(t)}});var Ti=m((lO,xp)=>{"use strict";var YE=Ep();xp.exports=function(a){var e=+a;return e!==e||e===0?0:YE(e)}});var Ap=m((cO,Pp)=>{"use strict";var zE=Ti(),KE=Math.max,JE=Math.min;Pp.exports=function(a,e){var t=zE(a);return t<0?KE(t+e,0):JE(t,e)}});var Ao=m((dO,wp)=>{"use strict";var XE=Ti(),ZE=Math.min;wp.exports=function(a){var e=XE(a);return e>0?ZE(e,9007199254740991):0}});var Or=m((pO,kp)=>{"use strict";var ex=Ao();kp.exports=function(a){return ex(a.length)}});var wo=m((hO,$p)=>{"use strict";var tx=Xt(),rx=Ap(),ix=Or(),Rp=function(a){return function(e,t,r){var i=tx(e),s=ix(i);if(s===0)return!a&&-1;var n=rx(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};$p.exports={includes:Rp(!0),indexOf:Rp(!1)}});var Ii=m((fO,Lp)=>{"use strict";Lp.exports=function(){}});var Mp=m(()=>{"use strict";var ax=te(),sx=wo().includes,nx=pe(),ox=Ii(),ux=nx(function(){return!Array(1).includes()});ax({target:"Array",proto:!0,forced:ux},{includes:function(e){return sx(this,e,arguments.length>1?arguments[1]:void 0)}});ox("includes")});var $t=m((gO,Cp)=>{"use strict";var lx=lt();Cp.exports=lx});var Op=m((vO,Dp)=>{"use strict";Mp();var cx=$t();Dp.exports=cx("Array","includes")});var Bp=m((SO,Vp)=>{"use strict";var dx=Op();Vp.exports=dx});var it=m((yO,_p)=>{"use strict";var px=Bp();_p.exports=px});var fs=m((MO,Qp)=>{"use strict";var yx=fo(),Tx=mo(),Gp=yx("keys");Qp.exports=function(a){return Gp[a]||(Gp[a]=Tx(a))}});var Yp=m((CO,Wp)=>{"use strict";var Ix=pe();Wp.exports=!Ix(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var ms=m((DO,Kp)=>{"use strict";var Ex=Ye(),xx=X(),Px=Rr(),Ax=fs(),wx=Yp(),zp=Ax("IE_PROTO"),$o=Object,kx=$o.prototype;Kp.exports=wx?$o.getPrototypeOf:function(a){var e=Px(a);if(Ex(e,zp))return e[zp];var t=e.constructor;return xx(t)&&e instanceof t?t.prototype:e instanceof $o?kx:null}});var bs=m((OO,Jp)=>{"use strict";Jp.exports={}});var eh=m((VO,Zp)=>{"use strict";var Rx=se(),Lo=Ye(),$x=Xt(),Lx=wo().indexOf,Mx=bs(),Xp=Rx([].push);Zp.exports=function(a,e){var t=$x(a),r=0,i=[],s;for(s in t)!Lo(Mx,s)&&Lo(t,s)&&Xp(i,s);for(;e.length>r;)Lo(t,s=e[r++])&&(~Lx(i,s)||Xp(i,s));return i}});var Mo=m((BO,th)=>{"use strict";th.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Co=m((_O,rh)=>{"use strict";var Cx=eh(),Dx=Mo();rh.exports=Object.keys||function(e){return Cx(e,Dx)}});var Do=m((NO,oh)=>{"use strict";var ah=ke(),Ox=pe(),sh=se(),Vx=ms(),Bx=Co(),_x=Xt(),Nx=to().f,nh=sh(Nx),Fx=sh([].push),qx=ah&&Ox(function(){var a=Object.create(null);return a[2]=2,!nh(a,2)}),ih=function(a){return function(e){for(var t=_x(e),r=Bx(t),i=qx&&Vx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!ah||(i?u in t:nh(t,u)))&&Fx(o,a?[u,t[u]]:t[u]);return o}};oh.exports={entries:ih(!0),values:ih(!1)}});var uh=m(()=>{"use strict";var Ux=te(),Hx=Do().entries;Ux({target:"Object",stat:!0},{entries:function(e){return Hx(e)}})});var ch=m((UO,lh)=>{"use strict";uh();var jx=kr();lh.exports=jx.Object.entries});var ph=m((HO,dh)=>{"use strict";var Gx=ch();dh.exports=Gx});var Vr=m((jO,hh)=>{"use strict";var Qx=ph();hh.exports=Qx});var tr=m((GO,fh)=>{"use strict";fh.exports={}});var gh=m((QO,bh)=>{"use strict";var Wx=Z(),Yx=X(),mh=Wx.WeakMap;bh.exports=Yx(mh)&&/native code/.test(String(mh))});var _o=m((WO,yh)=>{"use strict";var zx=gh(),Sh=Z(),Kx=$e(),Jx=Mr(),Oo=Ye(),Vo=vi(),Xx=fs(),Zx=bs(),vh="Object already initialized",Bo=Sh.TypeError,eP=Sh.WeakMap,gs,Ei,vs,tP=function(a){return vs(a)?Ei(a):gs(a,{})},rP=function(a){return function(e){var t;if(!Kx(e)||(t=Ei(e)).type!==a)throw new Bo("Incompatible receiver, "+a+" required");return t}};zx||Vo.state?(ze=Vo.state||(Vo.state=new eP),ze.get=ze.get,ze.has=ze.has,ze.set=ze.set,gs=function(a,e){if(ze.has(a))throw new Bo(vh);return e.facade=a,ze.set(a,e),e},Ei=function(a){return ze.get(a)||{}},vs=function(a){return ze.has(a)}):(rr=Xx("state"),Zx[rr]=!0,gs=function(a,e){if(Oo(a,rr))throw new Bo(vh);return e.facade=a,Jx(a,rr,e),e},Ei=function(a){return Oo(a,rr)?a[rr]:{}},vs=function(a){return Oo(a,rr)});var ze,rr;yh.exports={set:gs,get:Ei,has:vs,enforce:tP,getterFor:rP}});var qo=m((YO,Ih)=>{"use strict";var No=ke(),iP=Ye(),Th=Function.prototype,aP=No&&Object.getOwnPropertyDescriptor,Fo=iP(Th,"name"),sP=Fo&&function(){}.name==="something",nP=Fo&&(!No||No&&aP(Th,"name").configurable);Ih.exports={EXISTS:Fo,PROPER:sP,CONFIGURABLE:nP}});var xh=m(Eh=>{"use strict";var oP=ke(),uP=To(),lP=er(),cP=rt(),dP=Xt(),pP=Co();Eh.f=oP&&!uP?Object.defineProperties:function(e,t){cP(e);for(var r=dP(t),i=pP(t),s=i.length,n=0,o;s>n;)lP.f(e,o=i[n++],r[o]);return e}});var Uo=m((KO,Ph)=>{"use strict";var hP=lt();Ph.exports=hP("document","documentElement")});var Qo=m((JO,Mh)=>{"use strict";var fP=rt(),mP=xh(),Ah=Mo(),bP=bs(),gP=Uo(),vP=cs(),SP=fs(),wh=">",kh="<",jo="prototype",Go="script",$h=SP("IE_PROTO"),Ho=function(){},Lh=function(a){return kh+Go+wh+a+kh+"/"+Go+wh},Rh=function(a){a.write(Lh("")),a.close();var e=a.parentWindow.Object;return a=null,e},yP=function(){var a=vP("iframe"),e="java"+Go+":",t;return a.style.display="none",gP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Lh("document.F=Object")),t.close(),t.F},Ss,ys=function(){try{Ss=new ActiveXObject("htmlfile")}catch(e){}ys=typeof document!="undefined"?document.domain&&Ss?Rh(Ss):yP():Rh(Ss);for(var a=Ah.length;a--;)delete ys[jo][Ah[a]];return ys()};bP[$h]=!0;Mh.exports=Object.create||function(e,t){var r;return e!==null?(Ho[jo]=fP(e),r=new Ho,Ho[jo]=null,r[$h]=e):r=ys(),t===void 0?r:mP.f(r,t)}});var Br=m((XO,Ch)=>{"use strict";var TP=Mr();Ch.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:TP(a,e,t),a}});var Ko=m((ZO,Vh)=>{"use strict";var IP=pe(),EP=X(),xP=$e(),PP=Qo(),Dh=ms(),AP=Br(),wP=he(),kP=We(),zo=wP("iterator"),Oh=!1,ct,Wo,Yo;[].keys&&(Yo=[].keys(),"next"in Yo?(Wo=Dh(Dh(Yo)),Wo!==Object.prototype&&(ct=Wo)):Oh=!0);var RP=!xP(ct)||IP(function(){var a={};return ct[zo].call(a)!==a});RP?ct={}:kP&&(ct=PP(ct));EP(ct[zo])||AP(ct,zo,function(){return this});Vh.exports={IteratorPrototype:ct,BUGGY_SAFARI_ITERATORS:Oh}});var Ts=m((eV,_h)=>{"use strict";var $P=he(),LP=$P("toStringTag"),Bh={};Bh[LP]="z";_h.exports=String(Bh)==="[object z]"});var xi=m((tV,Nh)=>{"use strict";var MP=Ts(),CP=X(),Is=Jt(),DP=he(),OP=DP("toStringTag"),VP=Object,BP=Is(function(){return arguments}())==="Arguments",_P=function(a,e){try{return a[e]}catch(t){}};Nh.exports=MP?Is:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=_P(e=VP(a),OP))=="string"?t:BP?Is(e):(r=Is(e))==="Object"&&CP(e.callee)?"Arguments":r}});var qh=m((rV,Fh)=>{"use strict";var NP=Ts(),FP=xi();Fh.exports=NP?{}.toString:function(){return"[object "+FP(this)+"]"}});var Pi=m((iV,Hh)=>{"use strict";var qP=Ts(),UP=er().f,HP=Mr(),jP=Ye(),GP=qh(),QP=he(),Uh=QP("toStringTag");Hh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(jP(i,Uh)||UP(i,Uh,{configurable:!0,value:e}),r&&!qP&&HP(i,"toString",GP))}});var Gh=m((aV,jh)=>{"use strict";var WP=Ko().IteratorPrototype,YP=Qo(),zP=fi(),KP=Pi(),JP=tr(),XP=function(){return this};jh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=YP(WP,{next:zP(+!r,t)}),KP(a,i,!1,!0),JP[i]=XP,a}});var Wh=m((sV,Qh)=>{"use strict";var ZP=se(),eA=tt();Qh.exports=function(a,e,t){try{return ZP(eA(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var zh=m((nV,Yh)=>{"use strict";var tA=$e();Yh.exports=function(a){return tA(a)||a===null}});var Jh=m((oV,Kh)=>{"use strict";var rA=zh(),iA=String,aA=TypeError;Kh.exports=function(a){if(rA(a))return a;throw new aA("Can't set "+iA(a)+" as a prototype")}});var Jo=m((uV,Xh)=>{"use strict";var sA=Wh(),nA=$e(),oA=Rt(),uA=Jh();Xh.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=sA(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return oA(i),uA(s),nA(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var cf=m((lV,lf)=>{"use strict";var lA=te(),cA=Re(),Es=We(),of=qo(),dA=X(),pA=Gh(),Zh=ms(),ef=Jo(),hA=Pi(),fA=Mr(),Xo=Br(),mA=he(),tf=tr(),uf=Ko(),bA=of.PROPER,gA=of.CONFIGURABLE,rf=uf.IteratorPrototype,xs=uf.BUGGY_SAFARI_ITERATORS,Ai=mA("iterator"),af="keys",wi="values",sf="entries",nf=function(){return this};lf.exports=function(a,e,t,r,i,s,n){pA(t,e,r);var o=function(S){if(S===i&&h)return h;if(!xs&&S&&S in c)return c[S];switch(S){case af:return function(){return new t(this,S)};case wi:return function(){return new t(this,S)};case sf:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Ai]||c["@@iterator"]||i&&c[i],h=!xs&&d||o(i),p=e==="Array"&&c.entries||d,f,b,g;if(p&&(f=Zh(p.call(new a)),f!==Object.prototype&&f.next&&(!Es&&Zh(f)!==rf&&(ef?ef(f,rf):dA(f[Ai])||Xo(f,Ai,nf)),hA(f,u,!0,!0),Es&&(tf[u]=nf))),bA&&i===wi&&d&&d.name!==wi&&(!Es&&gA?fA(c,"name",wi):(l=!0,h=function(){return cA(d,this)})),i)if(b={values:o(wi),keys:s?h:o(af),entries:o(sf)},n)for(g in b)(xs||l||!(g in c))&&Xo(c,g,b[g]);else lA({target:e,proto:!0,forced:xs||l},b);return(!Es||n)&&c[Ai]!==h&&Xo(c,Ai,h,{name:i}),tf[e]=h,b}});var pf=m((cV,df)=>{"use strict";df.exports=function(a,e){return{value:a,done:e}}});var eu=m((dV,gf)=>{"use strict";var vA=Xt(),Zo=Ii(),hf=tr(),mf=_o(),SA=er().f,yA=cf(),Ps=pf(),TA=We(),IA=ke(),bf="Array Iterator",EA=mf.set,xA=mf.getterFor(bf);gf.exports=yA(Array,"Array",function(a,e){EA(this,{type:bf,target:vA(a),index:0,kind:e})},function(){var a=xA(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ps(void 0,!0);switch(a.kind){case"keys":return Ps(t,!1);case"values":return Ps(e[t],!1)}return Ps([t,e[t]],!1)},"values");var ff=hf.Arguments=hf.Array;Zo("keys");Zo("values");Zo("entries");if(!TA&&IA&&ff.name!=="values")try{SA(ff,"name",{value:"values"})}catch(a){}});var Sf=m((pV,vf)=>{"use strict";var PA=he(),AA=tr(),wA=PA("iterator"),kA=Array.prototype;vf.exports=function(a){return a!==void 0&&(AA.Array===a||kA[wA]===a)}});var tu=m((hV,Tf)=>{"use strict";var RA=xi(),yf=gi(),$A=wr(),LA=tr(),MA=he(),CA=MA("iterator");Tf.exports=function(a){if(!$A(a))return yf(a,CA)||yf(a,"@@iterator")||LA[RA(a)]}});var Ef=m((fV,If)=>{"use strict";var DA=Re(),OA=tt(),VA=rt(),BA=bi(),_A=tu(),NA=TypeError;If.exports=function(a,e){var t=arguments.length<2?_A(a):e;if(OA(t))return VA(DA(t,a));throw new NA(BA(a)+" is not iterable")}});var Af=m((mV,Pf)=>{"use strict";var FA=Re(),xf=rt(),qA=gi();Pf.exports=function(a,e,t){var r,i;xf(a);try{if(r=qA(a,"return"),!r){if(e==="throw")throw t;return t}r=FA(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return xf(r),t}});var ws=m((bV,$f)=>{"use strict";var UA=Lr(),HA=Re(),jA=rt(),GA=bi(),QA=Sf(),WA=Or(),wf=mi(),YA=Ef(),zA=tu(),kf=Af(),KA=TypeError,As=function(a,e){this.stopped=a,this.result=e},Rf=As.prototype;$f.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=UA(e,r),l,c,d,h,p,f,b,g=function(v){return l&&kf(l,"normal",v),new As(!0,v)},S=function(v){return i?(jA(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(s)l=a.iterator;else if(n)l=a;else{if(c=zA(a),!c)throw new KA(GA(a)+" is not iterable");if(QA(c)){for(d=0,h=WA(a);h>d;d++)if(p=S(a[d]),p&&wf(Rf,p))return p;return new As(!1)}l=YA(a,c)}for(f=s?a.next:l.next;!(b=HA(f,l)).done;){try{p=S(b.value)}catch(v){kf(l,"throw",v)}if(typeof p=="object"&&p&&wf(Rf,p))return p}return new As(!1)}});var Mf=m((gV,Lf)=>{"use strict";var JA=ke(),XA=er(),ZA=fi();Lf.exports=function(a,e,t){JA?XA.f(a,e,ZA(0,t)):a[e]=t}});var Cf=m(()=>{"use strict";var ew=te(),tw=ws(),rw=Mf();ew({target:"Object",stat:!0},{fromEntries:function(e){var t={};return tw(e,function(r,i){rw(t,r,i)},{AS_ENTRIES:!0}),t}})});var Of=m((yV,Df)=>{"use strict";eu();Cf();var iw=kr();Df.exports=iw.Object.fromEntries});var Bf=m((TV,Vf)=>{"use strict";Vf.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 Nf=m(()=>{"use strict";eu();var aw=Bf(),sw=Z(),nw=Pi(),_f=tr();for(ks in aw)nw(sw[ks],ks),_f[ks]=_f.Array;var ks});var qf=m((xV,Ff)=>{"use strict";var ow=Of();Nf();Ff.exports=ow});var ru=m((PV,Uf)=>{"use strict";var uw=qf();Uf.exports=uw});var Hf=m(()=>{"use strict"});var iu=m((kV,jf)=>{"use strict";var ki=Z(),lw=Zt(),cw=Jt(),Rs=function(a){return lw.slice(0,a.length)===a};jf.exports=function(){return Rs("Bun/")?"BUN":Rs("Cloudflare-Workers")?"CLOUDFLARE":Rs("Deno/")?"DENO":Rs("Node.js/")?"NODE":ki.Bun&&typeof Bun.version=="string"?"BUN":ki.Deno&&typeof Deno.version=="object"?"DENO":cw(ki.process)==="process"?"NODE":ki.window&&ki.document?"BROWSER":"REST"}()});var $s=m((RV,Gf)=>{"use strict";var dw=iu();Gf.exports=dw==="NODE"});var Wf=m(($V,Qf)=>{"use strict";var pw=er();Qf.exports=function(a,e,t){return pw.f(a,e,t)}});var Kf=m((LV,zf)=>{"use strict";var hw=lt(),fw=Wf(),mw=he(),bw=ke(),Yf=mw("species");zf.exports=function(a){var e=hw(a);bw&&e&&!e[Yf]&&fw(e,Yf,{configurable:!0,get:function(){return this}})}});var Xf=m((MV,Jf)=>{"use strict";var gw=mi(),vw=TypeError;Jf.exports=function(a,e){if(gw(e,a))return a;throw new vw("Incorrect invocation")}});var su=m((CV,Zf)=>{"use strict";var Sw=se(),yw=X(),au=vi(),Tw=Sw(Function.toString);yw(au.inspectSource)||(au.inspectSource=function(a){return Tw(a)});Zf.exports=au.inspectSource});var ou=m((DV,am)=>{"use strict";var Iw=se(),Ew=pe(),em=X(),xw=xi(),Pw=lt(),Aw=su(),tm=function(){},rm=Pw("Reflect","construct"),nu=/^\s*(?:class|function)\b/,ww=Iw(nu.exec),kw=!nu.test(tm),Ri=function(e){if(!em(e))return!1;try{return rm(tm,[],e),!0}catch(t){return!1}},im=function(e){if(!em(e))return!1;switch(xw(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return kw||!!ww(nu,Aw(e))}catch(t){return!0}};im.sham=!0;am.exports=!rm||Ew(function(){var a;return Ri(Ri.call)||!Ri(Object)||!Ri(function(){a=!0})||a})?im:Ri});var nm=m((OV,sm)=>{"use strict";var Rw=ou(),$w=bi(),Lw=TypeError;sm.exports=function(a){if(Rw(a))return a;throw new Lw($w(a)+" is not a constructor")}});var uu=m((VV,um)=>{"use strict";var om=rt(),Mw=nm(),Cw=wr(),Dw=he(),Ow=Dw("species");um.exports=function(a,e){var t=om(a).constructor,r;return t===void 0||Cw(r=om(t)[Ow])?e:Mw(r)}});var cm=m((BV,lm)=>{"use strict";var Vw=se();lm.exports=Vw([].slice)});var pm=m((_V,dm)=>{"use strict";var Bw=TypeError;dm.exports=function(a,e){if(a<e)throw new Bw("Not enough arguments");return a}});var lu=m((NV,hm)=>{"use strict";var _w=Zt();hm.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(_w)});var vu=m((FV,Im)=>{"use strict";var Le=Z(),Nw=Jn(),Fw=Lr(),fm=X(),qw=Ye(),Tm=pe(),mm=Uo(),Uw=cm(),bm=cs(),Hw=pm(),jw=lu(),Gw=$s(),mu=Le.setImmediate,bu=Le.clearImmediate,Qw=Le.process,cu=Le.Dispatch,Ww=Le.Function,gm=Le.MessageChannel,Yw=Le.String,du=0,$i={},vm="onreadystatechange",Li,ir,pu,hu;Tm(function(){Li=Le.location});var gu=function(a){if(qw($i,a)){var e=$i[a];delete $i[a],e()}},fu=function(a){return function(){gu(a)}},Sm=function(a){gu(a.data)},ym=function(a){Le.postMessage(Yw(a),Li.protocol+"//"+Li.host)};(!mu||!bu)&&(mu=function(e){Hw(arguments.length,1);var t=fm(e)?e:Ww(e),r=Uw(arguments,1);return $i[++du]=function(){Nw(t,void 0,r)},ir(du),du},bu=function(e){delete $i[e]},Gw?ir=function(a){Qw.nextTick(fu(a))}:cu&&cu.now?ir=function(a){cu.now(fu(a))}:gm&&!jw?(pu=new gm,hu=pu.port2,pu.port1.onmessage=Sm,ir=Fw(hu.postMessage,hu)):Le.addEventListener&&fm(Le.postMessage)&&!Le.importScripts&&Li&&Li.protocol!=="file:"&&!Tm(ym)?(ir=ym,Le.addEventListener("message",Sm,!1)):vm in bm("script")?ir=function(a){mm.appendChild(bm("script"))[vm]=function(){mm.removeChild(this),gu(a)}}:ir=function(a){setTimeout(fu(a),0)});Im.exports={set:mu,clear:bu}});var Pm=m((qV,xm)=>{"use strict";var Em=Z(),zw=ke(),Kw=Object.getOwnPropertyDescriptor;xm.exports=function(a){if(!zw)return Em[a];var e=Kw(Em,a);return e&&e.value}});var Su=m((UV,wm)=>{"use strict";var Am=function(){this.head=null,this.tail=null};Am.prototype={add:function(a){var e={item:a,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var a=this.head;if(a){var e=this.head=a.next;return e===null&&(this.tail=null),a.item}}};wm.exports=Am});var Rm=m((HV,km)=>{"use strict";var Jw=Zt();km.exports=/ipad|iphone|ipod/i.test(Jw)&&typeof Pebble!="undefined"});var Lm=m((jV,$m)=>{"use strict";var Xw=Zt();$m.exports=/web0s(?!.*chrome)/i.test(Xw)});var _m=m((GV,Bm)=>{"use strict";var Nr=Z(),Zw=Pm(),Mm=Lr(),yu=vu().set,ek=Su(),tk=lu(),rk=Rm(),ik=Lm(),Tu=$s(),Cm=Nr.MutationObserver||Nr.WebKitMutationObserver,Dm=Nr.document,Om=Nr.process,Ls=Nr.Promise,xu=Zw("queueMicrotask"),_r,Iu,Eu,Ms,Vm;xu||(Mi=new ek,Ci=function(){var a,e;for(Tu&&(a=Om.domain)&&a.exit();e=Mi.get();)try{e()}catch(t){throw Mi.head&&_r(),t}a&&a.enter()},!tk&&!Tu&&!ik&&Cm&&Dm?(Iu=!0,Eu=Dm.createTextNode(""),new Cm(Ci).observe(Eu,{characterData:!0}),_r=function(){Eu.data=Iu=!Iu}):!rk&&Ls&&Ls.resolve?(Ms=Ls.resolve(void 0),Ms.constructor=Ls,Vm=Mm(Ms.then,Ms),_r=function(){Vm(Ci)}):Tu?_r=function(){Om.nextTick(Ci)}:(yu=Mm(yu,Nr),_r=function(){yu(Ci)}),xu=function(a){Mi.head||_r(),Mi.add(a)});var Mi,Ci;Bm.exports=xu});var Fm=m((QV,Nm)=>{"use strict";Nm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Cs=m((WV,qm)=>{"use strict";qm.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ar=m((YV,Um)=>{"use strict";var ak=Z();Um.exports=ak.Promise});var Fr=m((zV,Qm)=>{"use strict";var sk=Z(),Di=ar(),nk=X(),ok=yo(),uk=su(),lk=he(),Hm=iu(),ck=We(),Pu=no(),jm=Di&&Di.prototype,dk=lk("species"),Au=!1,Gm=nk(sk.PromiseRejectionEvent),pk=ok("Promise",function(){var a=uk(Di),e=a!==String(Di);if(!e&&Pu===66||ck&&!(jm.catch&&jm.finally))return!0;if(!Pu||Pu<51||!/native code/.test(a)){var t=new Di(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[dk]=r,Au=t.then(function(){})instanceof r,!Au)return!0}return!e&&(Hm==="BROWSER"||Hm==="DENO")&&!Gm});Qm.exports={CONSTRUCTOR:pk,REJECTION_EVENT:Gm,SUBCLASSING:Au}});var qr=m((KV,Ym)=>{"use strict";var Wm=tt(),hk=TypeError,fk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new hk("Bad Promise constructor");e=r,t=i}),this.resolve=Wm(e),this.reject=Wm(t)};Ym.exports.f=function(a){return new fk(a)}});var hb=m(()=>{"use strict";var mk=te(),bk=We(),Bs=$s(),Lt=Z(),Gr=Re(),zm=Br(),Km=Jo(),gk=Pi(),vk=Kf(),Sk=tt(),Vs=X(),yk=$e(),Tk=Xf(),Ik=uu(),tb=vu().set,Lu=_m(),Ek=Fm(),xk=Cs(),Pk=Su(),rb=_o(),_s=ar(),Mu=Fr(),ib=qr(),Ns="Promise",ab=Mu.CONSTRUCTOR,Ak=Mu.REJECTION_EVENT,wk=Mu.SUBCLASSING,wu=rb.getterFor(Ns),kk=rb.set,Ur=_s&&_s.prototype,sr=_s,Ds=Ur,sb=Lt.TypeError,ku=Lt.document,Cu=Lt.process,Ru=ib.f,Rk=Ru,$k=!!(ku&&ku.createEvent&&Lt.dispatchEvent),nb="unhandledrejection",Lk="rejectionhandled",Jm=0,ob=1,Mk=2,Du=1,ub=2,Os,Xm,Ck,Zm,lb=function(a){var e;return yk(a)&&Vs(e=a.then)?e:!1},cb=function(a,e){var t=e.value,r=e.state===ob,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===ub&&Ok(e),e.rejection=Du),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new sb("Promise-chain cycle")):(l=lb(u))?Gr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},db=function(a,e){a.notified||(a.notified=!0,Lu(function(){for(var t=a.reactions,r;r=t.get();)cb(r,a);a.notified=!1,e&&!a.rejection&&Dk(a)}))},pb=function(a,e,t){var r,i;$k?(r=ku.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Lt.dispatchEvent(r)):r={promise:e,reason:t},!Ak&&(i=Lt["on"+a])?i(r):a===nb&&Ek("Unhandled promise rejection",t)},Dk=function(a){Gr(tb,Lt,function(){var e=a.facade,t=a.value,r=eb(a),i;if(r&&(i=xk(function(){Bs?Cu.emit("unhandledRejection",t,e):pb(nb,e,t)}),a.rejection=Bs||eb(a)?ub:Du,i.error))throw i.value})},eb=function(a){return a.rejection!==Du&&!a.parent},Ok=function(a){Gr(tb,Lt,function(){var e=a.facade;Bs?Cu.emit("rejectionHandled",e):pb(Lk,e,a.value)})},Hr=function(a,e,t){return function(r){a(e,r,t)}},jr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Mk,db(a,!0))},$u=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new sb("Promise can't be resolved itself");var r=lb(e);r?Lu(function(){var i={done:!1};try{Gr(r,e,Hr($u,i,a),Hr(jr,i,a))}catch(s){jr(i,s,a)}}):(a.value=e,a.state=ob,db(a,!1))}catch(i){jr({done:!1},i,a)}}};if(ab&&(sr=function(e){Tk(this,Ds),Sk(e),Gr(Os,this);var t=wu(this);try{e(Hr($u,t),Hr(jr,t))}catch(r){jr(t,r)}},Ds=sr.prototype,Os=function(e){kk(this,{type:Ns,done:!1,notified:!1,parent:!1,reactions:new Pk,rejection:!1,state:Jm,value:void 0})},Os.prototype=zm(Ds,"then",function(e,t){var r=wu(this),i=Ru(Ik(this,sr));return r.parent=!0,i.ok=Vs(e)?e:!0,i.fail=Vs(t)&&t,i.domain=Bs?Cu.domain:void 0,r.state===Jm?r.reactions.add(i):Lu(function(){cb(i,r)}),i.promise}),Xm=function(){var a=new Os,e=wu(a);this.promise=a,this.resolve=Hr($u,e),this.reject=Hr(jr,e)},ib.f=Ru=function(a){return a===sr||a===Ck?new Xm(a):Rk(a)},!bk&&Vs(_s)&&Ur!==Object.prototype)){Zm=Ur.then,wk||zm(Ur,"then",function(e,t){var r=this;return new sr(function(i,s){Gr(Zm,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Ur.constructor}catch(a){}Km&&Km(Ur,Ds)}mk({global:!0,constructor:!0,wrap:!0,forced:ab},{Promise:sr});gk(sr,Ns,!1,!0);vk(Ns)});var vb=m((ZV,gb)=>{"use strict";var Vk=he(),mb=Vk("iterator"),bb=!1;try{fb=0,Ou={next:function(){return{done:!!fb++}},return:function(){bb=!0}},Ou[mb]=function(){return this},Array.from(Ou,function(){throw 2})}catch(a){}var fb,Ou;gb.exports=function(a,e){try{if(!e&&!bb)return!1}catch(i){return!1}var t=!1;try{var r={};r[mb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Vu=m((eB,Sb)=>{"use strict";var Bk=ar(),_k=vb(),Nk=Fr().CONSTRUCTOR;Sb.exports=Nk||!_k(function(a){Bk.all(a).then(void 0,function(){})})});var yb=m(()=>{"use strict";var Fk=te(),qk=Re(),Uk=tt(),Hk=qr(),jk=Cs(),Gk=ws(),Qk=Vu();Fk({target:"Promise",stat:!0,forced:Qk},{all:function(e){var t=this,r=Hk.f(t),i=r.resolve,s=r.reject,n=jk(function(){var o=Uk(t.resolve),u=[],l=0,c=1;Gk(e,function(d){var h=l++,p=!1;c++,qk(o,t,d).then(function(f){p||(p=!0,u[h]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Ib=m(()=>{"use strict";var Wk=te(),Yk=We(),zk=Fr().CONSTRUCTOR,_u=ar(),Kk=lt(),Jk=X(),Xk=Br(),Tb=_u&&_u.prototype;Wk({target:"Promise",proto:!0,forced:zk,real:!0},{catch:function(a){return this.then(void 0,a)}});!Yk&&Jk(_u)&&(Bu=Kk("Promise").prototype.catch,Tb.catch!==Bu&&Xk(Tb,"catch",Bu,{unsafe:!0}));var Bu});var Eb=m(()=>{"use strict";var Zk=te(),eR=Re(),tR=tt(),rR=qr(),iR=Cs(),aR=ws(),sR=Vu();Zk({target:"Promise",stat:!0,forced:sR},{race:function(e){var t=this,r=rR.f(t),i=r.reject,s=iR(function(){var n=tR(t.resolve);aR(e,function(o){eR(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var xb=m(()=>{"use strict";var nR=te(),oR=qr(),uR=Fr().CONSTRUCTOR;nR({target:"Promise",stat:!0,forced:uR},{reject:function(e){var t=oR.f(this),r=t.reject;return r(e),t.promise}})});var Nu=m((lB,Pb)=>{"use strict";var lR=rt(),cR=$e(),dR=qr();Pb.exports=function(a,e){if(lR(a),cR(e)&&e.constructor===a)return e;var t=dR.f(a),r=t.resolve;return r(e),t.promise}});var kb=m(()=>{"use strict";var pR=te(),hR=lt(),Ab=We(),fR=ar(),wb=Fr().CONSTRUCTOR,mR=Nu(),bR=hR("Promise"),gR=Ab&&!wb;pR({target:"Promise",stat:!0,forced:Ab||wb},{resolve:function(e){return mR(gR&&this===bR?fR:this,e)}})});var Rb=m(()=>{"use strict";hb();yb();Ib();Eb();xb();kb()});var Cb=m(()=>{"use strict";var vR=te(),SR=We(),Fs=ar(),yR=pe(),Lb=lt(),Mb=X(),TR=uu(),$b=Nu(),IR=Br(),qu=Fs&&Fs.prototype,ER=!!Fs&&yR(function(){qu.finally.call({then:function(){}},function(){})});vR({target:"Promise",proto:!0,real:!0,forced:ER},{finally:function(a){var e=TR(this,Lb("Promise")),t=Mb(a);return this.then(t?function(r){return $b(e,a()).then(function(){return r})}:a,t?function(r){return $b(e,a()).then(function(){throw r})}:a)}});!SR&&Mb(Fs)&&(Fu=Lb("Promise").prototype.finally,qu.finally!==Fu&&IR(qu,"finally",Fu,{unsafe:!0}));var Fu});var Ob=m((bB,Db)=>{"use strict";Hf();Rb();Cb();var xR=$t();Db.exports=xR("Promise","finally")});var Bb=m((gB,Vb)=>{"use strict";var PR=Ob();Vb.exports=PR});var qs=m((vB,_b)=>{"use strict";var AR=Bb();_b.exports=AR});var Jb=m(()=>{"use strict";var FR=te(),qR=Do().values;FR({target:"Object",stat:!0},{values:function(e){return qR(e)}})});var Zb=m((r_,Xb)=>{"use strict";Jb();var UR=kr();Xb.exports=UR.Object.values});var tg=m((i_,eg)=>{"use strict";var HR=Zb();eg.exports=HR});var Vi=m((a_,rg)=>{"use strict";var jR=tg();rg.exports=jR});var mg=m(()=>{"use strict";var n$=te(),o$=Rr(),u$=Or(),l$=Ti(),c$=Ii();n$({target:"Array",proto:!0},{at:function(e){var t=o$(this),r=u$(t),i=l$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});c$("at")});var gg=m((M_,bg)=>{"use strict";mg();var d$=$t();bg.exports=d$("Array","at")});var Sg=m((C_,vg)=>{"use strict";var p$=gg();vg.exports=p$});var Yr=m((D_,yg)=>{"use strict";var h$=Sg();yg.exports=h$});var cl=m((lF,Kg)=>{"use strict";var Y$=Jt();Kg.exports=Array.isArray||function(e){return Y$(e)==="Array"}});var Xg=m((cF,Jg)=>{"use strict";var z$=TypeError,K$=9007199254740991;Jg.exports=function(a){if(a>K$)throw z$("Maximum allowed index exceeded");return a}});var tv=m((dF,ev)=>{"use strict";var J$=cl(),X$=Or(),Z$=Xg(),eL=Lr(),Zg=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?eL(n,o):!1,d,h;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&J$(d)?(h=X$(d),u=Zg(a,e,d,h,u,s-1)-1):(Z$(u+1),a[u]=d),u++),l++;return u};ev.exports=Zg});var sv=m((pF,av)=>{"use strict";var rv=cl(),tL=ou(),rL=$e(),iL=he(),aL=iL("species"),iv=Array;av.exports=function(a){var e;return rv(a)&&(e=a.constructor,tL(e)&&(e===iv||rv(e.prototype))?e=void 0:rL(e)&&(e=e[aL],e===null&&(e=void 0))),e===void 0?iv:e}});var ov=m((hF,nv)=>{"use strict";var sL=sv();nv.exports=function(a,e){return new(sL(a))(e===0?0:e)}});var uv=m(()=>{"use strict";var nL=te(),oL=tv(),uL=tt(),lL=Rr(),cL=Or(),dL=ov();nL({target:"Array",proto:!0},{flatMap:function(e){var t=lL(this),r=cL(t),i;return uL(e),i=dL(t,0),i.length=oL(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var lv=m(()=>{"use strict";var pL=Ii();pL("flatMap")});var dv=m((vF,cv)=>{"use strict";uv();lv();var hL=$t();cv.exports=hL("Array","flatMap")});var hv=m((SF,pv)=>{"use strict";var fL=dv();pv.exports=fL});var dl=m((yF,fv)=>{"use strict";var mL=hv();fv.exports=mL});var Ki=m((LF,Dv)=>{"use strict";var EL=xi(),xL=String;Dv.exports=function(a){if(EL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return xL(a)}});var hl=m((MF,Ov)=>{"use strict";Ov.exports=`
7
+ \v\f\r \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF`});var _v=m((CF,Bv)=>{"use strict";var PL=se(),AL=Rt(),wL=Ki(),ml=hl(),Vv=PL("".replace),kL=RegExp("^["+ml+"]+"),RL=RegExp("(^|[^"+ml+"])["+ml+"]+$"),fl=function(a){return function(e){var t=wL(AL(e));return a&1&&(t=Vv(t,kL,"")),a&2&&(t=Vv(t,RL,"$1")),t}};Bv.exports={start:fl(1),end:fl(2),trim:fl(3)}});var Uv=m((DF,qv)=>{"use strict";var $L=qo().PROPER,LL=pe(),Nv=hl(),Fv="\u200B\x85\u180E";qv.exports=function(a){return LL(function(){return!!Nv[a]()||Fv[a]()!==Fv||$L&&Nv[a].name!==a})}});var bl=m((OF,Hv)=>{"use strict";var ML=_v().start,CL=Uv();Hv.exports=CL("trimStart")?function(){return ML(this)}:"".trimStart});var Gv=m(()=>{"use strict";var DL=te(),jv=bl();DL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==jv},{trimLeft:jv})});var Wv=m(()=>{"use strict";Gv();var OL=te(),Qv=bl();OL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Qv},{trimStart:Qv})});var zv=m((FF,Yv)=>{"use strict";Wv();var VL=$t();Yv.exports=VL("String","trimLeft")});var Jv=m((qF,Kv)=>{"use strict";var BL=zv();Kv.exports=BL});var Zv=m((UF,Xv)=>{"use strict";var _L=Jv();Xv.exports=_L});var mS=m(()=>{"use strict"});var bS=m(()=>{"use strict"});var vS=m((m1,gS)=>{"use strict";var oM=$e(),uM=Jt(),lM=he(),cM=lM("match");gS.exports=function(a){var e;return oM(a)&&((e=a[cM])!==void 0?!!e:uM(a)==="RegExp")}});var yS=m((b1,SS)=>{"use strict";var dM=rt();SS.exports=function(){var a=dM(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var ES=m((g1,IS)=>{"use strict";var pM=Re(),hM=Ye(),fM=mi(),mM=yS(),TS=RegExp.prototype;IS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in TS)&&!hM(a,"flags")&&fM(TS,a)?pM(mM,a):e}});var PS=m((v1,xS)=>{"use strict";var Pl=se(),bM=Rr(),gM=Math.floor,El=Pl("".charAt),vM=Pl("".replace),xl=Pl("".slice),SM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,yM=/\$([$&'`]|\d{1,2})/g;xS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=yM;return i!==void 0&&(i=bM(i),u=SM),vM(s,u,function(l,c){var d;switch(El(c,0)){case"$":return"$";case"&":return a;case"`":return xl(e,0,t);case"'":return xl(e,n);case"<":d=i[xl(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=gM(h/10);return p===0?l:p<=o?r[p-1]===void 0?El(c,1):r[p-1]+El(c,1):l}d=r[h-1]}return d===void 0?"":d})}});var kS=m(()=>{"use strict";var TM=te(),IM=Re(),wl=se(),AS=Rt(),EM=X(),xM=wr(),PM=vS(),ei=Ki(),AM=gi(),wM=ES(),kM=PS(),RM=he(),$M=We(),LM=RM("replace"),MM=TypeError,Al=wl("".indexOf),CM=wl("".replace),wS=wl("".slice),DM=Math.max;TM({target:"String",proto:!0},{replaceAll:function(e,t){var r=AS(this),i,s,n,o,u,l,c,d,h,p,f=0,b="";if(!xM(e)){if(i=PM(e),i&&(s=ei(AS(wM(e))),!~Al(s,"g")))throw new MM("`.replaceAll` does not allow non-global regexes");if(n=AM(e,LM),n)return IM(n,e,r,t);if($M&&i)return CM(ei(r),e,t)}for(o=ei(r),u=ei(e),l=EM(t),l||(t=ei(t)),c=u.length,d=DM(1,c),h=Al(o,u);h!==-1;)p=l?ei(t(u,h,o)):kM(u,o,h,[],void 0,t),b+=wS(o,f,h)+p,f=h+c,h=h+d>o.length?-1:Al(o,u,h+d);return f<o.length&&(b+=wS(o,f)),b}})});var $S=m((T1,RS)=>{"use strict";mS();bS();kS();var OM=$t();RS.exports=OM("String","replaceAll")});var MS=m((I1,LS)=>{"use strict";var VM=$S();LS.exports=VM});var DS=m((E1,CS)=>{"use strict";var BM=MS();CS.exports=BM});var VS=m((x1,OS)=>{"use strict";var _M=Ti(),NM=Ki(),FM=Rt(),qM=RangeError;OS.exports=function(e){var t=NM(FM(this)),r="",i=_M(e);if(i<0||i===1/0)throw new qM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var qS=m((P1,FS)=>{"use strict";var NS=se(),UM=Ao(),BS=Ki(),HM=VS(),jM=Rt(),GM=NS(HM),QM=NS("".slice),WM=Math.ceil,_S=function(a){return function(e,t,r){var i=BS(jM(e)),s=UM(t),n=i.length,o=r===void 0?" ":BS(r),u,l;return s<=n||o===""?i:(u=s-n,l=GM(o,WM(u/o.length)),l.length>u&&(l=QM(l,0,u)),a?i+l:l+i)}};FS.exports={start:_S(!1),end:_S(!0)}});var HS=m((A1,US)=>{"use strict";var YM=Zt();US.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(YM)});var jS=m(()=>{"use strict";var zM=te(),KM=qS().start,JM=HS();zM({target:"String",proto:!0,forced:JM},{padStart:function(e){return KM(this,e,arguments.length>1?arguments[1]:void 0)}})});var QS=m((R1,GS)=>{"use strict";jS();var XM=$t();GS.exports=XM("String","padStart")});var YS=m(($1,WS)=>{"use strict";var ZM=QS();WS.exports=ZM});var KS=m((L1,zS)=>{"use strict";var eC=YS();zS.exports=eC});var Qc="2.0.123-dev.8ba72ee5.0";var Se=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Se||{}),kt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(kt||{});var os=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(os||{}),Yn=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(Yn||{});var zn=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(zn||{});var AT=F(it(),1);import{assertNever as jp,assertNonNullable as hx,isNonNullable as ps,ValueSubject as ko,Subject as fx,Subscription as mx,merge as bx,observableFrom as gx,fromEvent as Fp,map as qp,tap as Up,filterChanged as vx,isNullable as Ro,ErrorCategory as Hp}from"@vkontakte/videoplayer-shared/es2015";var Np=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var hs=class{constructor(e){this.connection$=new ko(void 0);this.castState$=new ko("NOT_AVAILABLE");this.errorEvent$=new fx;this.realCastState$=new ko("NOT_AVAILABLE");this.subscription=new mx;this.isDestroyed=!1;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=ps((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||Np("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Hp.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,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){ps(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Ro(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Ro(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Fp(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.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 jp(i.sessionState)}})).add(bx(Fp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Up(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),qp(i=>i.castState)),gx([r.getCastState()])).pipe(vx(),qp(Sx),Up(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=ps(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();hx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Ro(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?ps(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;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:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Hp.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Sx=a=>{switch(a){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 jp(a)}};var ic=F(it(),1),nT=F(Vr(),1),oT=F(ru(),1);var Yb=F(qs(),1);import{assertNever as Nb}from"@vkontakte/videoplayer-shared/es2015";var fe=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Nb(t)}return a},Us=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Nb(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as wR,Subject as Hs,merge as Fb}from"@vkontakte/videoplayer-shared/es2015";var C=class{constructor(e){this.transitionStarted$=new Hs;this.transitionEnded$=new Hs;this.transitionUpdated$=new Hs;this.forceChanged$=new Hs;this.stateChangeStarted$=Fb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Fb(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||wR(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 kR}from"@vkontakte/videoplayer-shared/es2015";var qb=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return kR(a)}};import{assertNever as Qr,assertNonNullable as nr,debounce as Ub,ErrorCategory as Hb,fromEvent as or,isNonNullable as jb,map as Gb,merge as Qb,observableFrom as RR,Subject as $R,Subscription as Uu,timeout as LR,getHighestQuality as MR}from"@vkontakte/videoplayer-shared/es2015";var CR=5,DR=5,OR=500,Wb=7e3,Oi=class{constructor(e){this.subscription=new Uu;this.loadMediaTimeoutSubscription=new Uu;this.videoState=new C("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=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((i==null?void 0:i.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:Qr(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:Qr(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:Qr(e)}break}default:Qr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(qb(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 Uu;this.subscription.add(e),this.subscription.add(Qb(this.videoState.stateChangeStarted$.pipe(Gb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Gb(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new $R;e.add(i.pipe(Ub(OR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(or(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)>CR)&&i.next(o),s=o})),e.add(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.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<DR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Qr(n)}}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(or(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Qb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,RR(["init"])).pipe(Ub(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"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(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"),x(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"),x(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"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i: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,i,s;switch(e){case"MPEG":{let c=t[e];nr(c);let d=MR(Object.keys(c));nr(d);let h=c[d];nr(h),r=h,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];nr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];nr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];nr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];nr(c),r=fe(c.url),i="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:Hb.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Qr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return jb(o)&&(n.metadata.title=o),jb(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((i,s)=>{this.loadMediaTimeoutSubscription.add(LR(Wb).subscribe(()=>s(`timeout(${Wb})`)))});(0,Yb.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()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Hb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ul=F(it(),1);import{clearVideoElement as Kb}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as VR}from"@vkontakte/videoplayer-shared/es2015";var zb=a=>{try{a.pause(),a.playbackRate=0,VR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as BR,Subscription as _R}from"@vkontakte/videoplayer-shared/es2015";var Hu=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)}},ju=window.WeakMap?new WeakMap:new Hu,Gu=window.WeakMap?new WeakMap:new Map,NR=(a,e=20)=>{let t=0;return BR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},ye=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?Kb(t):(t=document.createElement("video"),a.appendChild(t)),ju.set(t,r);let i=new _R;return i.add(NR(t,e)),Gu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Te=a=>{let e=Gu.get(a);e==null||e.unsubscribe(),Gu.delete(a);let t=ju.get(a);ju.delete(a),t?Kb(a):zb(a)};var Wu=F(Vi(),1);import{assertNonNullable as Bi,isNonNullable as st,isNullable as WR,fromEvent as Wr,merge as ig,observableFrom as ag,filterChanged as sg,map as _i,Subject as ng,Subscription as YR,ValueSubject as zR,ErrorCategory as KR}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Qu,isNullable as GR,Subscription as QR}from"@vkontakte/videoplayer-shared/es2015";var js=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=GR(i),l=new QR;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},at=(a,e,t)=>js(e,()=>a.loop,r=>{Qu(r)&&(a.loop=r)},{onError:t}),Ie=(a,e,t,r)=>js(e,()=>({muted:a.muted,volume:a.volume}),i=>{Qu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),_e=(a,e,t,r)=>js(e,()=>a.playbackRate,i=>{Qu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Mt=js;var JR=a=>["__",a.language,a.label].join("|"),XR=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},Yu=class a{constructor(){this.available$=new ng;this.current$=new zR(void 0);this.error$=new ng;this.subscription=new YR;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:KR.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(Mt(t.internalTextTracks,()=>(0,Wu.default)(this.internalTracks),s=>{st(s)&&this.setInternal(s)},{equal:(s,n)=>st(s)&&st(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(_i(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Mt(t.externalTextTracks,()=>(0,Wu.default)(this.externalTracks),s=>{st(s)&&this.setExternal(s)},{equal:(s,n)=>st(s)&&st(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(_i(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Mt(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:i})),this.subscription.add(Mt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Bi(this.video);let{textTracks:e}=this.video;this.subscription.add(Wr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(ig(Wr(e,"addtrack"),Wr(e,"removetrack"),ag(["init"])).pipe(_i(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),sg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(ig(Wr(e,"change"),ag(["init"])).pipe(_i(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),_i(r=>r&&this.htmlTextTrackToITextTrack(r).id),sg()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(Wr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Wr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;st(t.align)&&(i.align=t.align),st(t.position)&&(i.position=t.position),st(t.size)&&(i.size=t.size),st(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Bi(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:JR(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.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:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){Bi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(WR(e)||!XR(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){Bi(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){Bi(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)}},Ne=Yu;var pt=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 og=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},zu=a=>{let e=og(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},ug=a=>{let e=og(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Fe,map as Ct,merge as cg,filterChanged as e$,isNonNullable as dg,Subject as t$,filter as pg,mapTo as hg,combine as r$,once as i$,ErrorCategory as a$,ValueSubject as fg,clientChecker as s$}from"@vkontakte/videoplayer-shared/es2015";var ZR=3,lg=(a,e,t=ZR)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Ee=a=>{let e=y=>Fe(a,y).pipe(hg(void 0)),r=cg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Fe(a,y))).pipe(Ct(y=>y.type==="ended"?a.readyState<2:a.readyState<3),e$()),i=cg(Fe(a,"progress"),Fe(a,"timeupdate")).pipe(Ct(()=>lg(a.buffered,a.currentTime))),s=s$.isSafari?r$({play:e("play").pipe(i$()),playing:e("playing")}).pipe(hg(void 0)):e("playing"),n=Fe(a,"volumechange").pipe(Ct(()=>({muted:a.muted,volume:a.volume}))),o=Fe(a,"ratechange").pipe(Ct(()=>a.playbackRate)),u=Fe(a,"error").pipe(pg(()=>!!(a.error||a.played.length)),Ct(()=>{var I;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:a$.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=Fe(a,"timeupdate").pipe(Ct(()=>a.currentTime)),c=new t$,d=.3,h;l.subscribe(y=>{a.loop&&dg(h)&&dg(y)&&h>=a.duration-d&&y<=d&&c.next(h),h=y});let p=e("pause").pipe(pg(()=>!a.error&&h!==a.duration)),f=Fe(a,"enterpictureinpicture"),b=Fe(a,"leavepictureinpicture"),g=new fg(ug(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new fg(zu(a));return Fe(a,"fullscreenchange").pipe(Ct(()=>zu(a))).subscribe(S),{playing$:s,pause$:p,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Fe(a,"durationchange").pipe(Ct(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b}};import{VideoQuality as Dt}from"@vkontakte/videoplayer-shared/es2015";var Ot=a=>{switch(a){case"mobile":return Dt.Q_144P;case"lowest":return Dt.Q_240P;case"low":return Dt.Q_360P;case"sd":case"medium":return Dt.Q_480P;case"hd":case"high":return Dt.Q_720P;case"fullhd":case"full":return Dt.Q_1080P;case"quadhd":case"quad":return Dt.Q_1440P;case"ultrahd":case"ultra":return Dt.Q_2160P}};var Vt=F(Yr(),1),wg=F(it(),1),Gs=F(Vr(),1);import{isNonNullable as ne,isNullable as Ju,now as kg,isHigher as Xu,isHigherOrEqual as Zu,isInvariantQuality as xg,isLower as Pg,isLowerOrEqual as el,videoSizeToQuality as f$,assertNotEmptyArray as Rg,assertNonNullable as m$}from"@vkontakte/videoplayer-shared/es2015";var Ku=!1,ht={},Tg=a=>{Ku=a},Ig=()=>{ht={}},Eg=a=>{a(ht)},Ni=(a,e)=>{var t;Ku&&(ht.meta=(t=ht.meta)!=null?t:{},ht.meta[a]=e)},be=class{constructor(e){this.name=e}next(e){var r,i;if(!Ku)return;ht.series=(r=ht.series)!=null?r:{};let t=(i=ht.series[this.name])!=null?i:[];t.push([Date.now(),e]),ht.series[this.name]=t}};var b$=new be("best_bitrate"),$g=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var tl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Fi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=kg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Lg='Assertion "ABR Tracks is empty array" failed',Qs=(a,e,t,r)=>{var u;let i=[...e].sort(tl(1)),s=[...t].sort(tl(1)),n=s.filter(l=>ne(l.bitrate)&&ne(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Vt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Vt.default)(s,-1);return o&&(0,wg.default)(n,o)?o:n.length?(0,Vt.default)(n,-1):(0,Vt.default)(s,0)},Ag=a=>"quality"in a,Mg=(a,e,t,r)=>{var n;let i=ne((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&ne(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&kg()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Ag(o)?"video":"audio",l=Ag(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return r==null||r.recordSwitch(t),t},S$=(a,e)=>Math.log(e)/Math.log(a),y$=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&window.devicePixelRatio){let n=window.devicePixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(n-1)+1;else{let o=a.pixelRatioLogBase,[u=0,l=0,c=0]=a.pixelRatioLogCoefficients,d=S$(o,u*n+l)+c;Number.isFinite(d)&&(r*=d)}}let{highQualityLimit:i,trafficSavingLimit:s}=a;return t&&Gs({limits:t,highQualityLimit:i,trafficSavingLimit:s})==="high_quality"&&(r*=2),a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0},Vt=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:m})=>{var O,_,$,j,L,Y;Mg(a,Dg);let b=y$({container:e,tuning:r,limits:i}),g=r.considerPlaybackRate&&ne(o)?o:1,S=a.filter(y=>!wg(y.quality)).sort((y,k)=>tl(y.quality,k.quality)?-1:1),v=(O=(0,Ot.default)(S,-1))==null?void 0:O.quality,T=(_=(0,Ot.default)(S,0))==null?void 0:_.quality,I=el(i)||ne(i.min)&&ne(i.max)&&kg(i.max,i.min)||ne(i.min)&&T&&tl(i.min,T)||ne(i.max)&&v&&kg(i.max,v),E=g*Cg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),w={},B=S.filter(y=>{let k=!0;if(b)if(y.size)k=y.size.width<=b.width&&y.size.height<=b.height;else{let ie=b&&b$(b);k=ie?il(y.quality,ie):!0}if(!k)return w[y.quality]="FitsContainer",!1;let W=p||t;if(!(ne(W)&&isFinite(W)&&ne(y.bitrate)?W-s>=y.bitrate*E:!0))return w[y.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&ne(r.minBufferToSwitchUp)&&u&&!wg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&tl(y.quality,u.quality))return w[y.quality]="Buffer",!1;if(!!d&&rl(y.quality,d))return w[y.quality]="DroppedFramesLimit",!1;if(!!h&&rl(y.quality,h))return w[y.quality]="StallsLimit",!1;let Qt=I||(el(i.max)||il(y.quality,i.max))&&(el(i.min)||rl(y.quality,i.min)),q=ne(c)&&!c?il(y.quality,r.backgroundVideoQualityLimit):!0;return!Qt||!q?(w[y.quality]="FitsQualityLimits",!1):!0})[0];B&&B.bitrate&&v$.next(B.bitrate);let H=($=B!=null?B:(0,Ot.default)(S,-1))!=null?$:a[0];return H.quality!==((j=l==null?void 0:l.last)==null?void 0:j.quality)&&m({message:`
9
+ `}),o}return r==null||r.recordSwitch(t),t},g$=(a,e)=>Math.log(e)/Math.log(a),Bt=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:f})=>{var q,R,j,L,W,w;Rg(a,Lg);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let T=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(T-1)+1;else{let _=r.pixelRatioLogBase,[V=0,ie=0,Oe=0]=r.pixelRatioLogCoefficients,yt=g$(_,V*T+ie)+Oe;Number.isFinite(yt)&&(b*=yt)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,S=r.considerPlaybackRate&&ne(o)?o:1,v=a.filter(T=>!xg(T.quality)).sort((T,_)=>Xu(T.quality,_.quality)?-1:1),y=(q=(0,Vt.default)(v,-1))==null?void 0:q.quality,I=(R=(0,Vt.default)(v,0))==null?void 0:R.quality,E=Ju(i)||ne(i.min)&&ne(i.max)&&Pg(i.max,i.min)||ne(i.min)&&I&&Xu(i.min,I)||ne(i.max)&&y&&Pg(i.max,y),$=S*$g(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),D={},N=v.filter(T=>{let _=!0;if(g)if(T.size)_=T.size.width<=g.width&&T.size.height<=g.height;else{let ce=g&&f$(g);_=ce?el(T.quality,ce):!0}if(!_)return D[T.quality]="FitsContainer",!1;let V=p||t;if(!(ne(V)&&isFinite(V)&&ne(T.bitrate)?V-s>=T.bitrate*$:!0))return D[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&ne(r.minBufferToSwitchUp)&&u&&!xg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&Xu(T.quality,u.quality))return D[T.quality]="Buffer",!1;if(!!d&&Zu(T.quality,d))return D[T.quality]="DroppedFramesLimit",!1;if(!!h&&Zu(T.quality,h))return D[T.quality]="StallsLimit",!1;let H=E||(Ju(i.max)||el(T.quality,i.max))&&(Ju(i.min)||Zu(T.quality,i.min)),le=ne(c)&&!c?el(T.quality,r.backgroundVideoQualityLimit):!0;return!H||!le?(D[T.quality]="FitsQualityLimits",!1):!0})[0];N&&N.bitrate&&b$.next(N.bitrate);let O=(j=N!=null?N:(0,Vt.default)(v,-1))!=null?j:a[0];return O.quality!==((L=l==null?void 0:l.last)==null?void 0:L.quality)&&f({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${a.map(y=>`{ id: ${y.id}, quality: ${y.quality}, bitrate: ${y.bitrate} }`).join(`
12
+ ${a.map(T=>`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate} }`).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,Ws.default)(r!=null?r:{}).map(([y,k])=>`${y}: ${k}`).join(`
16
+ ${(0,Gs.default)(r!=null?r:{}).map(([T,_])=>`${T}: ${_}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
- containerSizeLimit: ${(L=b==null?void 0:b.width)!=null?L:0} x ${(Y=b==null?void 0:b.width)!=null?Y:0},
20
+ containerSizeLimit: ${(W=g==null?void 0:g.width)!=null?W:0} x ${(w=g==null?void 0:g.width)!=null?w:0},
21
21
  estimatedThroughput: ${t},
22
22
  stallsPredictedThroughput: ${p},
23
23
  reserve: ${s},
24
24
  playbackRate: ${o},
25
- playbackRateFactor: ${g},
25
+ playbackRateFactor: ${S},
26
26
  forwardBufferHealth: ${n},
27
- bitrateFactor: ${E},
27
+ bitrateFactor: ${$},
28
28
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
29
29
  droppedVideoMaxQualityLimit: ${d},
30
30
  stallsVideoMaxQualityLimit: ${h},
31
- limitsAreInvalid: ${I},
31
+ limitsAreInvalid: ${E},
32
32
  maxQualityLimit: ${i==null?void 0:i.max},
33
33
  minQualityLimit: ${i==null?void 0:i.min},
34
34
 
35
35
  [limited video tracks]
36
- ${(0,Ws.default)(w).map(([y,k])=>`${y}: ${k}`).join(`
36
+ ${(0,Gs.default)(D).map(([T,_])=>`${T}: ${_}`).join(`
37
37
  `)||"All tracks are available"}
38
38
 
39
- [best video track] ${B==null?void 0:B.quality}
40
- [selected video track] ${H==null?void 0:H.quality}
41
- `}),Og(r,m,H,l)},Vg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var S;Mg(t,Dg);let c=i.considerPlaybackRate&&ne(s)?s:1,d=[...t].sort(al(-1)),h=a.bitrate;g$(h);let p=c*Cg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,b=Ys(a,e,t,i.minVideoAudioRatio),g=l||r;return ne(g)&&isFinite(g)&&(m=d.find(v=>ne(v.bitrate)&&ne(b==null?void 0:b.bitrate)?g-h>=v.bitrate*p&&v.bitrate>=b.bitrate:!1)),m||(m=b),(m==null?void 0:m.bitrate)!==((S=o==null?void 0:o.last)==null?void 0:S.bitrate)&&u({message:`
39
+ [best video track] ${N==null?void 0:N.quality}
40
+ [selected video track] ${O==null?void 0:O.quality}
41
+ `}),Mg(r,f,O,l)},Cg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var S;Rg(t,Lg);let c=i.considerPlaybackRate&&ne(s)?s:1,d=[...t].sort(tl(-1)),h=a.bitrate;m$(h);let p=c*$g(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,b=Qs(a,e,t,i.minVideoAudioRatio),g=l||r;return ne(g)&&isFinite(g)&&(f=d.find(v=>ne(v.bitrate)&&ne(b==null?void 0:b.bitrate)?g-h>=v.bitrate*p&&v.bitrate>=b.bitrate:!1)),f||(f=b),(f==null?void 0:f.bitrate)!==((S=o==null?void 0:o.last)==null?void 0:S.bitrate)&&u({message:`
42
42
  [AUDIO TRACKS ABR]
43
43
  [available audio tracks]
44
44
  ${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
45
45
  `)}
46
46
 
47
47
  [tuning]
48
- ${(0,Ws.default)(i!=null?i:{}).map(([v,T])=>`${v}: ${T}`).join(`
48
+ ${(0,Gs.default)(i!=null?i:{}).map(([v,y])=>`${v}: ${y}`).join(`
49
49
  `)}
50
50
 
51
51
  [limit params]
@@ -58,15 +58,15 @@ var FT=Object.create;var Yn=Object.defineProperty,qT=Object.defineProperties,UT=
58
58
  bitrateFactor: ${p},
59
59
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
60
60
 
61
- [selected audio track] ${m==null?void 0:m.id}
62
- `}),m&&Og(i,u,m,o)};var oe=a=>new URL(a).hostname;import{assertNever as Gg,assertNonNullable as Wg,combine as q$,debounce as U$,ErrorCategory as Yg,filter as zg,filterChanged as H$,isNonNullable as ll,map as Zs,merge as Kg,observableFrom as j$,once as Q$,Subscription as G$,ValueSubject as cl,videoQualityToHeight as W$,videoSizeToQuality as Y$}from"@vkontakte/videoplayer-shared/es2015";var _g=V(it(),1);var Bg=a=>{if(a instanceof DOMException&&(0,_g.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},Ee=(a,e)=>R(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!Bg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return Bg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as Ks,isNullable as E$,assertNonNullable as ji}from"@vkontakte/videoplayer-shared/es2015";var Fg=V(Bi(),1);import{isNonNullable as Ng,assertNonNullable as zs,now as T$}from"@vkontakte/videoplayer-shared/es2015";function ue(){return T$()}function sl(a){return ue()-a}function nl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(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 qg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function Yr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;zs(c);let $=sl(c),j;if($<b){j=b-$,setTimeout(g,j);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,w()},S=$=>(s=$,_),v=$=>(d=$,_),T=()=>(p="json",_),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},E=$=>(h=$,_),w=()=>{c=ue(),n=new i,n.open("get",a);let $=0,j,L=0,Y=()=>(zs(c),Math.max(c,Math.max(j||0,L||0)));if(s&&n.addEventListener("progress",y=>{let k=ue();s.updateChunk&&y.loaded>$&&(s.updateChunk(Y(),y.loaded-$),$=y.loaded,j=k)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;zs(n);let y=n.status;if(y>=200&&y<300){if(n.response.byteLength&&s){let k=n.response.byteLength-$;k&&s.updateChunk&&s.updateChunk(Y(),k)}n.responseType==="json"&&!(0,Fg.default)(n.response).length?I():(d&&d(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),h){let y=()=>{zs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(L=ue(),n.removeEventListener("readystatechange",y))};n.addEventListener("readystatechange",y)}return n.responseType=p,n.send(),_},_={withBitrateReporting:S,withParallel:E,withJSONResponse:T,withRetryCount:$=>(l=$,_),withRetryInterval:($,j)=>(Ng($)&&(b=$),Ng(j)&&(m=j),_),withTimeout:$=>(o=$,_),withFinally:v,send:w,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return _}var Ui=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,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=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;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*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(i)}/${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 Ug=V(Bi(),1);var Hi=class{constructor(e,t,r,i,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=i,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=ue(),i=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=ue()-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=Yr(t,s,()=>i("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=ue()}_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=ue();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Ug.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,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=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as x$}from"@vkontakte/videoplayer-shared/es2015";var Js=1e4,ol=3;var P$=6e4,A$=10,w$=1,k$=500,Qi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new x$,this.chunkRateEstimator=new Ui(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=nl(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=nl(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 i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.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,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,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)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ks(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{qg(i,"progress",()=>{i.buffered.length?(i.currentTime=i.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 Hi(ol,Js,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},h=(I,E,w)=>{u&&u.abort(),u=Yr(this.urlResolver.resolve(I,!1),E,w,()=>this._retryCallback()).withTimeout(Js).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ol).withFinally(()=>{u=null}).send()},p=(I,E,w)=>{ji(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,w,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let E=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let w=ue()-1e4,U=0;for(let H=0;H<this.bufferStates.length;H++){let O=this.bufferStates[H];I=Math.min(I,O.buf),O.ts<w&&U++}this.bufferStates.splice(0,U),t(`update playback rate; minBuffer=${I} drop=${U} jitter=${this.sourceJitter}`);let B=I-w$;this.sourceJitter>=0?B-=this.sourceJitter/2:this.sourceJitter-=1,B>3?m(1.15):B>1?m(1.1):B>.3?m(1.05):m(1)}},S=I=>{let E,w=()=>E&&E.start?E.start.length:0,U=y=>E.start[y]/1e3,B=y=>E.dur[y]/1e3,H=y=>E.fragIndex+y,O=(y,k)=>({chunkIdx:H(y),startTS:U(y),dur:B(y),discontinuity:k}),_=()=>{let y=0;if(E&&E.dur){let k=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,N=k;this.sourceJitter>1&&(N+=this.sourceJitter-1);let he=E.dur.length-1;for(;he>=0&&(N-=E.dur[he],!(N<=0));--he);y=Math.min(he,E.dur.length-1-W),y=Math.max(y,0)}return O(y,!0)},$=y=>{let k=w();if(!(k<=0)){if(Ks(y)){for(let W=0;W<k;W++)if(U(W)>y)return O(W)}return _()}},j=y=>{let k=w(),W=y?y.chunkIdx+1:0,N=W-E.fragIndex;if(!(k<=0)){if(!y||N<0||N-k>A$)return t(`Resync: offset=${N} bChunks=${k} chunk=`+JSON.stringify(y)),_();if(!(N>=k))return O(W-E.fragIndex,!1)}},L=(y,k,W)=>{l&&l.abort(),l=Yr(this.urlResolver.resolve(y,!0,this.lowLatency),k,W,()=>this._retryCallback()).withTimeout(Js).withRetryCount(ol).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(y,k)=>{L(I,W=>{if(!d())return;E=W;let N=!!E.lowLatency;N!==this.lowLatency&&b(N);let he=0;for(let Je=0;Je<E.dur.length;++Je)he+=E.dur[Je];he>0&&(ji(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(he/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,y($(k))},()=>this._handleNetworkError())},nextChunk:j}},v=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),ji(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:w}=this.params,U=S(e.jidxUrl),B,H,O,_,$=0,j,L,Y,y=()=>{j&&(clearTimeout(j),j=void 0);let q=Math.max(k$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=$+q,we=ue(),Oe=Math.min(1e4,ie-we);$=we;let yt=()=>{l||d()&&U.seek(()=>{d()&&($=ue(),k(),y())})};Oe>0?j=window.setTimeout(()=>{this.paused?y():yt()},Oe):yt()},k=()=>{let q;for(;q=U.nextChunk(_);)_=q,si(q);let ie=U.nextChunk(O);if(ie){if(O&&ie.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?y():(v(),this._initPlayerWith(e));return}Je(ie)}else y()},W=(q,ie)=>{if(!d()||!this.sourceBuffer)return;let we,Oe,yt,vr=Tt=>{window.setTimeout(()=>{d()&&W(q,ie)},Tt)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),vr(100);else{let Tt=ue(),Gt=E.currentTime;!this.paused&&E.buffered.length>1&&L===Gt&&Tt-Y>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),L!==Gt&&(L=Gt,Y=Tt);let Sr=this._getBufferSizeSec();if(Sr>30)w(`Buffered ${Sr} seconds; delaying appendBuffer`),vr(2e3);else try{this.sourceBuffer.appendBuffer(q),this.videoPlayStarted?(this.bufferStates.push({ts:Tt,buf:Sr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(ni){if(ni.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),yt=this.sourceBuffer.buffered.length,yt!==0&&(we=this.sourceBuffer.buffered.start(0),Oe=Gt,Oe-we>4&&this.sourceBuffer.remove(we,Oe-3)),vr(1e3);else throw ni}}},N=()=>{H&&B&&(w([`Appending chunk, sz=${H.byteLength}:`,JSON.stringify(O)]),W(H,function(){H=null,k()}))},he=q=>e.fragUrlTemplate.replace("%%id%%",q.chunkIdx),Je=q=>{d()&&p(he(q),(ie,we)=>{if(d()){if(we/=1e3,H=ie,O=q,n=q.startTS,we){let Oe=Math.min(10,q.dur/we);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Oe:Oe}N()}},()=>this._handleNetworkError())},si=q=>{d()&&(ji(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(he(q),!1)))},Qt=q=>{d()&&(e.cachedHeader=q,W(q,()=>{B=!0,N()}))};s=!0,U.seek(q=>{if(d()){if($=ue(),!q){y();return}_=q,!E$(I)||q.startTS>I?Je(q):(O=q,k())}},I),e.cachedHeader?Qt(e.cachedHeader):h(e.headerUrl,Qt,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Ks(i)&&(i+=.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,ji(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ks(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=ue();if(this.chunkRateEstimator.addInterval(h,m,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&sl(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ue();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=Yr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Js).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;Ee(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.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))},P$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Qg=V(Or(),1);import{debounce as R$,filter as Hg,fromEvent as $$,interval as L$,isHigher as M$,isInvariantQuality as C$,isLower as D$,merge as O$,Subject as jg,Subscription as V$}from"@vkontakte/videoplayer-shared/es2015";var ul=class{constructor(){this.onDroopedVideoFramesLimit$=new jg;this.subscription=new V$;this.playing=!1;this.tracks=[];this.forceChecker$=new jg;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&&!C$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&M$(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add($$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=L$(this.droppedFramesChecker.checkTime).pipe(Hg(()=>this.playing),Hg(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(R$(this.droppedFramesChecker.checkTime)),r=O$(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,i;let t=(i=(r=(0,Qg.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>D$(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[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}},Xs=ul;import{map as B$,Observable as _$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as N$}from"@vkontakte/videoplayer-shared/es2015";var Gi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var F$=(a,e)=>new _$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Gi()))},P(P({},r),e));i.observe(a);let s=N$(document,"visibilitychange").pipe(B$(n=>!document.hidden||Gi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Fe=F$;var z$=["paused","playing","ready"],K$=["paused","playing","ready"],Wi=class{constructor(e){this.subscription=new G$;this.videoState=new C("stopped");this.representations$=new cl([]);this.textTracksManager=new _e;this.droppedFramesManager=new Xs;this.maxSeekBackTime$=new cl(1/0);this.zeroTime$=new cl(void 0);this.liveOffset=new pt;this._dashCb=e=>{var t,r,i,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:Yg.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=Dt(u.name))!=null?r:Y$(u.video),d=u.bitrate/1e3,h=P({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.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),ll(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(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,dl.default)(K$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,dl.default)(z$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(pe(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=i==null?void 0:i.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(pe(this.params.source.url,u))}return;default:return Gg(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Yg.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Kg(this.videoState.stateChangeStarted$.pipe(Zs(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Zs(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Ie(this.video);this.subscription.add(this.representations$.pipe(Zs(i=>i.map(({track:s})=>s)),zg(i=>!!i.length),Q$()).subscribe(i=>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:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.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(H$(),Zs(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(q$({zeroTime:this.zeroTime$.pipe(zg(ll)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(at(this.video,this.params.desiredState.isLooped,t)).add(Te(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Be(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Fe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&W$(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.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 Gg(i.to)}},t)).add(Kg(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,j$(["init"])).pipe(U$(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),ye(this.video)}createLiveDashPlayer(){let e=new Qi({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,h,p,m;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=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&ll(t)?t:Vt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;Wg(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;Wg(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(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(pe(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Jg=Wi;var Dy=V(it(),1);var nt=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as VC,assertNonNullable as BC,debounce as _C,ErrorCategory as Kl,filter as Ly,filterChanged as Da,fromEvent as NC,isNonNullable as My,map as Jl,merge as kn,observableFrom as FC,once as Cy,Subscription as qC}from"@vkontakte/videoplayer-shared/es2015";var en=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 i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];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}},zr=class extends en{constructor(){super(),this.listeners||en.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)}},Yi=class{constructor(){Object.defineProperty(this,"signal",{value:new zr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){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(i){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&&(Yi.prototype[Symbol.toStringTag]="AbortController",zr.prototype[Symbol.toStringTag]="AbortSignal");function tn(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function pl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!tn({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},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(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var zi=tn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Xg=zi?pl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,mt=zi?Xg.fetch:window.fetch,bF=zi?Xg.Request:window.Request,Me=zi?Yi:window.AbortController,gF=zi?zr:window.AbortSignal;var Wl=V(ml(),1);var dn=V(Wr(),1);var ft=()=>window.ManagedMediaSource||window.MediaSource,rn=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},vv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Sv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as hn,clientChecker as pn}from"@vkontakte/videoplayer-shared/es2015";var qe=document.createElement("video"),TL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',IL='video/mp4; codecs="hev1.1.6.L93.B0"',$v='video/webm; codecs="vp09.00.10.08"',Lv='video/webm; codecs="av01.0.00M.08"',EL='audio/mp4; codecs="mp4a.40.2"',xL='audio/webm; codecs="opus"',yv,Tv,Ki={mms:rn(),mse:vv(),hls:!!((yv=qe.canPlayType)!=null&&yv.call(qe,"application/x-mpegurl")||(Tv=qe.canPlayType)!=null&&Tv.call(qe,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Iv,Ev,xe={mp4:!!((Iv=qe.canPlayType)!=null&&Iv.call(qe,"video/mp4")),webm:!!((Ev=qe.canPlayType)!=null&&Ev.call(qe,"video/webm")),cmaf:!0},sn,xv,nn,Pv,on,Av,un,wv,ln,kv,cn,Rv,Pe={h264:!!((xv=(sn=ft())==null?void 0:sn.isTypeSupported)!=null&&xv.call(sn,TL)),h265:!!((Pv=(nn=ft())==null?void 0:nn.isTypeSupported)!=null&&Pv.call(nn,IL)),vp9:!!((Av=(on=ft())==null?void 0:on.isTypeSupported)!=null&&Av.call(on,$v)),av1:!!((wv=(un=ft())==null?void 0:un.isTypeSupported)!=null&&wv.call(un,Lv)),aac:!!((kv=(ln=ft())==null?void 0:ln.isTypeSupported)!=null&&kv.call(ln,EL)),opus:!!((Rv=(cn=ft())==null?void 0:cn.isTypeSupported)!=null&&Rv.call(cn,xL))},Kr=(Pe.h264||Pe.h265)&&Pe.aac,ur,PL=()=>R(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:Lv})})),window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:$v})}))]);ur={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{PL()}catch(a){console.error(a)}var Jr=Ki.hls&&xe.mp4,Mv=()=>Object.keys(Pe).filter(a=>Pe[a]),Cv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=Ki.mse&&(!r||!!window.MediaStreamTrack)||Ki.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&xe.mp4&&Kr;case"DASH_WEBM":return i&&xe.webm&&Pe.vp9&&Pe.opus;case"DASH_WEBM_AV1":return i&&xe.webm&&Pe.av1&&Pe.opus;case"DASH_STREAMS":return i&&(xe.mp4&&Kr||xe.webm&&(Pe.vp9||Pe.av1)&&(Pe.opus||Pe.aac));case"DASH_LIVE":return i&&xe.mp4&&Kr;case"DASH_LIVE_CMAF":return i&&xe.mp4&&Kr&&xe.cmaf;case"DASH_ONDEMAND":return i&&xe.mp4&&Kr;case"HLS":case"HLS_ONDEMAND":return Jr||e&&i&&xe.mp4&&Kr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Jr;case"MPEG":return xe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return Ki.webrtc&&Ki.ws&&Pe.h264&&(xe.mp4||xe.webm);default:return hn(s)}})},an=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return ur?ur[t].smooth?[t,e]:ur[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ur?ur[t].powerEfficient?[t,e]:ur[e].powerEfficient?[e,t]:[t,e]:[e,t];default:hn(a)}return[e,t]},Dv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...an(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(pn.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...an(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...an(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...an(a),...i,"HLS","HLS_ONDEMAND"];default:hn(e)}return Jr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Ov=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=pn.isMac&&pn.isSafari;if(pn.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:hn(a)}else Jr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},fl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Vv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,dn.default)(t.value.split("."),0)}for(let t of a){let r=(0,dn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,dn.default)(e.value.split("."),0)};var iS=V(rS(),1);import{ErrorCategory as Xi}from"@vkontakte/videoplayer-shared/es2015";var aS=a=>{if(!a)return{id:"EmptyResponse",category:Xi.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Xi.NETWORK,message:`UV Error ${a}`};let e=(0,iS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Xi.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Xi.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Xi.PARSER,message:"Response is valid XML, but parser failed"}};var Bt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as jl,assertNonNullable as mr,clientChecker as bC,combine as $a,ErrorCategory as qt,filter as In,filterChanged as Ql,flattenObject as La,fromEvent as fr,getTraceSubscriptionMethod as gC,interval as Gl,isNonNullable as Iy,map as Ma,merge as br,now as vC,Subject as Ey,Subscription as xy,tap as SC,throttle as yC,ValueSubject as ee}from"@vkontakte/videoplayer-shared/es2015";var bn=V(it(),1),ti=V(Wr(),1),gn=V(ml(),1);var UL=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},HL=a=>window.clearTimeout(a),sS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),nS=!sS(window.requestIdleCallback)||!sS(window.cancelIdleCallback),yl=nS?UL:window.requestIdleCallback,Zi=nS?HL:window.cancelIdleCallback;var my=V(Us(),1);import{assertNever as jL,ErrorCategory as oS,clientChecker as Tl,Subject as uS}from"@vkontakte/videoplayer-shared/es2015";var QL=18,lS=!1;try{lS=Tl.isSafari&&!!Tl.macVersion&&Tl.macVersion<=QL}catch(a){console.error(a)}var Il=class{constructor(e){this.bufferFull$=new uS;this.error$=new uS;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:oS.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 i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return R(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return R(this,null,function*(){return new Promise(t=>{let r;lS&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!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 i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.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:oS.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:jL(t)}}},cS=Il;var El=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as dr,assertNonNullable as be,ErrorCategory as Nt,fromEvent as Nl,getExponentialDelay as Fl,isNonNullable as mn,isNullable as Ue,now as fn,once as nC,Subject as oC,Subscription as uC,ValueSubject as ei}from"@vkontakte/videoplayer-shared/es2015";var G=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 i=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,i),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 i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}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 Xr=class extends G{};var ea=class extends G{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ta=class extends G{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ra=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var J=class extends G{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ia=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var aa=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var sa=class extends G{constructor(e,t){super(e,t),this.data=this.content}};var lr=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var na=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oa=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ua=class extends J{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var la=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ca=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var da=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pa=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var ha=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ma=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ba=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ga=class extends J{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var va=class extends J{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Sa=class extends J{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)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 WL={ftyp:ta,moov:ra,mvhd:ia,moof:aa,mdat:sa,sidx:lr,trak:na,mdia:da,mfhd:fa,tkhd:pa,traf:ba,tfhd:ga,tfdt:va,trun:Sa,minf:ha,sv3d:oa,st3d:ua,prhd:la,proj:ma,equi:ca,uuid:ea,unknown:Xr},bt=class a{constructor(e={}){this.options=P({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(i){break}return t}createBox(e,t){let r=WL[e];return r?new r(t,new a):new Xr(t,new a)}};var _t=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),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 zL=new TextDecoder("ascii"),KL=a=>zL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",JL=a=>{let e=new lr(a,new bt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.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})},XL=(a,e)=>{let r=new bt().parse(a),i=new _t(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.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(a.buffer,l,d)},ZL=a=>{let t=new bt().parse(a),r=new _t(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},eM=a=>{var i;let t=new bt().parse(a);return(i=new _t(t).find("sidx"))==null?void 0:i.timescale},tM=(a,e)=>{let r=new bt().parse(a),s=new _t(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,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},rM=a=>{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 bt().parse(a),i=new _t(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.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},dS={validateData:KL,parseInit:rM,getIndexRange:()=>{},parseSegments:JL,parseFeedableSegmentChunk:XL,getChunkEndTime:tM,getServerLatencyTimestamps:ZL,getTimescaleFromIndex:eM};var Ta=V(it(),1);import{assertNonNullable as Pl,isNonNullable as fS,isNullable as aM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as iM}from"@vkontakte/videoplayer-shared/es2015";var pS={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"}},hS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=ya(a,t),i=r in pS,s=i?pS[r].type:"binary",n=a.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(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=ya(u),d=l*et(2,(o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},ya=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*et(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*et(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*et(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ya(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:iM(e)}},cr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=hS(r);if(!e(i))return;i.type==="master"&&cr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},mS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=hS(a);return cr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=ze(o,n):s===17026?t=ze(o,n):s===17029&&(r=ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var bS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],sM=[231,22612,22743,167,171,163,160,175],nM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return cr(a,({tag:h,type:p,value:m,valueSize:b})=>{if(h===21419){let g=ze(m,p);l=ya(g)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=ze(m,p):h===17545?i=ze(m,p):h===21420&&l===475249515?u=ze(m,p):h===374648427?cr(m,({tag:g,type:S,value:v})=>g===30321?(c=ze(v,S)===1,!1):!0):s&&n&&(0,Ta.default)(bS,h)&&(o=!0),!o}),Pl(e,"Failed to parse webm Segment start"),Pl(t,"Failed to parse webm Segment end"),Pl(i,"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(i/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}}}},oM=a=>{if(aM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},uM=(a,e)=>{let t=!1,r=!1,i=o=>fS(o.time)&&fS(o.position),s=[],n;return cr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=ze(l,u));break;case 183:break;case 241:n&&(n.position=ze(l,u));break;default:t&&(0,Ta.default)(bS,o)&&(r=!0)}return!(t&&r)}),n&&i(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}}})},lM=a=>{let e=0,t=!1;try{cr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Ta.default)(sM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Ta.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},gS={validateData:mS,parseInit:nM,getIndexRange:oM,parseSegments:uM,parseFeedableSegmentChunk:lM};var Ia=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return gS;case"mp4":return dS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Ml=V(BS(),1),ny=V(Or(),1),oy=V(ZS(),1),uy=V(Wr(),1);var ey=V(it(),1),Ll=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,ey.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as iy,isNullable as ay}from"@vkontakte/videoplayer-shared/es2015";var ty=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var ry=a=>{var e;try{let t=aC(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function aC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
61
+ [selected audio track] ${f==null?void 0:f.id}
62
+ `}),f&&Mg(i,u,f,o)};var oe=a=>new URL(a).hostname;import{assertNever as Hg,assertNonNullable as jg,combine as _$,debounce as N$,ErrorCategory as Gg,filter as Qg,filterChanged as F$,isNonNullable as nl,map as Js,merge as Wg,observableFrom as q$,once as U$,Subscription as H$,ValueSubject as ol,videoQualityToHeight as j$,videoSizeToQuality as G$}from"@vkontakte/videoplayer-shared/es2015";var Og=F(it(),1);var Dg=a=>{if(a instanceof DOMException&&(0,Og.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},xe=(a,e)=>k(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!Dg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return Dg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as Ys,isNullable as y$,assertNonNullable as Hi}from"@vkontakte/videoplayer-shared/es2015";var Bg=F(Vi(),1);import{isNonNullable as Vg,assertNonNullable as Ws,now as v$}from"@vkontakte/videoplayer-shared/es2015";function ue(){return v$()}function rl(a){return ue()-a}function il(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(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 _g(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function zr(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;Ws(c);let R=rl(c),j;if(R<b){j=b-R,setTimeout(g,j);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,$()},S=R=>(s=R,q),v=R=>(d=R,q),y=()=>(p="json",q),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},E=R=>(h=R,q),$=()=>{c=ue(),n=new i,n.open("get",a);let R=0,j,L=0,W=()=>(Ws(c),Math.max(c,Math.max(j||0,L||0)));if(s&&n.addEventListener("progress",w=>{let T=ue();s.updateChunk&&w.loaded>R&&(s.updateChunk(W(),w.loaded-R),R=w.loaded,j=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;Ws(n);let w=n.status;if(w>=200&&w<300){if(n.response.byteLength&&s){let T=n.response.byteLength-R;T&&s.updateChunk&&s.updateChunk(W(),T)}n.responseType==="json"&&!(0,Bg.default)(n.response).length?I():(d&&d(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),h){let w=()=>{Ws(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(L=ue(),n.removeEventListener("readystatechange",w))};n.addEventListener("readystatechange",w)}return n.responseType=p,n.send(),q},q={withBitrateReporting:S,withParallel:E,withJSONResponse:y,withRetryCount:R=>(l=R,q),withRetryInterval:(R,j)=>(Vg(R)&&(b=R),Vg(j)&&(f=j),q),withTimeout:R=>(o=R,q),withFinally:v,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return q}var qi=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,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=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;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*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(i)}/${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 Ng=F(Vi(),1);var Ui=class{constructor(e,t,r,i,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=i,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=ue(),i=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=ue()-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=zr(t,s,()=>i("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=ue()}_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=ue();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Ng.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,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=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as T$}from"@vkontakte/videoplayer-shared/es2015";var zs=1e4,al=3;var I$=6e4,E$=10,x$=1,P$=500,ji=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new T$,this.chunkRateEstimator=new qi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=il(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=il(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 i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.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,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,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)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||Ys(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{_g(i,"progress",()=>{i.buffered.length?(i.currentTime=i.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 Ui(al,zs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},h=(I,E,$)=>{u&&u.abort(),u=zr(this.urlResolver.resolve(I,!1),E,$,()=>this._retryCallback()).withTimeout(zs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(al).withFinally(()=>{u=null}).send()},p=(I,E,$)=>{Hi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let E=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let $=ue()-1e4,D=0;for(let N=0;N<this.bufferStates.length;N++){let O=this.bufferStates[N];I=Math.min(I,O.buf),O.ts<$&&D++}this.bufferStates.splice(0,D),t(`update playback rate; minBuffer=${I} drop=${D} jitter=${this.sourceJitter}`);let z=I-x$;this.sourceJitter>=0?z-=this.sourceJitter/2:this.sourceJitter-=1,z>3?f(1.15):z>1?f(1.1):z>.3?f(1.05):f(1)}},S=I=>{let E,$=()=>E&&E.start?E.start.length:0,D=w=>E.start[w]/1e3,z=w=>E.dur[w]/1e3,N=w=>E.fragIndex+w,O=(w,T)=>({chunkIdx:N(w),startTS:D(w),dur:z(w),discontinuity:T}),q=()=>{let w=0;if(E&&E.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,_=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,V=T;this.sourceJitter>1&&(V+=this.sourceJitter-1);let ie=E.dur.length-1;for(;ie>=0&&(V-=E.dur[ie],!(V<=0));--ie);w=Math.min(ie,E.dur.length-1-_),w=Math.max(w,0)}return O(w,!0)},R=w=>{let T=$();if(!(T<=0)){if(Ys(w)){for(let _=0;_<T;_++)if(D(_)>w)return O(_)}return q()}},j=w=>{let T=$(),_=w?w.chunkIdx+1:0,V=_-E.fragIndex;if(!(T<=0)){if(!w||V<0||V-T>E$)return t(`Resync: offset=${V} bChunks=${T} chunk=`+JSON.stringify(w)),q();if(!(V>=T))return O(_-E.fragIndex,!1)}},L=(w,T,_)=>{l&&l.abort(),l=zr(this.urlResolver.resolve(w,!0,this.lowLatency),T,_,()=>this._retryCallback()).withTimeout(zs).withRetryCount(al).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(w,T)=>{L(I,_=>{if(!d())return;E=_;let V=!!E.lowLatency;V!==this.lowLatency&&b(V);let ie=0;for(let Oe=0;Oe<E.dur.length;++Oe)ie+=E.dur[Oe];ie>0&&(Hi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,w(R(T))},()=>this._handleNetworkError())},nextChunk:j}},v=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Hi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:$}=this.params,D=S(e.jidxUrl),z,N,O,q,R=0,j,L,W,w=()=>{j&&(clearTimeout(j),j=void 0);let H=Math.max(P$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),le=R+H,ce=ue(),Ve=Math.min(1e4,le-ce);R=ce;let Tt=()=>{l||d()&&D.seek(()=>{d()&&(R=ue(),T(),w())})};Ve>0?j=window.setTimeout(()=>{this.paused?w():Tt()},Ve):Tt()},T=()=>{let H;for(;H=D.nextChunk(q);)q=H,yt(H);let le=D.nextChunk(O);if(le){if(O&&le.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?w():(v(),this._initPlayerWith(e));return}Oe(le)}else w()},_=(H,le)=>{if(!d()||!this.sourceBuffer)return;let ce,Ve,Tt,Sr=It=>{window.setTimeout(()=>{d()&&_(H,le)},It)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),Sr(100);else{let It=ue(),Qt=E.currentTime;!this.paused&&E.buffered.length>1&&L===Qt&&It-W>500&&($("Stall suspected; trying to fix"),this._fixupStall()),L!==Qt&&(L=Qt,W=It);let yr=this._getBufferSizeSec();if(yr>30)$(`Buffered ${yr} seconds; delaying appendBuffer`),Sr(2e3);else try{this.sourceBuffer.appendBuffer(H),this.videoPlayStarted?(this.bufferStates.push({ts:It,buf:yr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),le&&le()}catch(ni){if(ni.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),Tt=this.sourceBuffer.buffered.length,Tt!==0&&(ce=this.sourceBuffer.buffered.start(0),Ve=Qt,Ve-ce>4&&this.sourceBuffer.remove(ce,Ve-3)),Sr(1e3);else throw ni}}},V=()=>{N&&z&&($([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(O)]),_(N,function(){N=null,T()}))},ie=H=>e.fragUrlTemplate.replace("%%id%%",H.chunkIdx),Oe=H=>{d()&&p(ie(H),(le,ce)=>{if(d()){if(ce/=1e3,N=le,O=H,n=H.startTS,ce){let Ve=Math.min(10,H.dur/ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ve:Ve}V()}},()=>this._handleNetworkError())},yt=H=>{d()&&(Hi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(H),!1)))},vr=H=>{d()&&(e.cachedHeader=H,_(H,()=>{z=!0,V()}))};s=!0,D.seek(H=>{if(d()){if(R=ue(),!H){w();return}q=H,!y$(I)||H.startTS>I?Oe(H):(O=H,T())}},I),e.cachedHeader?vr(e.cachedHeader):h(e.headerUrl,vr,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),Ys(i)&&(i+=.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,Hi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return Ys(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let h,p,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),f=d/this.bitrate,p>10&&f>.8||p>15&&f>.5||p>20&&f>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let f=ue();if(this.chunkRateEstimator.addInterval(h,f,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:f-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&rl(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=ue();d<o&&(n=h),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=zr(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(zs).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;xe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.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))},I$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ug=F(Vr(),1);import{debounce as A$,filter as Fg,fromEvent as w$,interval as k$,isHigher as R$,isInvariantQuality as $$,isLower as L$,merge as M$,Subject as qg,Subscription as C$}from"@vkontakte/videoplayer-shared/es2015";var sl=class{constructor(){this.onDroopedVideoFramesLimit$=new qg;this.subscription=new C$;this.playing=!1;this.tracks=[];this.forceChecker$=new qg;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&&!$$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&R$(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(w$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=k$(this.droppedFramesChecker.checkTime).pipe(Fg(()=>this.playing),Fg(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(A$(this.droppedFramesChecker.checkTime)),r=M$(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,i;let t=(i=(r=(0,Ug.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>L$(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[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}},Ks=sl;import{map as D$,Observable as O$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as V$}from"@vkontakte/videoplayer-shared/es2015";var Gi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var B$=(a,e)=>new O$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Gi()))},P(P({},r),e));i.observe(a);let s=V$(document,"visibilitychange").pipe(D$(n=>!document.hidden||Gi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),qe=B$;var Q$=["paused","playing","ready"],W$=["paused","playing","ready"],Qi=class{constructor(e){this.subscription=new H$;this.videoState=new C("stopped");this.representations$=new ol([]);this.textTracksManager=new Ne;this.droppedFramesManager=new Ks;this.maxSeekBackTime$=new ol(1/0);this.zeroTime$=new ol(void 0);this.liveOffset=new pt;this._dashCb=e=>{var t,r,i,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:Gg.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=Ot(u.name))!=null?r:G$(u.video),d=u.bitrate/1e3,h=P({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.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),nl(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(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,ul.default)(W$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,ul.default)(Q$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(fe(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=i==null?void 0:i.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(fe(this.params.source.url,u))}return;default:return Hg(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Gg.WTF,message:"DashLiveProvider internal logic error",thrown:i})};Wg(this.videoState.stateChangeStarted$.pipe(Js(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Js(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Ee(this.video);this.subscription.add(this.representations$.pipe(Js(i=>i.map(({track:s})=>s)),Qg(i=>!!i.length),U$()).subscribe(i=>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:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.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(F$(),Js(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(_$({zeroTime:this.zeroTime$.pipe(Qg(nl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(at(this.video,this.params.desiredState.isLooped,t)).add(Ie(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(_e(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(qe(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&j$(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.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 Hg(i.to)}},t)).add(Wg(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,q$(["init"])).pipe(N$(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),Te(this.video)}createLiveDashPlayer(){let e=new ji({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,h,p,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=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&nl(t)?t:Bt(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;jg(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;jg(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(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(fe(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var Yg=Qi;var Ly=F(it(),1);var nt=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as CC,assertNonNullable as DC,debounce as OC,ErrorCategory as Wl,filter as ky,filterChanged as Ca,fromEvent as VC,isNonNullable as Ry,map as Yl,merge as An,observableFrom as BC,once as $y,Subscription as _C}from"@vkontakte/videoplayer-shared/es2015";var Xs=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 i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];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}},Kr=class extends Xs{constructor(){super(),this.listeners||Xs.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)}},Wi=class{constructor(){Object.defineProperty(this,"signal",{value:new Kr,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){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(i){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&&(Wi.prototype[Symbol.toStringTag]="AbortController",Kr.prototype[Symbol.toStringTag]="AbortSignal");function Zs(a){return a.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof a.Request=="function"&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function ll(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!Zs({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},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(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var Yi=Zs({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zg=Yi?ll({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ft=Yi?zg.fetch:window.fetch,nF=Yi?zg.Request:window.Request,Me=Yi?Wi:window.AbortController,oF=Yi?Kr:window.AbortSignal;var jl=F(dl(),1);var ln=F(Yr(),1);var mt=()=>window.ManagedMediaSource||window.MediaSource,en=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},mv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},bv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as dn,clientChecker as cn}from"@vkontakte/videoplayer-shared/es2015";var Ue=document.createElement("video"),vL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',SL='video/mp4; codecs="hev1.1.6.L93.B0"',wv='video/webm; codecs="vp09.00.10.08"',kv='video/webm; codecs="av01.0.00M.08"',yL='audio/mp4; codecs="mp4a.40.2"',TL='audio/webm; codecs="opus"',gv,vv,zi={mms:en(),mse:mv(),hls:!!((gv=Ue.canPlayType)!=null&&gv.call(Ue,"application/x-mpegurl")||(vv=Ue.canPlayType)!=null&&vv.call(Ue,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Sv,yv,Pe={mp4:!!((Sv=Ue.canPlayType)!=null&&Sv.call(Ue,"video/mp4")),webm:!!((yv=Ue.canPlayType)!=null&&yv.call(Ue,"video/webm")),cmaf:!0},rn,Tv,an,Iv,sn,Ev,nn,xv,on,Pv,un,Av,Ae={h264:!!((Tv=(rn=mt())==null?void 0:rn.isTypeSupported)!=null&&Tv.call(rn,vL)),h265:!!((Iv=(an=mt())==null?void 0:an.isTypeSupported)!=null&&Iv.call(an,SL)),vp9:!!((Ev=(sn=mt())==null?void 0:sn.isTypeSupported)!=null&&Ev.call(sn,wv)),av1:!!((xv=(nn=mt())==null?void 0:nn.isTypeSupported)!=null&&xv.call(nn,kv)),aac:!!((Pv=(on=mt())==null?void 0:on.isTypeSupported)!=null&&Pv.call(on,yL)),opus:!!((Av=(un=mt())==null?void 0:un.isTypeSupported)!=null&&Av.call(un,TL))},Jr=(Ae.h264||Ae.h265)&&Ae.aac,ur,IL=()=>k(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:kv})})),window.navigator.mediaCapabilities.decodingInfo(M(P({},a),{video:M(P({},a.video),{contentType:wv})}))]);ur={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{IL()}catch(a){console.error(a)}var Xr=zi.hls&&Pe.mp4,Rv=()=>Object.keys(Ae).filter(a=>Ae[a]),$v=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=zi.mse&&(!r||!!window.MediaStreamTrack)||zi.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Pe.mp4&&Jr;case"DASH_WEBM":return i&&Pe.webm&&Ae.vp9&&Ae.opus;case"DASH_WEBM_AV1":return i&&Pe.webm&&Ae.av1&&Ae.opus;case"DASH_STREAMS":return i&&(Pe.mp4&&Jr||Pe.webm&&(Ae.vp9||Ae.av1)&&(Ae.opus||Ae.aac));case"DASH_LIVE":return i&&Pe.mp4&&Jr;case"DASH_LIVE_CMAF":return i&&Pe.mp4&&Jr&&Pe.cmaf;case"DASH_ONDEMAND":return i&&Pe.mp4&&Jr;case"HLS":case"HLS_ONDEMAND":return Xr||e&&i&&Pe.mp4&&Jr;case"HLS_LIVE":case"HLS_LIVE_CMAF":return Xr;case"MPEG":return Pe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return zi.webrtc&&zi.ws&&Ae.h264&&(Pe.mp4||Pe.webm);default:return dn(s)}})},tn=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return ur?ur[t].smooth?[t,e]:ur[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return ur?ur[t].powerEfficient?[t,e]:ur[e].powerEfficient?[e,t]:[t,e]:[e,t];default:dn(a)}return[e,t]},Lv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...tn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(cn.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...tn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...tn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...tn(a),...i,"HLS","HLS_ONDEMAND"];default:dn(e)}return Xr?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Mv=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=cn.isMac&&cn.isSafari;if(cn.isAndroid)switch(a){case"dash":case"dash_any_mpeg":case"dash_any_webm":case"dash_sep":{o=s;break}case"hls":case"mpeg":{o=n;break}default:dn(a)}else Xr&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},pl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Cv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,ln.default)(t.value.split("."),0)}for(let t of a){let r=(0,ln.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,ln.default)(e.value.split("."),0)};var eS=F(Zv(),1);import{ErrorCategory as Ji}from"@vkontakte/videoplayer-shared/es2015";var tS=a=>{if(!a)return{id:"EmptyResponse",category:Ji.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:Ji.NETWORK,message:`UV Error ${a}`};let e=(0,eS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:Ji.NETWORK,message:"Received unexpected HTML, possibly a ISP block"};if(e.startsWith("<?xml"))return new DOMParser().parseFromString(a,"text/xml").querySelector("parsererror")?{id:"InvalidXML",category:Ji.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:Ji.PARSER,message:"Response is valid XML, but parser failed"}};var _t=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as ql,assertNonNullable as fr,clientChecker as hC,combine as Ra,ErrorCategory as Ut,filter as yn,filterChanged as Ul,flattenObject as $a,fromEvent as mr,getTraceSubscriptionMethod as fC,interval as Hl,isNonNullable as Sy,map as La,merge as br,now as mC,Subject as yy,Subscription as Ty,tap as bC,throttle as gC,ValueSubject as ee}from"@vkontakte/videoplayer-shared/es2015";var fn=F(it(),1),ri=F(Yr(),1),mn=F(dl(),1);var NL=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},FL=a=>window.clearTimeout(a),rS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),iS=!rS(window.requestIdleCallback)||!rS(window.cancelIdleCallback),gl=iS?NL:window.requestIdleCallback,Xi=iS?FL:window.cancelIdleCallback;var dy=F(qs(),1);import{assertNever as qL,ErrorCategory as aS,clientChecker as vl,Subject as sS}from"@vkontakte/videoplayer-shared/es2015";var UL=18,nS=!1;try{nS=vl.isSafari&&!!vl.macVersion&&vl.macVersion<=UL}catch(a){console.error(a)}var Sl=class{constructor(e){this.bufferFull$=new sS;this.error$=new sS;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:aS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return k(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return k(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return k(this,null,function*(){return new Promise(t=>{let r;nS&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(let{callback:i}of this.queue)i(!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 i;if(this.buffer.updating||this.currentTask||this.destroyed)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.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:aS.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:qL(t)}}},oS=Sl;var yl=a=>{let e=0;for(let t=0;t<a.length;t++)e+=a.end(t)-a.start(t);return e*1e3};import{abortable as dr,assertNonNullable as ge,ErrorCategory as Ft,fromEvent as Vl,getExponentialDelay as Bl,isNonNullable as pn,isNullable as He,now as hn,once as iC,Subject as aC,Subscription as sC,ValueSubject as ti}from"@vkontakte/videoplayer-shared/es2015";var Q=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 i=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,i),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 i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}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 Zr=class extends Q{};var Zi=class extends Q{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var ea=class extends Q{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ta=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var J=class extends Q{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ra=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ia=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var aa=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var lr=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var sa=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var na=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var oa=class extends J{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var ua=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var la=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ca=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var da=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var pa=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ha=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var ma=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ba=class extends J{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var ga=class extends J{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var va=class extends J{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)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 jL={ftyp:ea,moov:ta,mvhd:ra,moof:ia,mdat:aa,sidx:lr,trak:sa,mdia:ca,mfhd:fa,tkhd:da,traf:ma,tfhd:ba,tfdt:ga,trun:va,minf:pa,sv3d:na,st3d:oa,prhd:ua,proj:ha,equi:la,uuid:Zi,unknown:Zr},bt=class a{constructor(e={}){this.options=P({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(i){break}return t}createBox(e,t){let r=jL[e];return r?new r(t,new a):new Zr(t,new a)}};var Nt=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),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 QL=new TextDecoder("ascii"),WL=a=>QL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",YL=a=>{let e=new lr(a,new bt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.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})},zL=(a,e)=>{let r=new bt().parse(a),i=new Nt(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.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(a.buffer,l,d)},KL=a=>{let t=new bt().parse(a),r=new Nt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},JL=a=>{var i;let t=new bt().parse(a);return(i=new Nt(t).find("sidx"))==null?void 0:i.timescale},XL=(a,e)=>{let r=new bt().parse(a),s=new Nt(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,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},ZL=a=>{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 bt().parse(a),i=new Nt(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.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},uS={validateData:WL,parseInit:ZL,getIndexRange:()=>{},parseSegments:YL,parseFeedableSegmentChunk:zL,getChunkEndTime:XL,getServerLatencyTimestamps:KL,getTimescaleFromIndex:JL};var ya=F(it(),1);import{assertNonNullable as Il,isNonNullable as pS,isNullable as tM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as eM}from"@vkontakte/videoplayer-shared/es2015";var lS={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"}},cS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=Sa(a,t),i=r in lS,s=i?lS[r].type:"binary",n=a.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(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=Sa(u),d=l*et(2,(o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},Sa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*et(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*et(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*et(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ke=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Sa(a);case"float":return a.byteLength===4?a.getFloat32(0):a.getFloat64(0);case"string":return new TextDecoder("ascii").decode(a);case"utf8":return new TextDecoder("utf-8").decode(a);case"date":return new Date(Date.UTC(2001,0)+a.getInt8(0)).getTime();case"master":return a;case"binary":return a;default:eM(e)}},cr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=cS(r);if(!e(i))return;i.type==="master"&&cr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},dS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=cS(a);return cr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ke(o,n):s===17026?t=Ke(o,n):s===17029&&(r=Ke(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var hS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],rM=[231,22612,22743,167,171,163,160,175],iM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return cr(a,({tag:h,type:p,value:f,valueSize:b})=>{if(h===21419){let g=Ke(f,p);l=Sa(g)}else h!==21420&&(l=void 0);return h===408125543?(e=f.byteOffset,t=f.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?r=Ke(f,p):h===17545?i=Ke(f,p):h===21420&&l===475249515?u=Ke(f,p):h===374648427?cr(f,({tag:g,type:S,value:v})=>g===30321?(c=Ke(v,S)===1,!1):!0):s&&n&&(0,ya.default)(hS,h)&&(o=!0),!o}),Il(e,"Failed to parse webm Segment start"),Il(t,"Failed to parse webm Segment end"),Il(i,"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(i/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}}}},aM=a=>{if(tM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},sM=(a,e)=>{let t=!1,r=!1,i=o=>pS(o.time)&&pS(o.position),s=[],n;return cr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ke(l,u));break;case 183:break;case 241:n&&(n.position=Ke(l,u));break;default:t&&(0,ya.default)(hS,o)&&(r=!0)}return!(t&&r)}),n&&i(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}}})},nM=a=>{let e=0,t=!1;try{cr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ya.default)(rM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ya.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},fS={validateData:dS,parseInit:iM,getIndexRange:aM,parseSegments:sM,parseFeedableSegmentChunk:nM};var Ta=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return fS;case"mp4":return uS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Rl=F(DS(),1),iy=F(Vr(),1),ay=F(KS(),1),sy=F(Yr(),1);var JS=F(it(),1),kl=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,JS.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as ey,isNullable as ty}from"@vkontakte/videoplayer-shared/es2015";var XS=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var ZS=a=>{var e;try{let t=tC(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function tC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
63
63
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
64
64
  (-(?<script>[a-z]{4}))?
65
65
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
66
66
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
67
67
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
68
68
  (?:-(?<privateuse>(?:${e})))?
69
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var sy=a=>{if(!a.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(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},gt=(a,e)=>{let t=a;t=(0,Ml.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,ny.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Ml.default)(t,n,(o,u)=>ay(s)?o:ay(u)?s:(0,oy.default)(s,parseInt(u,10),"0"))}return t},ly=(a,e)=>{var E,w,U,B,H,O,_,$,j,L,Y,y,k,W,N,he,Je,si,Qt,q,ie,we,Oe,yt,vr,Tt,Gt,Sr,ni,hc,mc,fc,bc,gc,vc,Sc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc,Rc,$c,Lc,Mc,Cc,Dc,Oc,Vc,Bc,_c,Nc,Fc,qc,Uc,Hc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(le=>{var Ya,It;return(It=(Ya=le.textContent)==null?void 0:Ya.trim())!=null?It:""}),u=(E=(0,uy.default)(o,0))!=null?E:"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,m=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(m)p=sy(m);else if(b){let le=sy(b);iy(le)&&(p=le)}else S&&(p=parseInt(S,10));let v=0,T=(U=(w=s.getAttribute("profiles"))==null?void 0:w.split(","))!=null?U:[];for(let le of l){let Ya=(B=le.getAttribute("id"))!=null?B:"id"+(v++).toString(10),It=(H=le.getAttribute("mimeType"))!=null?H:"",Hn=(O=le.getAttribute("codecs"))!=null?O:"",jn=(_=le.getAttribute("contentType"))!=null?_:It==null?void 0:It.split("/")[0],RT=(j=($=le.getAttribute("profiles"))==null?void 0:$.split(","))!=null?j:[],jc=(Y=ry((L=le.getAttribute("lang"))!=null?L:""))!=null?Y:{},$T=(W=(k=(y=le.querySelector("Label"))==null?void 0:y.textContent)==null?void 0:k.trim())!=null?W:void 0,LT=le.querySelectorAll("Representation"),MT=le.querySelector("SegmentTemplate"),CT=(he=(N=le.querySelector("Role"))==null?void 0:N.getAttribute("value"))!=null?he:void 0,oi=jn,ae={id:Ya,language:jc.language,isDefault:CT==="main",label:$T,codecs:Hn,hdr:oi==="video"&&Ll(Hn),mime:It,representations:[]};for(let K of LT){let DT=(Je=K.getAttribute("lang"))!=null?Je:void 0,OT=(si=K.getAttribute("label"))!=null?si:void 0,VT=(ie=(q=(Qt=K.querySelector("BaseURL"))==null?void 0:Qt.textContent)==null?void 0:q.trim())!=null?ie:"",za=new URL(VT||u,e).toString(),yr=(we=K.getAttribute("mimeType"))!=null?we:It,Ka=(yt=(Oe=K.getAttribute("codecs"))!=null?Oe:Hn)!=null?yt:"",Ja;if(jn==="text"){let Et=K.getAttribute("id")||"",Xa=((vr=jc.privateuse)==null?void 0:vr.includes("x-auto"))||Et.includes("_auto"),Wt=K.querySelector("SegmentTemplate");if(Wt){let ui={representationId:(Tt=K.getAttribute("id"))!=null?Tt:void 0,bandwidth:(Gt=K.getAttribute("bandwidth"))!=null?Gt:void 0},Za=parseInt((Sr=K.getAttribute("bandwidth"))!=null?Sr:"",10)/1e3,es=(hc=parseInt((ni=Wt.getAttribute("startNumber"))!=null?ni:"",10))!=null?hc:1,Tr=parseInt((mc=Wt.getAttribute("timescale"))!=null?mc:"",10),Qn=(fc=Wt.querySelectorAll("SegmentTimeline S"))!=null?fc:[],Ir=Wt.getAttribute("media");if(!Ir)continue;let ts=[],rs=0,is="",Er=0,li=es,me=0;for(let He of Qn){let Yt=parseInt((bc=He.getAttribute("d"))!=null?bc:"",10),Ve=parseInt((gc=He.getAttribute("r"))!=null?gc:"",10)||0,xt=parseInt((vc=He.getAttribute("t"))!=null?vc:"",10);me=Number.isFinite(xt)?xt:me;let zt=Yt/Tr*1e3,Pt=me/Tr*1e3;for(let Xe=0;Xe<Ve+1;Xe++){let At=gt(Ir,M(P({},ui),{segmentNumber:li.toString(10),segmentTime:(me+Xe*Yt).toString(10)})),xr=(Pt!=null?Pt:0)+Xe*zt,di=xr+zt;li++,ts.push({time:{from:xr,to:di},url:At})}me+=(Ve+1)*Yt,rs+=(Ve+1)*zt}Er=me/Tr*1e3,is=gt(Ir,M(P({},ui),{segmentNumber:li.toString(10),segmentTime:me.toString(10)}));let ci={time:{from:Er,to:1/0},url:is},ut={type:"template",baseUrl:za,segmentTemplateUrl:Ir,initUrl:"",totalSegmentsDurationMs:rs,segments:ts,nextSegmentBeyondManifest:ci,timescale:Tr};Ja={id:Et,kind:"text",segmentReference:ut,profiles:[],duration:p,bitrate:Za,mime:"",codecs:"",width:0,height:0,isAuto:Xa}}else Ja={id:Et,isAuto:Xa,kind:"text",url:za}}else{let Et=(yc=(Sc=K.getAttribute("contentType"))!=null?Sc:yr==null?void 0:yr.split("/")[0])!=null?yc:jn,Xa=(Ic=(Tc=le.getAttribute("profiles"))==null?void 0:Tc.split(","))!=null?Ic:[],Wt=parseInt((Ec=K.getAttribute("width"))!=null?Ec:"",10),ui=parseInt((xc=K.getAttribute("height"))!=null?xc:"",10),Za=parseInt((Pc=K.getAttribute("bandwidth"))!=null?Pc:"",10)/1e3,es=(Ac=K.getAttribute("frameRate"))!=null?Ac:"",Tr=(wc=K.getAttribute("quality"))!=null?wc:void 0,Qn=es?ty(es):void 0,Ir=(kc=K.getAttribute("id"))!=null?kc:"id"+(v++).toString(10),ts=Et==="video"?`${ui}p`:Et==="audio"?`${Za}Kbps`:Ka,rs=`${Ir}@${ts}`,is=[...T,...RT,...Xa],Er,li=K.querySelector("SegmentBase"),me=(Rc=K.querySelector("SegmentTemplate"))!=null?Rc:MT;if(li){let ut=(Lc=($c=K.querySelector("SegmentBase Initialization"))==null?void 0:$c.getAttribute("range"))!=null?Lc:"",[He,Yt]=ut.split("-").map(At=>parseInt(At,10)),Ve={from:He,to:Yt},xt=(Mc=K.querySelector("SegmentBase"))==null?void 0:Mc.getAttribute("indexRange"),[zt,Pt]=xt?xt.split("-").map(At=>parseInt(At,10)):[],Xe=xt?{from:zt,to:Pt}:void 0;Er={type:"byteRange",url:za,initRange:Ve,indexRange:Xe}}else if(me){let ut={representationId:(Cc=K.getAttribute("id"))!=null?Cc:void 0,bandwidth:(Dc=K.getAttribute("bandwidth"))!=null?Dc:void 0},He=parseInt((Oc=me.getAttribute("timescale"))!=null?Oc:"",10),Yt=(Vc=me.getAttribute("initialization"))!=null?Vc:"",Ve=me.getAttribute("media"),xt=(_c=parseInt((Bc=me.getAttribute("startNumber"))!=null?Bc:"",10))!=null?_c:1,zt=gt(Yt,ut);if(!Ve)throw new ReferenceError("No media attribute in SegmentTemplate");let Pt=(Nc=me.querySelectorAll("SegmentTimeline S"))!=null?Nc:[],Xe=[],At=0,xr="",di=0;if(Pt.length){let as=xt,je=0;for(let Pr of Pt){let Ze=parseInt((Fc=Pr.getAttribute("d"))!=null?Fc:"",10),Kt=parseInt((qc=Pr.getAttribute("r"))!=null?qc:"",10)||0,ss=parseInt((Uc=Pr.getAttribute("t"))!=null?Uc:"",10);je=Number.isFinite(ss)?ss:je;let Gn=Ze/He*1e3,Wn=je/He*1e3;for(let ns=0;ns<Kt+1;ns++){let _T=gt(Ve,M(P({},ut),{segmentNumber:as.toString(10),segmentTime:(je+ns*Ze).toString(10)})),Qc=(Wn!=null?Wn:0)+ns*Gn,NT=Qc+Gn;as++,Xe.push({time:{from:Qc,to:NT},url:_T})}je+=(Kt+1)*Ze,At+=(Kt+1)*Gn}di=je/He*1e3,xr=gt(Ve,M(P({},ut),{segmentNumber:as.toString(10),segmentTime:je.toString(10)}))}else if(iy(p)){let je=parseInt((Hc=me.getAttribute("duration"))!=null?Hc:"",10)/He*1e3,Pr=Math.ceil(p/je),Ze=0;for(let Kt=1;Kt<Pr;Kt++){let ss=gt(Ve,M(P({},ut),{segmentNumber:Kt.toString(10),segmentTime:Ze.toString(10)}));Xe.push({time:{from:Ze,to:Ze+je},url:ss}),Ze+=je}di=Ze,xr=gt(Ve,M(P({},ut),{segmentNumber:Pr.toString(10),segmentTime:Ze.toString(10)}))}let BT={time:{from:di,to:1/0},url:xr};Er={type:"template",baseUrl:za,segmentTemplateUrl:Ve,initUrl:zt,totalSegmentsDurationMs:At,segments:Xe,nextSegmentBeyondManifest:BT,timescale:He}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Et||!yr)continue;let ci={video:"video",audio:"audio",text:"text"}[Et];if(!ci)continue;oi||(oi=ci),Ja={id:rs,kind:ci,segmentReference:Er,profiles:is,duration:p,bitrate:Za,mime:yr,codecs:Ka,width:Wt,height:ui,fps:Qn,quality:Tr}}ae.language||(ae.language=DT),ae.label||(ae.label=OT),ae.mime||(ae.mime=yr),ae.codecs||(ae.codecs=Ka),ae.hdr||(ae.hdr=oi==="video"&&Ll(Ka)),ae.representations.push(Ja)}oi&&i[oi].push(ae)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:i,baseUrls:o}};var Ol=V(Wr(),1);import{videoSizeToQuality as sC}from"@vkontakte/videoplayer-shared/es2015";var cy=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Dt(s):void 0)!=null?u:sC({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},dy=({id:a,bitrate:e})=>({id:a,bitrate:e}),py=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),hy=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Vl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ol.default)(r.split("."),0),isDefault:i}),Bl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ol.default)(i.split("."),0)}),_l=a=>"url"in a,Ce=a=>a.type==="template",Ea=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var xa=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ei(0);this.currentSegmentLength$=new ei(0);this.onLastSegment$=new ei(!1);this.fullyBuffered$=new ei(!1);this.playingRepresentation$=new ei(void 0);this.playingRepresentationInit$=new ei(void 0);this.error$=new oC;this.gaps=[];this.subscription=new uC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Me;this.switchAbortController=new Me;this.destroyAbortController=new Me;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=dr(this.destroyAbortController.signal,function(e){return re(this,null,function*(){let t=this.representations.get(e);be(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new cS(this.sourceBuffer),this.subscription.add(Nl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Nt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Nt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Nl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Nt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,El(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=nt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);be(r,"No init buffer for starting representation"),be(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchToOld=dr(this.destroyAbortController.signal,function(e,t=!1){return re(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);be(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Ue(s)||Ue(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),be(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();mn(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Kn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=dr(this.destroyAbortController.signal,function(e){return re(this,null,function*(){var u,l;let t=(u=(0,gn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!Ce(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);be(i);let s=this.segments.get(r);be(s,"No segments for starting representation");let n=this.initData.get(r);if(be(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Me,dr(this.switchAbortController.signal,function(r,i=!1){return re(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);be(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(Ue(o)||Ue(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),be(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();mn(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Me,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(Ue(e)||Ue(this.downloadingRepresentationId)||Ue(this.playingRepresentationId)||Ue(this.sourceBuffer)||mn(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(be(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=nt(this.sourceBuffer.buffered,e),p=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=i.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&El(this.sourceBuffer.buffered)>=this.bufferLimit){let d=nt(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);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&&i)if((0,bn.default)(o,i))d="high";else{let h=(0,ti.default)(o,0);h&&h.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&nt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ti.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=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+i}),r=s.time.to;mn(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,i=[],s=0,n=t.length-1;do i.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()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,gn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,gn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Ce(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>M(P({},h),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,ti.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;be(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Ce(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=gt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}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 i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.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&&Zi&&Zi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Zi&&Zi(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.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let b=h<=r&&p>=r,g=h>r||b||m===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=r+S||p<=r+S;return(d==="none"||d==="partially_ejected"&&g&&v&&this.sourceBuffer&&!(Bt(this.sourceBuffer.buffered,h)&&Bt(this.sourceBuffer.buffered,p)))&&g&&v});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+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=i;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,r="auto"){return R(this,null,function*(){Ce(t.segmentReference)?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 i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield dr(o,function(){return re(this,null,function*(){let c=Fl(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(this.lastDataObtainedTimestampMs=fn(),!c)return;let d=new DataView(c),h=Ia(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=h.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ea(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ce(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}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:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield dr(n,function(){return re(this,null,function*(){let u=Fl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Nl(window,"online").pipe(nC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=fn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ea(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Ce(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ti.default)(e,0).byte.from,to:(0,ti.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=fn(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Nt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ce(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=fn();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:Nt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,bn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return R(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ia(o.mime).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(o){return R(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,h=c.byte.to-r,p=h-d+1,m=d<i,b=h<=i;if(!m)continue;let g=Ia(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,i-d),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===p?S:g.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(c.status="partially_fed",l.feedingBytes+=v.byteLength,(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?(l.fedBytes+=v.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):n())}}})}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(be(this.sourceBuffer),Bt(this.sourceBuffer.buffered,e.segment.time.from,100)&&Bt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Nt.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",_l(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");be(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=yl(()=>(0,my.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return R(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?dr(this.destroyAbortController.signal,function(){return re(this,null,function*(){let o=Fl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ia(e.mime),i)).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 h=c;this.isLive&&Ce(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),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:Nt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return R(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return R(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||Ue(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(P({},u.time)),i=n(i);let l=_l(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,bn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||Ue(e)?0:nt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={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){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){be(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=yl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Nt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Ue(this.sourceBuffer)||Ue(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Pa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var fy=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Aa,assertNever as gy,fromEvent as vy,merge as lC,now as wa,Subscription as cC,ValueSubject as ql,flattenObject as ri}from"@vkontakte/videoplayer-shared/es2015";var by=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var vn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new ql(void 0);this.lastConnectionReused$=new ql(void 0);this.lastRequestFirstBytes$=new ql(void 0);this.abortAllController=new Me;this.subscription=new cC;this.fetchManifest=Aa(this.abortAllController.signal,function(e){return re(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Pa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=by(r));let i=yield mt(r,{signal:this.abortAllController.signal}).catch(ka);return i?(t.log("success",ri({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ri({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Aa(this.abortAllController.signal,function(l){return re(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var $,j;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");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:gy(t)}this.requestQuic&&(c=Pa(c));let p=this.abortAllController.signal,m;if(n){let L=new Me;if(m=lC(vy(this.abortAllController.signal,"abort"),vy(n,"abort")).subscribe(()=>{try{L.abort()}catch(Y){ka(Y)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(Y){ka(Y)}p=L.signal}let b=wa();h.log("startRequest",ri({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield mt(c,{priority:s,headers:d,signal:p}).catch(ka),S=wa();if(!g)return h.error("error",{message:"No response in request"}),h.end(),m==null||m.unsubscribe(),null;if(($=this.throughputEstimator)==null||$.addRawRtt(S-b),!g.ok||!g.body){m==null||m.unsubscribe();let L=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:L}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){m==null||m.unsubscribe();let L=wa(),Y={requestStartedAt:b,requestEndedAt:L,duration:L-b};return h.log("endRequest",ri(Y)),h.end(),g.arrayBuffer()}let[v,T]=g.body.tee(),I=v.getReader();o&&((j=this.throughputEstimator)==null||j.trackStream(T,u));let E=0,w=new Uint8Array(0),U=!1,B=L=>{m==null||m.unsubscribe(),U=!0,ka(L)},H=Aa(p,function(y){return re(this,arguments,function*({done:L,value:Y}){if(E===0&&this.lastRequestFirstBytes$.next(wa()-b),p.aborted){m==null||m.unsubscribe();return}if(!L&&Y){let k=new Uint8Array(w.length+Y.length);k.set(w),k.set(Y,w.length),w=k,E+=Y.byteLength,i==null||i(new DataView(w.buffer),E),yield I==null?void 0:I.read().then(H,B)}})}.bind(this));yield I==null?void 0:I.read().then(H,B),m==null||m.unsubscribe();let O=wa(),_={failed:U,requestStartedAt:b,requestEndedAt:O,duration:O-b};return U?(h.error("endRequest",ri(_)),h.end(),null):(h.log("endRequest",ri(_)),h.end(),w.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Aa(this.abortAllController.signal,function(e,t,r){return re(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,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,i),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 h=new DataView(d,i-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let v=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,p,m);return{init:p,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Aa(this.abortAllController.signal,function(e,t){return re(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>M(P({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=fy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return R(this,null,function*(){var s,n;let{type:i}=e;switch(i){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:gy(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},ka=a=>{if(!Ea(a))throw a};var pr=(a,e,t)=>t*e+(1-t)*a,Ul=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Sy=(a,e,t,r)=>{let i=0,s=t,n=Ul(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as dC,ValueSubject as yy}from"@vkontakte/videoplayer-shared/es2015";var Ft=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new yy(e.initial),this.debounced$=new yy(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new fe(`raw_${t}`),this.smoothedSeries$=new fe(`smoothed_${t}`),this.reportedSeries$=new fe(`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+=et(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;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)&&(dC(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 Sn=class extends Ft{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=pr(this.slow,e,this.params.emaAlphaSlow),this.fast=pr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var yn=class extends Ft{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ul(this.pastMeasures,this.takenMeasures);this.emaSmoothed=pr(this.emaSmoothed,e,this.params.emaAlpha);let r=Sy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Tn=class extends Ft{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?pr(this.smoothed,t,this.params.emaAlpha):t}};var hr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Sn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new yn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Tn(P({initial:e,label:"liveEdgeDelay"},t))}};var Hl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as pC,ValueSubject as hC}from"@vkontakte/videoplayer-shared/es2015";var Ra=class a{constructor(e,t){this.currentRepresentation$=new hC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!pC(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(M(P({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ce(t.segmentReference))}};var TC=["timeupdate","progress","play","seeked","stalled","waiting"],IC=["timeupdate","progress","loadeddata","playing","seeked"];var En=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new xy;this.representationSubscription=new xy;this.state$=new C("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Ey;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.liveDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.isLowLatency$=new ee(!1);this.isActiveLowLatency$=new ee(!1);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Ey;this.gapWatchdogActive=!1;this.destroyController=new Me;this.initManifest=jl(this.destroyController.signal,function(e,t,r){return re(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=pe(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:qt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=jl(this.destroyController.signal,function(){return re(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:qt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=ly(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=aS(e))!=null?n:{id:"ManifestParsing",category:qt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,h,p,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=ft())==null?void 0:p.isTypeSupported)!=null&&m.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:m})=>r(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=Vv(d);if(h&&(i[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);bC.isHDR&&p&&m?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=M(P({},t),{streams:i});return this.tracer.log("updateManifestEnd",La(s)),s})}.bind(this));this.initRepresentations=jl(this.destroyController.signal,function(e,t,r){return re(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",La({initialVideo:e,initialAudio:t,sourceHls:r})),mr(this.manifest),mr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(fr(p,"error").pipe(In(m=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:qt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Sv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&rn())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new xa("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Iy(t)){let p=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.representations],[]);this.audioBufferManager=new xa("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ra.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ra(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Gl(1e3).subscribe(p=>{var m;if((m=this.element)!=null&&m.paused){let b=Hs(this.manifestUrlString,2);this.manifestUrlString=pe(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(br(...IC.map(p=>fr(this.element,p))).pipe(Ma(p=>this.element?nt(this.element.buffered,this.element.currentTime*1e3):0),Ql(),SC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(br(fr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Ql()).subscribe(m=>Hl(this.element,1))),this.representationSubscription.add($a({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(In(({bufferLength:m,isActiveLowLatency:b})=>b&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add($a({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(In(({isLive:m})=>m),Ma(m=>P({},m)),Ql((m,b)=>b.bufferLength<m.bufferLength),Ma(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let S=Hs(this.manifestUrlString,2);return(m/2+b+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add($a({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:m,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=m-g,I=1;Math.abs(T)>S&&(I=1+Math.sign(T)*v),Hl(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var g,S;let b=0;if(m){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;b=Math.min(...this.bufferManagers.map(I=>{var E,w;return(w=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?w:v}))-v}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add($a({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(yC(1e3)).subscribe(g=>R(this,[g],function*({liveLoadBufferLength:m,bufferLength:b}){if(mr(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,v=Hs(this.manifestUrlString,2),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,w=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,U=isFinite(m)?m:b,B=this.isActiveLowLatency$.getValue(),H=T<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(B&&H);let O="none";if(B?O="active_low_latency":this.isLowLatency$.getValue()&&H?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(_=>_.proceedLowLatencyLive()),O="active_low_latency"):v!==0&&U<I?O="live_forward_buffering":U<I+w&&(O="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),O==="live_forward_buffering"||O==="live_with_target_offset"){let _=p-(I+E),$=this.normolizeLiveOffset(Math.trunc(v+_/S)),j=Math.abs($-v),L;!m||j<=this.tuning.dashCmafLive.offsetCalculationError?L=v:$>0&&j>this.tuning.dashCmafLive.offsetCalculationError?L=$:L=0,this.manifestUrlString=pe(this.manifestUrlString,L,2)}O!=="none"&&O!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=br(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Ma(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=br(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Ma(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(br(this.forceEnded$,$a({allBuffersFull:l,someBufferEnded:c}).pipe(In(({allBuffersFull:p,someBufferEnded:m})=>p&&m))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(p=this.source)==null||p.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:qt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add(br(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var m;return(m=this.source)==null?void 0:m.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...(0,Wl.default)((0,Wl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let m=[];return p.duration&&m.push(p.duration),Ce(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&m.push(p.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&Iy(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Gl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:qt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new vn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=hr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,P({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return R(this,null,function*(){var r,i,s;mr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=pe(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){mr(this.element),this.state$.setState("running"),this.subscription.add(br(...TC.map(e=>fr(this.element,e)),fr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:qt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(fr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(fr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Bt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,m,b,g,S,v,T,I,E,w;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=vC(),n=100,o=(m=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(v=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?v:0,c=(I=(T=this.audioBufferManager)==null?void 0:T.getForwardBufferDuration())!=null?I:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let U=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(U),(w=this.audioBufferManager)==null||w.maintain(U),i.position=U}this.tracer.log("stallIntervalCallback",La(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Gl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:qt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return R(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u;mr(this.element),mr(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((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Bt(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,this.tracer.log("seek",La({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=gC(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return R(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=M(P({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",La(t)))}}};var xn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Pn=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/et(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 i=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:i,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=P({},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 i=-this.fadeCorrection*et(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>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 Py=`attribute vec2 a_vertex;
69
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var ry=a=>{if(!a.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(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},gt=(a,e)=>{let t=a;t=(0,Rl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,iy.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Rl.default)(t,n,(o,u)=>ty(s)?o:ty(u)?s:(0,ay.default)(s,parseInt(u,10),"0"))}return t},ny=(a,e)=>{var E,$,D,z,N,O,q,R,j,L,W,w,T,_,V,ie,Oe,yt,vr,H,le,ce,Ve,Tt,Sr,It,Qt,yr,ni,cc,dc,pc,hc,fc,mc,bc,gc,vc,Sc,yc,Tc,Ic,Ec,xc,Pc,Ac,wc,kc,Rc,$c,Lc,Mc,Cc,Dc,Oc,Vc,Bc,_c,Nc,Fc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=s.getElementsByTagName("Period")[0],o=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(de=>{var Wa,Et;return(Et=(Wa=de.textContent)==null?void 0:Wa.trim())!=null?Et:""}),u=(E=(0,sy.default)(o,0))!=null?E:"",l=n.children,c=s.getAttribute("type")==="dynamic",d=s.getAttribute("availabilityStartTime"),h=d?new Date(d).getTime():void 0,p,f=s.getAttribute("mediaPresentationDuration"),b=n.getAttribute("duration"),g=s.getElementsByTagName("vk:Attrs")[0],S=g==null?void 0:g.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(f)p=ry(f);else if(b){let de=ry(b);ey(de)&&(p=de)}else S&&(p=parseInt(S,10));let v=0,y=(D=($=s.getAttribute("profiles"))==null?void 0:$.split(","))!=null?D:[];for(let de of l){let Wa=(z=de.getAttribute("id"))!=null?z:"id"+(v++).toString(10),Et=(N=de.getAttribute("mimeType"))!=null?N:"",Fn=(O=de.getAttribute("codecs"))!=null?O:"",qn=(q=de.getAttribute("contentType"))!=null?q:Et==null?void 0:Et.split("/")[0],wT=(j=(R=de.getAttribute("profiles"))==null?void 0:R.split(","))!=null?j:[],qc=(W=ZS((L=de.getAttribute("lang"))!=null?L:""))!=null?W:{},kT=(_=(T=(w=de.querySelector("Label"))==null?void 0:w.textContent)==null?void 0:T.trim())!=null?_:void 0,RT=de.querySelectorAll("Representation"),$T=de.querySelector("SegmentTemplate"),LT=(ie=(V=de.querySelector("Role"))==null?void 0:V.getAttribute("value"))!=null?ie:void 0,oi=qn,ae={id:Wa,language:qc.language,isDefault:LT==="main",label:kT,codecs:Fn,hdr:oi==="video"&&kl(Fn),mime:Et,representations:[]};for(let K of RT){let MT=(Oe=K.getAttribute("lang"))!=null?Oe:void 0,CT=(yt=K.getAttribute("label"))!=null?yt:void 0,DT=(le=(H=(vr=K.querySelector("BaseURL"))==null?void 0:vr.textContent)==null?void 0:H.trim())!=null?le:"",Ya=new URL(DT||u,e).toString(),Tr=(ce=K.getAttribute("mimeType"))!=null?ce:Et,za=(Tt=(Ve=K.getAttribute("codecs"))!=null?Ve:Fn)!=null?Tt:"",Ka;if(qn==="text"){let xt=K.getAttribute("id")||"",Ja=((Sr=qc.privateuse)==null?void 0:Sr.includes("x-auto"))||xt.includes("_auto"),Wt=K.querySelector("SegmentTemplate");if(Wt){let ui={representationId:(It=K.getAttribute("id"))!=null?It:void 0,bandwidth:(Qt=K.getAttribute("bandwidth"))!=null?Qt:void 0},Xa=parseInt((yr=K.getAttribute("bandwidth"))!=null?yr:"",10)/1e3,Za=(cc=parseInt((ni=Wt.getAttribute("startNumber"))!=null?ni:"",10))!=null?cc:1,Ir=parseInt((dc=Wt.getAttribute("timescale"))!=null?dc:"",10),Un=(pc=Wt.querySelectorAll("SegmentTimeline S"))!=null?pc:[],Er=Wt.getAttribute("media");if(!Er)continue;let es=[],ts=0,rs="",xr=0,li=Za,me=0;for(let je of Un){let Yt=parseInt((hc=je.getAttribute("d"))!=null?hc:"",10),Be=parseInt((fc=je.getAttribute("r"))!=null?fc:"",10)||0,Pt=parseInt((mc=je.getAttribute("t"))!=null?mc:"",10);me=Number.isFinite(Pt)?Pt:me;let zt=Yt/Ir*1e3,At=me/Ir*1e3;for(let Xe=0;Xe<Be+1;Xe++){let wt=gt(Er,M(P({},ui),{segmentNumber:li.toString(10),segmentTime:(me+Xe*Yt).toString(10)})),Pr=(At!=null?At:0)+Xe*zt,di=Pr+zt;li++,es.push({time:{from:Pr,to:di},url:wt})}me+=(Be+1)*Yt,ts+=(Be+1)*zt}xr=me/Ir*1e3,rs=gt(Er,M(P({},ui),{segmentNumber:li.toString(10),segmentTime:me.toString(10)}));let ci={time:{from:xr,to:1/0},url:rs},ut={type:"template",baseUrl:Ya,segmentTemplateUrl:Er,initUrl:"",totalSegmentsDurationMs:ts,segments:es,nextSegmentBeyondManifest:ci,timescale:Ir};Ka={id:xt,kind:"text",segmentReference:ut,profiles:[],duration:p,bitrate:Xa,mime:"",codecs:"",width:0,height:0,isAuto:Ja}}else Ka={id:xt,isAuto:Ja,kind:"text",url:Ya}}else{let xt=(gc=(bc=K.getAttribute("contentType"))!=null?bc:Tr==null?void 0:Tr.split("/")[0])!=null?gc:qn,Ja=(Sc=(vc=de.getAttribute("profiles"))==null?void 0:vc.split(","))!=null?Sc:[],Wt=parseInt((yc=K.getAttribute("width"))!=null?yc:"",10),ui=parseInt((Tc=K.getAttribute("height"))!=null?Tc:"",10),Xa=parseInt((Ic=K.getAttribute("bandwidth"))!=null?Ic:"",10)/1e3,Za=(Ec=K.getAttribute("frameRate"))!=null?Ec:"",Ir=(xc=K.getAttribute("quality"))!=null?xc:void 0,Un=Za?XS(Za):void 0,Er=(Pc=K.getAttribute("id"))!=null?Pc:"id"+(v++).toString(10),es=xt==="video"?`${ui}p`:xt==="audio"?`${Xa}Kbps`:za,ts=`${Er}@${es}`,rs=[...y,...wT,...Ja],xr,li=K.querySelector("SegmentBase"),me=(Ac=K.querySelector("SegmentTemplate"))!=null?Ac:$T;if(li){let ut=(kc=(wc=K.querySelector("SegmentBase Initialization"))==null?void 0:wc.getAttribute("range"))!=null?kc:"",[je,Yt]=ut.split("-").map(wt=>parseInt(wt,10)),Be={from:je,to:Yt},Pt=(Rc=K.querySelector("SegmentBase"))==null?void 0:Rc.getAttribute("indexRange"),[zt,At]=Pt?Pt.split("-").map(wt=>parseInt(wt,10)):[],Xe=Pt?{from:zt,to:At}:void 0;xr={type:"byteRange",url:Ya,initRange:Be,indexRange:Xe}}else if(me){let ut={representationId:($c=K.getAttribute("id"))!=null?$c:void 0,bandwidth:(Lc=K.getAttribute("bandwidth"))!=null?Lc:void 0},je=parseInt((Mc=me.getAttribute("timescale"))!=null?Mc:"",10),Yt=(Cc=me.getAttribute("initialization"))!=null?Cc:"",Be=me.getAttribute("media"),Pt=(Oc=parseInt((Dc=me.getAttribute("startNumber"))!=null?Dc:"",10))!=null?Oc:1,zt=gt(Yt,ut);if(!Be)throw new ReferenceError("No media attribute in SegmentTemplate");let At=(Vc=me.querySelectorAll("SegmentTimeline S"))!=null?Vc:[],Xe=[],wt=0,Pr="",di=0;if(At.length){let is=Pt,Ge=0;for(let Ar of At){let Ze=parseInt((Bc=Ar.getAttribute("d"))!=null?Bc:"",10),Kt=parseInt((_c=Ar.getAttribute("r"))!=null?_c:"",10)||0,as=parseInt((Nc=Ar.getAttribute("t"))!=null?Nc:"",10);Ge=Number.isFinite(as)?as:Ge;let Hn=Ze/je*1e3,jn=Ge/je*1e3;for(let ss=0;ss<Kt+1;ss++){let VT=gt(Be,M(P({},ut),{segmentNumber:is.toString(10),segmentTime:(Ge+ss*Ze).toString(10)})),Uc=(jn!=null?jn:0)+ss*Hn,BT=Uc+Hn;is++,Xe.push({time:{from:Uc,to:BT},url:VT})}Ge+=(Kt+1)*Ze,wt+=(Kt+1)*Hn}di=Ge/je*1e3,Pr=gt(Be,M(P({},ut),{segmentNumber:is.toString(10),segmentTime:Ge.toString(10)}))}else if(ey(p)){let Ge=parseInt((Fc=me.getAttribute("duration"))!=null?Fc:"",10)/je*1e3,Ar=Math.ceil(p/Ge),Ze=0;for(let Kt=1;Kt<Ar;Kt++){let as=gt(Be,M(P({},ut),{segmentNumber:Kt.toString(10),segmentTime:Ze.toString(10)}));Xe.push({time:{from:Ze,to:Ze+Ge},url:as}),Ze+=Ge}di=Ze,Pr=gt(Be,M(P({},ut),{segmentNumber:Ar.toString(10),segmentTime:Ze.toString(10)}))}let OT={time:{from:di,to:1/0},url:Pr};xr={type:"template",baseUrl:Ya,segmentTemplateUrl:Be,initUrl:zt,totalSegmentsDurationMs:wt,segments:Xe,nextSegmentBeyondManifest:OT,timescale:je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!xt||!Tr)continue;let ci={video:"video",audio:"audio",text:"text"}[xt];if(!ci)continue;oi||(oi=ci),Ka={id:ts,kind:ci,segmentReference:xr,profiles:rs,duration:p,bitrate:Xa,mime:Tr,codecs:za,width:Wt,height:ui,fps:Un,quality:Ir}}ae.language||(ae.language=MT),ae.label||(ae.label=CT),ae.mime||(ae.mime=Tr),ae.codecs||(ae.codecs=za),ae.hdr||(ae.hdr=oi==="video"&&kl(za)),ae.representations.push(Ka)}oi&&i[oi].push(ae)}return{dynamic:c,liveAvailabilityStartTime:h,duration:p,streams:i,baseUrls:o}};var Ml=F(Yr(),1);import{videoSizeToQuality as rC}from"@vkontakte/videoplayer-shared/es2015";var oy=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Ot(s):void 0)!=null?u:rC({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},uy=({id:a,bitrate:e})=>({id:a,bitrate:e}),ly=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),cy=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Cl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Ml.default)(r.split("."),0),isDefault:i}),Dl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Ml.default)(i.split("."),0)}),Ol=a=>"url"in a,Ce=a=>a.type==="template",Ia=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Ea=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new ti(0);this.currentSegmentLength$=new ti(0);this.onLastSegment$=new ti(!1);this.fullyBuffered$=new ti(!1);this.playingRepresentation$=new ti(void 0);this.playingRepresentationInit$=new ti(void 0);this.error$=new aC;this.gaps=[];this.subscription=new sC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new Me;this.switchAbortController=new Me;this.destroyAbortController=new Me;this.bufferLimit=1/0;this.failedDownloads=0;this.baseUrls=[];this.baseUrlsIndex=0;this.isLive=!1;this.liveUpdateSegmentIndex=0;this.liveInitialAdditionalOffset=0;this.isSeekingLive=!1;this.index=0;this.lastDataObtainedTimestampMs=0;this.loadByteRangeSegmentsTimeoutId=0;this.startWith=dr(this.destroyAbortController.signal,function(e){return re(this,null,function*(){let t=this.representations.get(e);ge(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new oS(this.sourceBuffer),this.subscription.add(Vl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ft.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Vl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ft.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o)return;let u=Math.min(this.bufferLimit,yl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=nt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);ge(r,"No init buffer for starting representation"),ge(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchToOld=dr(this.destroyAbortController.signal,function(e,t=!1){return re(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);ge(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(He(s)||He(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),ge(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer))if(this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();pn(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Wn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=dr(this.destroyAbortController.signal,function(e){return re(this,null,function*(){var u,l;let t=(u=(0,mn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!Ce(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);ge(i);let s=this.segments.get(r);ge(s,"No segments for starting representation");let n=this.initData.get(r);if(ge(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new Me,dr(this.switchAbortController.signal,function(r,i=!1){return re(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);ge(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(He(o)||He(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),ge(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer)){if(this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();pn(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}abort(){for(let e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Me,this.abortBuffer()}maintain(e=this.getCurrentPosition()){var l,c;if(He(e)||He(this.downloadingRepresentationId)||He(this.playingRepresentationId)||He(this.sourceBuffer)||pn(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(ge(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(d=>e>=d.time.from&&e<d.time.to);this.currentSegmentLength$.next(((l=i==null?void 0:i.time.to)!=null?l:0)-((c=i==null?void 0:i.time.from)!=null?c:0));let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let h=nt(this.sourceBuffer.buffered,e),p=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&h>=i.time.to-e+100&&(s=p)}if(isFinite(this.bufferLimit)&&yl(this.sourceBuffer.buffered)>=this.bufferLimit){let d=nt(this.sourceBuffer.buffered,e),h=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<h);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&&i)if((0,fn.default)(o,i))d="high";else{let h=(0,ri.default)(o,0);h&&h.time.from-i.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&nt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ri.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=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+i}),r=s.time.to;pn(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,i=[],s=0,n=t.length-1;do i.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()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,mn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,mn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];for(let o of t){if(!o||!Ce(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>M(P({},h),{status:"none",size:void 0})),l=(i=this.segments.get(o.id))!=null?i:[],c=(n=(s=(0,ri.default)(l,-1))==null?void 0:s.time.to)!=null?n:0,d=u==null?void 0:u.findIndex(h=>Math.floor(c)>=Math.floor(h.time.from)&&Math.floor(c)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(d+1);this.segments.set(o.id,[...l,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;ge(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var t;for(let r of this.representations.values()){let i=r.segmentReference;if(!Ce(i))return;let s=(t=this.segments.get(r.id))!=null?t:[],n=s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.from));if(n&&!isFinite(n.time.to)&&(n.time.to=e.time.to),!!!s.find(u=>Math.floor(u.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let u=Math.round(e.time.to*i.timescale/1e3).toString(10),l=gt(i.segmentTemplateUrl,{segmentTime:u});s.push({status:"none",time:{from:e.time.to,to:1/0},url:l})}}}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 i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.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&&Xi&&Xi(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&Xi&&Xi(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.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:h,to:p}},f)=>{let b=h<=r&&p>=r,g=h>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&h<=r+S||p<=r+S;return(d==="none"||d==="partially_ejected"&&g&&v&&this.sourceBuffer&&!(_t(this.sourceBuffer.buffered,h)&&_t(this.sourceBuffer.buffered,p)))&&g&&v});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+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=i;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,r="auto"){return k(this,null,function*(){Ce(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return k(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield dr(o,function(){return re(this,null,function*(){let c=Bl(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(this.lastDataObtainedTimestampMs=hn(),!c)return;let d=new DataView(c),h=Ta(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=h.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:f}=h.getServerLatencyTimestamps(d);p&&f&&this.currentLiveSegmentServerLatency$.next(f-p),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ia(c)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}updateRepresentationsBaseUrlIfNeeded(){if(!this.tuning.dash.enableBaseUrlSupport||!this.baseUrls.length||this.failedDownloads<=this.tuning.dash.maxSegmentRetryCount)return;this.baseUrlsIndex=(this.baseUrlsIndex+1)%this.baseUrls.length;let e=this.baseUrls[this.baseUrlsIndex];for(let t of this.representations.values())Ce(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return k(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:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield dr(n,function(){return re(this,null,function*(){let u=Bl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Vl(window,"online").pipe(iC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=hn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ia(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Ce(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ri.default)(e,0).byte.from,to:(0,ri.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=hn(),this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ce(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=hn();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:Ft.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,fn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return k(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=Ta(o.mime).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(o){return k(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){n();continue}let d=c.byte.from-r,h=c.byte.to-r,p=h-d+1,f=d<i,b=h<=i;if(!f)continue;let g=Ta(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,p);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(p,i-d),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===p?S:g.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(c.status="partially_fed",l.feedingBytes+=v.byteLength,(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?(l.fedBytes+=v.byteLength,l.fedBytes===p&&this.onSegmentFullyAppended(l,t)):n())}}})}onSegmentFullyAppended(e,t){var r;this.tuning.useSafariEndlessRequestBugfix&&!this.isLive&&(ge(this.sourceBuffer),_t(this.sourceBuffer.buffered,e.segment.time.from,100)&&_t(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"SafariEmptyAppendBuffer",category:Ft.VIDEO_PIPELINE,message:"Safari stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Ol(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");ge(this.sourceBuffer),this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=gl(()=>(0,dy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return k(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?dr(this.destroyAbortController.signal,function(){return re(this,null,function*(){let o=Bl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ta(e.mime),i)).then(o=>k(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 h=c;this.isLive&&Ce(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),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:Ft.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return k(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return k(this,null,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||He(e)||this.sourceBuffer.updating)return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(P({},u.time)),i=n(i);let l=Ol(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,fn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!this.sourceBuffer.buffered.length||He(e)?0:nt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(this.sourceBuffer)for(let r of t){let i={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){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!this.gapDetectionIdleCallback){ge(this.sourceBuffer);for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=gl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ft.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(He(this.sourceBuffer)||He(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var xa=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var py=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Pa,assertNever as fy,fromEvent as my,merge as nC,now as Aa,Subscription as oC,ValueSubject as _l,flattenObject as ii}from"@vkontakte/videoplayer-shared/es2015";var hy=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var bn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new _l(void 0);this.lastConnectionReused$=new _l(void 0);this.lastRequestFirstBytes$=new _l(void 0);this.abortAllController=new Me;this.subscription=new oC;this.fetchManifest=Pa(this.abortAllController.signal,function(e){return re(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=xa(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=hy(r));let i=yield ft(r,{signal:this.abortAllController.signal}).catch(wa);return i?(t.log("success",ii({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ii({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Pa(this.abortAllController.signal,function(l){return re(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var R,j;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");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:fy(t)}this.requestQuic&&(c=xa(c));let p=this.abortAllController.signal,f;if(n){let L=new Me;if(f=nC(my(this.abortAllController.signal,"abort"),my(n,"abort")).subscribe(()=>{try{L.abort()}catch(W){wa(W)}}),this.abortAllController.signal.aborted||n.aborted)try{L.abort()}catch(W){wa(W)}p=L.signal}let b=Aa();h.log("startRequest",ii({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield ft(c,{priority:s,headers:d,signal:p}).catch(wa),S=Aa();if(!g)return h.error("error",{message:"No response in request"}),h.end(),f==null||f.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(S-b),!g.ok||!g.body){f==null||f.unsubscribe();let L=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:L}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let L=Aa(),W={requestStartedAt:b,requestEndedAt:L,duration:L-b};return h.log("endRequest",ii(W)),h.end(),g.arrayBuffer()}let[v,y]=g.body.tee(),I=v.getReader();o&&((j=this.throughputEstimator)==null||j.trackStream(y,u));let E=0,$=new Uint8Array(0),D=!1,z=L=>{f==null||f.unsubscribe(),D=!0,wa(L)},N=Pa(p,function(w){return re(this,arguments,function*({done:L,value:W}){if(E===0&&this.lastRequestFirstBytes$.next(Aa()-b),p.aborted){f==null||f.unsubscribe();return}if(!L&&W){let T=new Uint8Array($.length+W.length);T.set($),T.set(W,$.length),$=T,E+=W.byteLength,i==null||i(new DataView($.buffer),E),yield I==null?void 0:I.read().then(N,z)}})}.bind(this));yield I==null?void 0:I.read().then(N,z),f==null||f.unsubscribe();let O=Aa(),q={failed:D,requestStartedAt:b,requestEndedAt:O,duration:O-b};return D?(h.error("endRequest",ii(q)),h.end(),null):(h.log("endRequest",ii(q)),h.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Pa(this.abortAllController.signal,function(e,t,r){return re(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,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,i),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 h=new DataView(d,i-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),f=(S=e.indexRange)!=null?S:t.getIndexRange(p);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,p,f);return{init:p,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Pa(this.abortAllController.signal,function(e,t){return re(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>M(P({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=py(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return k(this,null,function*(){var s,n;let{type:i}=e;switch(i){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:fy(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},wa=a=>{if(!Ia(a))throw a};var pr=(a,e,t)=>t*e+(1-t)*a,Nl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,by=(a,e,t,r)=>{let i=0,s=t,n=Nl(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as uC,ValueSubject as gy}from"@vkontakte/videoplayer-shared/es2015";var qt=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 gy(e.initial),this.debounced$=new gy(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new be(`raw_${t}`),this.smoothedSeries$=new be(`smoothed_${t}`),this.reportedSeries$=new be(`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+=et(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;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)&&(uC(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 gn=class extends qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=pr(this.slow,e,this.params.emaAlphaSlow),this.fast=pr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var vn=class extends qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Nl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=pr(this.emaSmoothed,e,this.params.emaAlpha);let r=by(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Sn=class extends qt{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?pr(this.smoothed,t,this.params.emaAlpha):t}};var hr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new gn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new vn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Sn(P({initial:e,label:"liveEdgeDelay"},t))}};var Fl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as lC,ValueSubject as cC}from"@vkontakte/videoplayer-shared/es2015";var ka=class a{constructor(e,t){this.currentRepresentation$=new cC(null);this.maxRepresentations=4;this.representationsCursor=0;this.representations=[];this.currentSegment=null;this.getCurrentPosition=t.getCurrentPosition,this.processStreams(e)}updateLive(e){this.processStreams(e==null?void 0:e.streams.text)}seekLive(e){this.processStreams(e)}maintain(e=this.getCurrentPosition()){var t;if(!lC(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(M(P({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&Ce(t.segmentReference))}};var vC=["timeupdate","progress","play","seeked","stalled","waiting"],SC=["timeupdate","progress","loadeddata","playing","seeked"];var Tn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Ty;this.representationSubscription=new Ty;this.state$=new C("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new yy;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.liveDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.isLowLatency$=new ee(!1);this.isActiveLowLatency$=new ee(!1);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new yy;this.gapWatchdogActive=!1;this.destroyController=new Me;this.initManifest=ql(this.destroyController.signal,function(e,t,r){return re(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=fe(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Ut.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ql(this.destroyController.signal,function(){return re(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Ut.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=ny(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=tS(e))!=null?n:{id:"ManifestParsing",category:Ut.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,h,p,f;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((f=(p=mt())==null?void 0:p.isTypeSupported)!=null&&f.call(p,`${l}; codecs="${c}"`))||u==="text")};t.dynamic&&this.isLive$.getValue()!==t.dynamic&&(this.isLive$.next(t.dynamic),this.liveDuration$.getValue()!==t.duration&&this.liveDuration$.next(-1*((o=t.duration)!=null?o:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==t.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime));let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:f})=>r(u,p,f)),d=new Set(c.map(({codecs:p})=>p)),h=Cv(d);if(h&&(i[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);hC.isHDR&&p&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=M(P({},t),{streams:i});return this.tracer.log("updateManifestEnd",$a(s)),s})}.bind(this));this.initRepresentations=ql(this.destroyController.signal,function(e,t,r){return re(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",$a({initialVideo:e,initialAudio:t,sourceHls:r})),fr(this.manifest),fr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(mr(p,"error").pipe(yn(f=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(f=>{this.error$.next({id:"VideoSource",category:Ut.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:f})}))};this.source=this.tuning.useManagedMediaSource?bv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&en())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,f)=>[...p,...f.representations],[]);if(this.videoBufferManager=new Ea("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Sy(t)){let p=this.manifest.streams.audio.reduce((f,b)=>[...f,...b.representations],[]);this.audioBufferManager=new Ea("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}ka.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new ka(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Hl(1e3).subscribe(p=>{var f;if((f=this.element)!=null&&f.paused){let b=Us(this.manifestUrlString,2);this.manifestUrlString=fe(this.manifestUrlString,b+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(br(...SC.map(p=>mr(this.element,p))).pipe(La(p=>this.element?nt(this.element.buffered,this.element.currentTime*1e3):0),Ul(),bC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(br(mr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Ul()).subscribe(f=>Fl(this.element,1))),this.representationSubscription.add(Ra({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(yn(({bufferLength:f,isActiveLowLatency:b})=>b&&!!f)).subscribe(({bufferLength:f})=>this.liveBuffer.next(f))),this.representationSubscription.add(Ra({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(yn(({isLive:f})=>f),La(f=>P({},f)),Ul((f,b)=>b.bufferLength<f.bufferLength),La(({rtt:f,bufferLength:b,segmentServerLatency:g})=>{let S=Us(this.manifestUrlString,2);return(f/2+b+g+S)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(Ra({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:f,isActiveLowLatency:b})=>{if(!b)return;let g=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,y=f-g,I=1;Math.abs(y)>S&&(I=1+Math.sign(y)*v),Fl(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(f=>{var g,S;let b=0;if(f){let v=((S=(g=this.element)==null?void 0:g.currentTime)!=null?S:0)*1e3;b=Math.min(...this.bufferManagers.map(I=>{var E,$;return($=(E=I.getLiveSegmentsToLoadState(this.manifest))==null?void 0:E.to)!=null?$:v}))-v}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(Ra({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(gC(1e3)).subscribe(g=>k(this,[g],function*({liveLoadBufferLength:f,bufferLength:b}){if(fr(this.element),this.isUpdatingLive)return;let S=this.element.playbackRate,v=Us(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,I=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*S),E=this.tuning.dashCmafLive.normalizedActualBufferOffset*S,$=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*S,D=isFinite(f)?f:b,z=this.isActiveLowLatency$.getValue(),N=y<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(z&&N);let O="none";if(z?O="active_low_latency":this.isLowLatency$.getValue()&&N?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(q=>q.proceedLowLatencyLive()),O="active_low_latency"):v!==0&&D<I?O="live_forward_buffering":D<I+$&&(O="live_with_target_offset"),isFinite(f)&&(p=f>p?f:p),O==="live_forward_buffering"||O==="live_with_target_offset"){let q=p-(I+E),R=this.normolizeLiveOffset(Math.trunc(v+q/S)),j=Math.abs(R-v),L;!f||j<=this.tuning.dashCmafLive.offsetCalculationError?L=v:R>0&&j>this.tuning.dashCmafLive.offsetCalculationError?L=R:L=0,this.manifestUrlString=fe(this.manifestUrlString,L,2)}O!=="none"&&O!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=br(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(La(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=br(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(La(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));this.representationSubscription.add(br(this.forceEnded$,Ra({allBuffersFull:l,someBufferEnded:c}).pipe(yn(({allBuffersFull:p,someBufferEnded:f})=>p&&f))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(f=>!f.updating))try{(p=this.source)==null||p.endOfStream()}catch(f){this.error$.next({id:"EndOfStream",category:Ut.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:f})}})),this.representationSubscription.add(br(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var f;return(f=this.source)==null?void 0:f.addEventListener("sourceopen",p)}));let d=[(h=this.manifest.duration)!=null?h:0,...(0,jl.default)((0,jl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],p=>p.representations),p=>{let f=[];return p.duration&&f.push(p.duration),Ce(p.segmentReference)&&p.segmentReference.totalSegmentsDurationMs&&f.push(p.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...d)/1e3,this.audioBufferManager&&Sy(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Hl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Ut.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new bn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=hr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,P({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return k(this,null,function*(){var r,i,s;fr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=fe(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){fr(this.element),this.state$.setState("running"),this.subscription.add(br(...vC.map(e=>mr(this.element,e)),mr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Ut.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(mr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(mr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&_t(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,f,b,g,S,v,y,I,E,$;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=mC(),n=100,o=(f=(p=this.videoBufferManager)==null?void 0:p.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(v=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?v:0,c=(I=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let D=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(D),($=this.audioBufferManager)==null||$.maintain(D),i.position=D}this.tracer.log("stallIntervalCallback",$a(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Hl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Ut.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return k(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){var i,s,n,o,u;fr(this.element),fr(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((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),_t(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,this.tracer.log("seek",$a({requestedPosition:e,forcePrecise:t,position:r}))}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>i.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=fC(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return k(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=M(P({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",$a(t)))}}};var In=class{constructor(e,t){this.fov=e,this.orientation=t}};var En=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/et(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 i=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:i,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=P({},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 i=-this.fadeCorrection*et(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>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 Iy=`attribute vec2 a_vertex;
70
70
  attribute vec2 a_texel;
71
71
 
72
72
  varying vec2 v_texel;
@@ -77,7 +77,7 @@ void main(void) {
77
77
  // save texel vector to pass to fragment shader
78
78
  v_texel = a_texel;
79
79
  }
80
- `;var Ay=`#ifdef GL_ES
80
+ `;var Ey=`#ifdef GL_ES
81
81
  precision highp float;
82
82
  precision highp int;
83
83
  #else
@@ -120,5 +120,5 @@ void main(void) {
120
120
  // sample using new coordinates
121
121
  gl_FragColor = texture2D(u_texture, tc);
122
122
  }
123
- `;var An=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 i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new xn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Pn(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"),i=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(i,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(Py,this.gl.VERTEX_SHADER),r=this.createShader(Ay,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,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/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,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,h=t+i;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as PC,now as wy,Subscription as AC,filter as wC,combine as ky,ValueSubject as Ry,isNonNullable as kC}from"@vkontakte/videoplayer-shared/es2015";var Yl=class{constructor(){this.isSeeked$=new Ry(!1);this.isBuffering$=new Ry(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new AC}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(ky({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(wC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(ky({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(PC(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=wy(),h=n&&this.currentStallsCount>=n,p=i&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,m=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(h||p||m)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,kC(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=wy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},$y=Yl;import{combine as RC,map as $C,observeElementSize as LC,Subscription as MC,ValueSubject as zl,noop as CC}from"@vkontakte/videoplayer-shared/es2015";var wn=class{constructor(){this.subscription=new MC;this.pipSize$=new zl(void 0);this.videoSize$=new zl(void 0);this.elementSize$=new zl(void 0);this.pictureInPictureWindowRemoveEventListener=CC}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(LC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(RC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe($C(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var gr=class{constructor(e){this.subscription=new qC;this.videoState=new C("stopped");this.textTracksManager=new _e;this.droppedFramesManager=new Xs;this.stallsManager=new $y;this.elementSizeManager=new wn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new qi;this.audioTrackSwitchHistory=new qi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.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(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return VC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new An(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:((i=e.projectionData)==null?void 0:i.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.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=Se(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new En({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Ie(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Kl.WTF,message:`${i} 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:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(Ly(c=>!!c.length),Cy()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Jl(c=>c.to.state!=="none"),Da());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Da()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(Ly(My),Cy()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Jl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(at(this.video,t.isLooped,i)),this.subscription.add(Te(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Be(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Fe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(BC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let m of d.audio){p.push(Vl(m));let b=[];for(let g of m.representations){let S=dy(g);b.push(S),this.audioTracksMap.set(S,{stream:m,representation:g})}this.audioStreamsMap.set(m,b)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(Bl(p));let m=[];for(let b of p.representations){let g=cy(M(P({},b),{streamId:p.id}));g&&(m.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,m)}this.params.output.availableVideoStreams$.next(h);for(let p of d.text)for(let m of p.representations){let b=py(p,m);this.textTracksMap.set(b,{stream:p,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:Kl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(kn(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,NC(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Dy.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,m]=h,b=[...this.videoTracksMap.keys()].find(S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});My(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(p.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(o),m){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,S).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Da()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:p}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===p.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Bl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Da()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===p.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Vl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(Jl(({to:c})=>c==="ready"),Da());this.subscription.add(kn(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(kn(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=kn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,FC(["init"])).pipe(_C(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var w,U,B,H,O,_,$,j,L,Y,y,k,W;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(w=e.videoTrack.getState())==null?void 0:w.id,n=[...this.videoTracksMap.keys()].find(({id:N})=>N===i),o=t.currentVideoTrack$.getValue(),u=((H=(B=e.videoStream.getState())!=null?B:n&&((U=this.videoTracksMap.get(n))==null?void 0:U.stream))!=null?H:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:N})=>N===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=nt(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(O=e.audioStream.getState())!=null?O:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(_=[...this.audioStreamsMap.keys()].find(({id:N})=>N===(m==null?void 0:m.id)))!=null?_:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let N=Ys(n,c,($=this.audioStreamsMap.get(b))!=null?$:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(j=N==null?void 0:N.bitrate)!=null?j:-1/0)}if(o){let N=Ys(o,c,(L=this.audioStreamsMap.get(b))!=null?L:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(Y=N==null?void 0:N.bitrate)!=null?Y:-1/0)}}let S=Vt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),v=r?S!=null?S:n:n!=null?n:S,T=b&&Vg(v,c,(y=this.audioStreamsMap.get(b))!=null?y:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=(k=this.videoTracksMap.get(v))==null?void 0:k.representation,E=T&&((W=this.audioTracksMap.get(T))==null?void 0:W.representation);if(I&&E)return[I,E];if(I&&!E&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Kl.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ye(this.video),this.tracer.end()}};var Oa=class extends gr{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 Oy,interval as UC,map as Vy}from"@vkontakte/videoplayer-shared/es2015";var Va=class extends gr{constructor(e){super(e),this.liveOffset=new pt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(Vy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Oy({interval:UC(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(Oy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Vy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=hy(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=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,i)})}};var _y=V(Us(),1);import{assertNever as Ba,assertNonNullable as By,debounce as HC,ErrorCategory as Rn,filter as jC,isNonNullable as QC,isNullable as GC,map as $n,merge as WC,Observable as YC,observableFrom as zC,Subscription as KC,videoSizeToQuality as JC}from"@vkontakte/videoplayer-shared/es2015";var Ke={};var ii=(a,e)=>new YC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),_a=class{constructor(e){this.subscription=new KC;this.videoState=new C("initializing");this.textTracksManager=new _e;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Ba(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ba(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ba(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ba(e)}break;default:Ba(t)}};this.video=Se(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(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),ye(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Rn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,_y.default)(import("hls.js").then(i=>{e||(Ke.Hls=i.default,Ke.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){By(Ke.Hls,"hls.js not loaded"),this.hls=new Ke.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){By(Ke.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Rn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Ie(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(at(this.video,e.isLooped,r)),this.subscription.add(Te(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Be(this.video,e.playbackRate,i.playbackRateState$,r)),s(Fe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe($n(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ii(this.hls,Ke.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Rn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},r)).add(i.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(ii(this.hls,Ke.Events.MANIFEST_PARSED).pipe($n(({levels:l})=>l.reduce((c,d)=>{var v,T;let h=d.name||d.height.toString(10),{width:p,height:m}=d,b=(T=Dt((v=d.attrs.QUALITY)!=null?v:""))!=null?T:JC({width:p,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:g};return this.trackLevels.set(h,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(ii(this.hls,Ke.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ii(this.hls,Ke.Events.LEVEL_LOADING).pipe($n(({url:l})=>oe(l))),t.hostname$),s(ii(this.hls,Ke.Events.FRAG_CHANGED),l=>{var h,p,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Lt(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=ii(this.hls,Ke.Events.LEVEL_SWITCHED).pipe($n(({level:l})=>n(this.hls.levels[l])));o.pipe(jC(QC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Lt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(GC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=WC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,zC(["init"])).pipe(HC(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 Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Rn.DOM,thrown:t})))||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0)}};var Ny="X-Playback-Duration",Xl=a=>R(void 0,null,function*(){var i;let e=yield mt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Ny)?parseInt(e.headers.get(Ny),10):void 0});import{assertNever as i0,combine as a0,debounce as s0,ErrorCategory as Mn,filter as n0,filterChanged as o0,isNonNullable as qy,isNullable as Cn,map as Uy,merge as u0,observableFrom as l0,Subscription as c0,ValueSubject as tc,VideoQuality as d0}from"@vkontakte/videoplayer-shared/es2015";var ec=V(su(),1);import{videoSizeToQuality as XC,getExponentialDelay as ZC}from"@vkontakte/videoplayer-shared/es2015";var e0=a=>{let e=null;if(a.QUALITY&&(e=Dt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=XC({width:t,height:r})}return e!=null?e:null},t0=(a,e)=>{var s,n;let t=a.split(`
124
- `),r=[],i=[];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,ec.default)(l[1].split(",").map(v=>v.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=e0(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[v,T]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));v&&T&&(g={width:v,height:T})}let S=new URL(t[++o],e).toString();p&&r.push({id:h,quality:p,url:S,bandwidth:m,size:g,fps:b})}if(c){let d=(0,ec.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,m=d.NAME;h&&p&&i.push({type:"internal",id:p,label:m,language:p,url:h,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},r0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Zl=0,Fy=(r,...i)=>R(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield mt(a)).text();Zl+=1;try{let{qualityManifests:o,textTracks:u}=t0(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Zl<=t.manifestRetryMaxCount)return yield r0(ZC(Zl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Fy(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Ln=Fy;var Na=class{constructor(e){this.subscription=new c0;this.videoState=new C("stopped");this.textTracksManager=new _e;this.manifests$=new tc([]);this.liveOffset=new pt;this.manifestStartTime$=new tc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=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"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.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"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(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(i==null?void 0:i.to)==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return i0(t)}};var t;this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:d0.INVARIANT,url:this.params.source.url},Ln(pe(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:Mn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Mn.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(oe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new tc((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(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.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&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Mn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Ie(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Te(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),s(Fe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.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(o0(),Uy(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.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&&qy(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(oe(h.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(i.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(a0({startTime:this.manifestStartTime$.pipe(n0(qy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Uy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=u0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,l0(["init"])).pipe(s0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Cn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=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,h]of[[l,"mq"],[c,"lq"]]){let p=String(parseFloat(d||""));h&&d&&i.searchParams.set(h,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=pe(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),Xl(n).then(l=>{var c;if(!Cn(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Cn(d)||!isFinite(d))try{mt(n).then(h=>h.text()).then(h=>{var m;let p=(m=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:m[1];if(p){let b=new URL(p,n).toString();Xl(b).then(g=>{Cn(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Mn.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 p0,debounce as h0,ErrorCategory as rc,fromEvent as ic,isNonNullable as m0,isNullable as f0,map as Hy,merge as jy,observableFrom as Qy,Subscription as b0,ValueSubject as g0,VideoQuality as v0,clientChecker as S0}from"@vkontakte/videoplayer-shared/es2015";var Fa=class{constructor(e){this.subscription=new b0;this.videoState=new C("stopped");this.textTracksManager=new _e;this.manifests$=new g0([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=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"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return p0(t)}};this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:v0.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(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ln(pe(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:rc.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(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.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&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:rc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Ie(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Hy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(at(this.video,t.isLooped,r)),this.subscription.add(Te(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.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(i.loadedMetadata$.subscribe(()=>{var p;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&&m0(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(oe(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Hy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!S0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(jy(ic(o,"addtrack"),ic(o,"removetrack"),ic(o,"change"),Qy(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=jy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Qy(["init"])).pipe(h0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ye(this.video)}prepare(){var s,n;let e=this.selectManifest();if(f0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=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&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:rc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var zy=V(Or(),1),qa=V(Bi(),1);import{assertNever as y0,assertNonNullable as Gy,debounce as T0,ErrorCategory as Wy,isHigher as I0,isHigherOrEqual as E0,isInvariantQuality as Yy,isLowerOrEqual as x0,isNonNullable as P0,merge as A0,observableFrom as w0,Subscription as k0,map as R0}from"@vkontakte/videoplayer-shared/es2015";var Ua=class{constructor(e){this.subscription=new k0;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new _e;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"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime: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"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return y0(e)}};this.params=e,this.video=Se(e.container,e.tuning),this.params.output.element$.next(this.video),(0,zy.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,qa.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:Wy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Ie(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(R0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(at(this.video,t.isLooped,r)),this.subscription.add(Te(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Be(this.video,t.playbackRate,i.playbackRateState$,r)),s(Fe(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.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&&P0(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 h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=A0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,w0(["init"])).pipe(T0(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),ye(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Gy(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Gy(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Pa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wy.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,qa.default)(this.trackUrls).find(d=>!Yy(d.track.quality)&&x0(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&&E0(c.quality,u.quality)&&(t=u),!t){let d=(0,qa.default)(this.trackUrls).filter(p=>!Yy(p.track.quality)&&I0(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,qa.default)(this.trackUrls).map(l=>l.track);t=Vt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as Jy,debounce as C0,merge as Xy,observableFrom as D0,Subscription as O0,map as Zy,ValueSubject as V0,ErrorCategory as sc,VideoQuality as B0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as $0}from"@vkontakte/videoplayer-shared/es2015";var Ky=["stun:videostun.mycdn.me:80"],L0=1e3,M0=3,ac=()=>null,Dn=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=ac;this.externalStopCallback=ac;this.externalErrorCallback=ac;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:Ky}]};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:$0.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),L0)}normalizeOptions(e={}){let t={stunServerList:Ky,maxRetryNumber:M0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ha=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new V0(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"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Jy(e)}};this.subscription=new O0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Se(e.container,e.tuning),this.liveStreamClient=new Dn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ye(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:sc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};Xy(this.videoState.stateChangeStarted$.pipe(Zy(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Zy(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Ie(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Fe(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Te(this.video,t.volume,i.volumeState$,r)).add(i.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 Jy(n.to)}},r)).add(Xy(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,D0(["init"])).pipe(C0(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(oe(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:B0.INVARIANT}),this.video.srcObject=e,x(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:sc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ee(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:sc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var ja=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 Ga,assertNonNullable as Ut,ErrorCategory as On,filter as sT,isNonNullable as nT,isNullable as Q0,map as G0,merge as W0,once as Y0,Subject as Ae,Subscription as oT,ValueSubject as D,flattenObject as uT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as _0,map as eT,Subscription as N0,Subject as F0}from"@vkontakte/videoplayer-shared/es2015";var tT=a=>new _0(e=>{let t=new N0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(eT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(eT(({type:l})=>l!==void 0)),n=new F0,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.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),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as q0,Subscription as U0,combine as H0,filter as iT,once as aT}from"@vkontakte/videoplayer-shared/es2015";function rT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as j0}from"@vkontakte/videoplayer-shared/es2015";var Qa=class Qa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new Me;this.subscriptions=new U0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(iT(s=>!!s.type),aT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){j0.isSafari&&e!=="MPEG"||this.subscriptions.add(H0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(iT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),aT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return R(this,null,function*(){let{volumeMultiplier:t}=this,r=rT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Qa.errorId,category:q0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Qa.errorId} exception`,thrown:e})}};Qa.errorId="VolumeMultiplierManager";var ai=Qa;var z0={chunkDuration:5e3,maxParallelRequests:5},Wa=class{constructor(e){this.current$=new D({type:void 0});this.providerError$=new Ae;this.noAvailableProvidersError$=new Ae;this.volumeMultiplierError$=new Ae;this.providerOutput={position$:new D(0),duration$:new D(1/0),volume$:new D({muted:!1,volume:1}),availableVideoStreams$:new D([]),currentVideoStream$:new D(void 0),availableVideoTracks$:new D([]),currentVideoTrack$:new D(void 0),availableAudioStreams$:new D([]),currentAudioStream$:new D(void 0),availableAudioTracks$:new D([]),currentVideoSegmentLength$:new D(0),currentAudioSegmentLength$:new D(0),isAudioAvailable$:new D(!0),autoVideoTrackLimitingAvailable$:new D(!1),autoVideoTrackLimits$:new D(void 0),currentBuffer$:new D(void 0),isBuffering$:new D(!0),error$:new Ae,warning$:new Ae,willSeekEvent$:new Ae,soundProhibitedEvent$:new Ae,seekedEvent$:new Ae,loopedEvent$:new Ae,endedEvent$:new Ae,firstBytesEvent$:new Ae,loadedMetadataEvent$:new Ae,firstFrameEvent$:new Ae,canplay$:new Ae,isLive$:new D(void 0),isLowLatency$:new D(!1),canChangePlaybackSpeed$:new D(!0),liveTime$:new D(void 0),liveBufferTime$:new D(void 0),liveLatency$:new D(void 0),availableTextTracks$:new D([]),currentTextTrack$:new D(void 0),hostname$:new D(void 0),httpConnectionType$:new D(void 0),httpConnectionReused$:new D(void 0),inPiP$:new D(!1),inFullscreen$:new D(!1),element$:new D(void 0),elementVisible$:new D(!0),availableSources$:new D(void 0),is3DVideo$:new D(!1),playbackState$:new D("")};this.subscription=new oT;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Cv([...Ov(this.params.tuning),...Dv(this.params.tuning)],this.params.tuning).filter(l=>nT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,nc.default)(i,l)),...t.filter(l=>(0,nc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",uT(s)),this.screenFormatsIterator=new ja(s);let n=[...fl(!0),...fl(!1)];this.chromecastFormatsIterator=new ja(n.filter(l=>nT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&ai.isSupported()&&(this.volumeMultiplierManager=new ai(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(Q0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:On.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ga(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Ut(o),new Oa(M(P({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Va(M(P({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ut(o),Jr||!this.params.tuning.useHlsJs?new Fa(M(P({},n),{source:o})):new _a(M(P({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Na(M(P({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Ua(M(P({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Jg(M(P({},n),{source:o,config:M(P({},z0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ut(o),new Ha({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ga(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ut(o),new Vi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,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 Ga(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ga(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 Ga(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);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 M(P({},e),{url:r(e.url)})}return(0,cT.default)((0,lT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new oT,t=!1,r=0;return e.add(W0(this.providerOutput.error$.pipe(sT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),tT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(G0(i=>({id:`ProviderHangup:${i}`,category:On.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(sT(({to:s})=>s==="playing"),Y0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===On.NETWORK,u=i.category===On.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=M(P({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",uT(n))})),e}};import{fromEvent as Vn,once as K0,combine as J0,Subscription as dT,ValueSubject as oc,map as X0,filter as Z0,isNonNullable as Bn,now as De,safeStorage as uc}from"@vkontakte/videoplayer-shared/es2015";var eD=5e3,pT="one_video_throughput",hT="one_video_rtt",vt=window.navigator.connection,mT=()=>{let a=vt==null?void 0:vt.downlink;if(Bn(a)&&a!==10)return a*1e3},fT=()=>{let a=vt==null?void 0:vt.rtt;if(Bn(a)&&a!==3e3)return a},bT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},lc=class a{constructor(e){this.subscription=new dT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(pT)||(e.useBrowserEstimation?mT():void 0)||eD,r=(s=(i=a.load(hT))!=null?i:e.useBrowserEstimation?fT():void 0)!=null?s:0;if(this.throughput$=new oc(t),this.rtt$=new oc(r),this.rttAdjustedThroughput$=new oc(bT(t,r,e.rttPenaltyRequestSize)),this.throughput=hr.getSmoothedValue(t,-1,e),this.rtt=hr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=mT();u&&this.throughput.next(u);let l=fT();Bn(l)&&this.rtt.next(l)};vt&&"onchange"in vt&&this.subscription.add(Vn(vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{uc.set(pT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{uc.set(hT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(J0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(X0(({throughput:n,rtt:o})=>bT(n,o,e.rttPenaltyRequestSize)),Z0(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=De(),i=new dT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Vn(e,"progress").pipe(K0()).subscribe(s=>{t=s.loaded,r=De()}));break;case 1:case 0:i.add(Vn(e,"loadstart").subscribe(()=>{t=0,r=De()}));break}i.add(Vn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=De(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=De(),n=0,o=De(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>R(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,De()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=De();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=De()}else n+=d.byteLength;o=De()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&De()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,De()-o,this.concurrentDownloads.size),n=0,o=De());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,i=!1){if(a.sanityCheck(e,t,i)){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 i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=uc.get(e);if(Bn(t))return(r=parseInt(t,10))!=null?r:void 0}},gT=lc;import{fillWithDefault as tD,VideoQuality as _n}from"@vkontakte/videoplayer-shared/es2015";var vT={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:_n.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:_n.Q_720P,trafficSavingLimit:_n.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:_n.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,exposeInternalsToGlobal:!1},ST=a=>{var e;return M(P({},tD(a,vT)),{configName:[...(e=a.configName)!=null?e:[],...vT.configName]})};import{assertNonNullable as Nn,combine as St,ErrorCategory as Fn,filter as ge,filterChanged as Q,fromEvent as dc,isNonNullable as uD,isNullable as lD,Logger as cD,map as F,mapTo as ET,merge as Ht,now as qn,once as ot,Subject as z,Subscription as xT,tap as PT,ValueSubject as A,isHigher as dD,isInvariantQuality as AT,flattenObject as jt,throttle as pc,getTraceSubscriptionMethod as wT,Tracer as pD,InternalsExposure as hD}from"@vkontakte/videoplayer-shared/es2015";import{merge as rD,map as iD,filter as yT,isNonNullable as aD}from"@vkontakte/videoplayer-shared/es2015";var cc=({seekState:a,position$:e})=>rD(a.stateChangeEnded$.pipe(iD(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),yT(aD)),e.pipe(yT(()=>a.getState().state==="none")));import{assertNonNullable as sD}from"@vkontakte/videoplayer-shared/es2015";var TT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return sD(e,`Wrong container or containerId {${a.container}}`),e};import{filter as nD,once as oD}from"@vkontakte/videoplayer-shared/es2015";var IT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(nD(i=>i.length>0),oD()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Un=class{constructor(e={configName:[]},t=pD.createRootTracer(!1)){this.subscription=new xT;this.logger=new cD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency: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 A("stopped"),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),predefinedQualityLimitType$:new A("unknown"),availableAudioStreams$:new A([]),currentAudioStream$:new A(void 0),availableAudioTracks$:new A([]),isAudioAvailable$:new A(!0),currentPlaybackRate$:new A(1),currentBuffer$:new A({start:0,end:0}),isBuffering$:new A(!0),isStalled$:new A(!1),isEnded$:new A(!1),isLooped$:new A(!1),isLive$:new A(void 0),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),liveLatency$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new z,ready$:new z,started$:new z,playing$:new z,paused$:new z,stopped$:new z,willStart$:new z,willResume$:new z,willPause$:new z,willStop$:new z,willDestruct$:new z,watchCoverageRecord$:new z,watchCoverageLive$:new z,managedError$:new z,fatalError$:new z,ended$:new z,looped$:new z,seeked$:new z,willSeek$:new z,autoplaySoundProhibited$:new z,firstBytes$:new z,loadedMetadata$:new z,firstFrame$:new z,canplay$:new z,log$:new z};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:Ag};if(this.initLogs(),this.tuning=ST(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ms({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new gT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new hD("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,m)=>{let b=typeof m;return(0,kT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Fn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=Yc(i,["container"]);return this.tracer.log("initVideo",jt(r)),this.domContainer=TT(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Wa({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(u=this.internalsExposure)==null||u.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),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(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Gi()?(this.tracer.log("request play from hidden tab"),dc(document,"visibilitychange").pipe(ot()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Nn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ge(r=>r.length>0),ot()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",jt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPredefinedQualityLimits(e){let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection,i;switch(e){case"high_quality":i={min:t,max:void 0};break;case"traffic_saving":i={max:r,min:void 0};break;default:i={max:void 0,min:void 0}}return this.desiredState.autoVideoTrackLimits.startTransitionTo(i),this}setPlaybackRate(e){var r;Nn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",jt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>P({type:"external"},t))),this}selectTextTrack(e){var t;return IT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",P({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.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(lD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return uD(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:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Ht(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(F(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(F(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Gs({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ge(({from:e})=>e==="stopped"),ot()).subscribe(()=>{this.initedAt=qn(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",jt(n)),n.state==="requested"?this.desiredState.seekState.setState(M(P({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Fn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ot()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",jt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(F(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(F(n=>n.destination),Q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(St({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(F(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>AT(u)?1:AT(l)?-1:dD(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(Q()).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$.pipe(Q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Q((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Q()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Q()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Q()).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(F(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(St({hasLiveOffsetByPaused:Ht(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(F(n=>n.to),Q(),F(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(St({atLiveEdge:St({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:cc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(F(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Q(),PT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(F(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(St({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(F(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Q(),PT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(F(n=>n.muted),Q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(F(n=>n.volume),Q()).subscribe(this.info.volume$)).add(cc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Ht(e.providerOutput.endedEvent$.pipe(ET(!0)),e.providerOutput.seekedEvent$.pipe(ET(!1))).pipe(Q()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(F(n=>({id:n?`No${n}`:"NoProviders",category:Fn.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(ot(),F(n=>n!=null?n:qn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ot(),F(()=>qn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ot(),F(()=>qn()-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 A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new A(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ge(({to:n})=>n==="playing"),ot()).subscribe(()=>r.next(!1)));let i=0,s=Ht(e.providerOutput.isBuffering$,t,r).pipe(F(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),Q());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(Ht(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(Ht(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(F(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 xT;this.subscription.add(t),this.subscription.add(e.current$.pipe(Q((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ge(r=>r.length>0),ot()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Vt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Ht(this.desiredState.videoTrack.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(F(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(F(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(F(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;Nn(this.providerContainer),Nn(e),Pg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>xg(r)),this.providerContainer.current$.subscribe(({type:r})=>Fi("provider",r)),e.duration$.subscribe(r=>Fi("duration",r)),e.availableVideoTracks$.pipe(ge(r=>!!r.length),ot()).subscribe(r=>Fi("tracks",r)),this.events.fatalError$.subscribe(new fe("fatalError")),this.events.managedError$.subscribe(new fe("managedError")),e.position$.subscribe(new fe("position")),e.currentVideoTrack$.pipe(F(r=>r==null?void 0:r.quality)).subscribe(new fe("quality")),this.info.currentBuffer$.subscribe(new fe("buffer")),e.isBuffering$.subscribe(new fe("isBuffering"))].forEach(r=>this.subscription.add(r)),Fi("codecs",Mv())}initTracerSubscription(){let e=wT(this.tracer.log.bind(this.tracer)),t=wT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(Q()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(St({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ge(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),Q((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ge(r=>r>0),Q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ge(r=>r>0),Q()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(St({currentBuffer:this.info.currentBuffer$.pipe(ge(r=>r.end>0),Q((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(Q())}).pipe(pc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Q()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Q()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Q()).subscribe(e("canChangePlaybackSpeed"))).add(St({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ge(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),pc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Q(),ge(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Q(),ge(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Q()).subscribe(e("muted"))).add(this.info.volume$.pipe(Q()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Q(),ge(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(St({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ge(({throughputEstimation:r,rtt:i})=>!!r&&!!i),pc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Q(),ge(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>R(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Fn.DOM,message:String(i)})})});this.subscription.add(Ht(dc(document,"visibilitychange"),dc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",jt({quality:t,availableTracks:jt(e),track:jt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as u4,Observable as l4,Subject as c4,ValueSubject as d4,VideoQuality as p4}from"@vkontakte/videoplayer-shared/es2015";var h4=`@vkontakte/videoplayer-core@${zc}`;export{us as ChromecastState,Jn as HttpConnectionType,l4 as Observable,ve as PlaybackState,Un as Player,pi as PredefinedQualityLimits,h4 as SDK_VERSION,c4 as Subject,u4 as Subscription,Xn as Surface,zc as VERSION,d4 as ValueSubject,wt as VideoFormat,p4 as VideoQuality};
123
+ `;var xn=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 i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new In(this.params.fov,this.params.orientation),this.cameraRotationManager=new En(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"),i=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(i,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(Iy,this.gl.VERTEX_SHADER),r=this.createShader(Ey,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,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/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,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,h=t+i;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as IC,now as xy,Subscription as EC,filter as xC,combine as Py,ValueSubject as Ay,isNonNullable as PC}from"@vkontakte/videoplayer-shared/es2015";var Gl=class{constructor(){this.isSeeked$=new Ay(!1);this.isBuffering$=new Ay(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new EC}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(Py({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(xC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Py({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(IC(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=xy(),h=n&&this.currentStallsCount>=n,p=i&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,f=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(h||p||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,PC(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=xy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},wy=Gl;import{combine as AC,map as wC,observeElementSize as kC,Subscription as RC,ValueSubject as Ql,noop as $C}from"@vkontakte/videoplayer-shared/es2015";var Pn=class{constructor(){this.subscription=new RC;this.pipSize$=new Ql(void 0);this.videoSize$=new Ql(void 0);this.elementSize$=new Ql(void 0);this.pictureInPictureWindowRemoveEventListener=$C}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(kC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(AC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(wC(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var gr=class{constructor(e){this.subscription=new _C;this.videoState=new C("stopped");this.textTracksManager=new Ne;this.droppedFramesManager=new Ks;this.stallsManager=new wy;this.elementSizeManager=new Pn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Fi;this.audioTrackSwitchHistory=new Fi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.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(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return CC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new xn(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:((i=e.projectionData)==null?void 0:i.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.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ye(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new Tn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Ee(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Wl.WTF,message:`${i} 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:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(ky(c=>!!c.length),$y()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(Yl(c=>c.to.state!=="none"),Ca());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ca()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(ky(Ry),$y()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(Yl(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(at(this.video,t.isLooped,i)),this.subscription.add(Ie(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(_e(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(qe(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(DC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let p=[];for(let f of d.audio){p.push(Cl(f));let b=[];for(let g of f.representations){let S=uy(g);b.push(S),this.audioTracksMap.set(S,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(p)}let h=[];for(let p of d.video){h.push(Dl(p));let f=[];for(let b of p.representations){let g=oy(M(P({},b),{streamId:p.id}));g&&(f.push(g),this.videoTracksMap.set(g,{stream:p,representation:b}))}this.videoStreamsMap.set(p,f)}this.params.output.availableVideoStreams$.next(h);for(let p of d.text)for(let f of p.representations){let b=ly(p,f);this.textTracksMap.set(b,{stream:p,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:Wl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(An(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,t.videoStream.stateChangeStarted$,t.audioStream.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,VC(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Ly.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let h=this.selectVideoAudioRepresentations();if(!h)return;let[p,f]=h,b=[...this.videoTracksMap.keys()].find(S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===p.id});Ry(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(p.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",p.id).catch(o),f){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,S).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Ca()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(h),e.currentVideoStream$.next(Dl(p))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ca()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[h,{stream:p}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===p.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Cl(p))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,h;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),(h=this.params.tuning.spherical)!=null&&h.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(Yl(({to:c})=>c==="ready"),Ca());this.subscription.add(An(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(An(u,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=An(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,BC(["init"])).pipe(OC(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var $,D,z,N,O,q,R,j,L,W,w,T,_;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=($=e.videoTrack.getState())==null?void 0:$.id,n=[...this.videoTracksMap.keys()].find(({id:V})=>V===i),o=t.currentVideoTrack$.getValue(),u=((N=(z=e.videoStream.getState())!=null?z:n&&((D=this.videoTracksMap.get(n))==null?void 0:D.stream))!=null?N:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:V})=>V===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=nt(this.video.buffered,this.video.currentTime*1e3),h=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(d/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(O=e.audioStream.getState())!=null?O:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(q=[...this.audioStreamsMap.keys()].find(({id:V})=>V===(f==null?void 0:f.id)))!=null?q:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let V=Qs(n,c,(R=this.audioStreamsMap.get(b))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(j=V==null?void 0:V.bitrate)!=null?j:-1/0)}if(o){let V=Qs(o,c,(L=this.audioStreamsMap.get(b))!=null?L:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(W=V==null?void 0:V.bitrate)!=null?W:-1/0)}}let S=Bt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:p,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),v=r?S!=null?S:n:n!=null?n:S,y=b&&Cg(v,c,(w=this.audioStreamsMap.get(b))!=null?w:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:p,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=(T=this.videoTracksMap.get(v))==null?void 0:T.representation,E=y&&((_=this.audioTracksMap.get(y))==null?void 0:_.representation);if(I&&E)return[I,E];if(I&&!E&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Wl.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Te(this.video),this.tracer.end()}};var Da=class extends gr{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 My,interval as NC,map as Cy}from"@vkontakte/videoplayer-shared/es2015";var Oa=class extends gr{constructor(e){super(e),this.liveOffset=new pt,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(Cy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(My({interval:NC(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(My({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Cy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=cy(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=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,i)})}};var Oy=F(qs(),1);import{assertNever as Va,assertNonNullable as Dy,debounce as FC,ErrorCategory as wn,filter as qC,isNonNullable as UC,isNullable as HC,map as kn,merge as jC,Observable as GC,observableFrom as QC,Subscription as WC,videoSizeToQuality as YC}from"@vkontakte/videoplayer-shared/es2015";var Je={};var ai=(a,e)=>new GC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ba=class{constructor(e){this.subscription=new WC;this.videoState=new C("initializing");this.textTracksManager=new Ne;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Va(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Va(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Va(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Va(e)}break;default:Va(t)}};this.video=ye(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(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),Te(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:wn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Oy.default)(import("hls.js").then(i=>{e||(Je.Hls=i.default,Je.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Dy(Je.Hls,"hls.js not loaded"),this.hls=new Je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Dy(Je.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:wn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Ee(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(at(this.video,e.isLooped,r)),this.subscription.add(Ie(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(_e(this.video,e.playbackRate,i.playbackRateState$,r)),s(qe(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(kn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ai(this.hls,Je.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:wn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},r)).add(i.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(ai(this.hls,Je.Events.MANIFEST_PARSED).pipe(kn(({levels:l})=>l.reduce((c,d)=>{var v,y;let h=d.name||d.height.toString(10),{width:p,height:f}=d,b=(y=Ot((v=d.attrs.QUALITY)!=null?v:""))!=null?y:YC({width:p,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:f},fps:g};return this.trackLevels.set(h,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(ai(this.hls,Je.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",f=d.lang;c.push({id:h,url:p,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ai(this.hls,Je.Events.LEVEL_LOADING).pipe(kn(({url:l})=>oe(l))),t.hostname$),s(ai(this.hls,Je.Events.FRAG_CHANGED),l=>{var h,p,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p: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(Mt(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=ai(this.hls,Je.Events.LEVEL_SWITCHED).pipe(kn(({level:l})=>n(this.hls.levels[l])));o.pipe(qC(UC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Mt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(HC(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),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=jC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,QC(["init"])).pipe(FC(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 k(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:wn.DOM,thrown:t})))||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0)}};var Vy="X-Playback-Duration",zl=a=>k(void 0,null,function*(){var i;let e=yield ft(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(Vy)?parseInt(e.headers.get(Vy),10):void 0});import{assertNever as e0,combine as t0,debounce as r0,ErrorCategory as $n,filter as i0,filterChanged as a0,isNonNullable as _y,isNullable as Ln,map as Ny,merge as s0,observableFrom as n0,Subscription as o0,ValueSubject as Xl,VideoQuality as u0}from"@vkontakte/videoplayer-shared/es2015";var Jl=F(ru(),1);import{videoSizeToQuality as zC,getExponentialDelay as KC}from"@vkontakte/videoplayer-shared/es2015";var JC=a=>{let e=null;if(a.QUALITY&&(e=Ot(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=zC({width:t,height:r})}return e!=null?e:null},XC=(a,e)=>{var s,n;let t=a.split(`
124
+ `),r=[],i=[];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,Jl.default)(l[1].split(",").map(v=>v.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=JC(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,g;if(d.RESOLUTION){let[v,y]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));v&&y&&(g={width:v,height:y})}let S=new URL(t[++o],e).toString();p&&r.push({id:h,quality:p,url:S,bandwidth:f,size:g,fps:b})}if(c){let d=(0,Jl.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,f=d.NAME;h&&p&&i.push({type:"internal",id:p,label:f,language:p,url:h,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},ZC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),Kl=0,By=(r,...i)=>k(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield ft(a)).text();Kl+=1;try{let{qualityManifests:o,textTracks:u}=XC(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(Kl<=t.manifestRetryMaxCount)return yield ZC(KC(Kl-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),By(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Rn=By;var _a=class{constructor(e){this.subscription=new o0;this.videoState=new C("stopped");this.textTracksManager=new Ne;this.manifests$=new Xl([]);this.liveOffset=new pt;this.manifestStartTime$=new Xl(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=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"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.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"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(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(i==null?void 0:i.to)==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return e0(t)}};var t;this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:u0.INVARIANT,url:this.params.source.url},Rn(fe(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:$n.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:$n.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(oe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new Xl((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(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.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&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:$n.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),s(qe(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.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(a0(),Ny(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.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&&_y(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(oe(h.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(i.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(t0({startTime:this.manifestStartTime$.pipe(i0(_y)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Ny(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=s0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,n0(["init"])).pipe(r0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Ln(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=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,h]of[[l,"mq"],[c,"lq"]]){let p=String(parseFloat(d||""));h&&d&&i.searchParams.set(h,p)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=fe(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),zl(n).then(l=>{var c;if(!Ln(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Ln(d)||!isFinite(d))try{ft(n).then(h=>h.text()).then(h=>{var f;let p=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:f[1];if(p){let b=new URL(p,n).toString();zl(b).then(g=>{Ln(g)||this.maxSeekBackTime$.next(g)})}})}catch(h){}}})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:$n.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 l0,debounce as c0,ErrorCategory as Zl,fromEvent as ec,isNonNullable as d0,isNullable as p0,map as Fy,merge as qy,observableFrom as Uy,Subscription as h0,ValueSubject as f0,VideoQuality as m0,clientChecker as b0}from"@vkontakte/videoplayer-shared/es2015";var Na=class{constructor(e){this.subscription=new h0;this.videoState=new C("stopped");this.textTracksManager=new Ne;this.manifests$=new f0([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=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"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return l0(t)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:m0.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(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Rn(fe(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:Zl.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(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.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&&!i&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:Zl.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Fy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(at(this.video,t.isLooped,r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.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(i.loadedMetadata$.subscribe(()=>{var p;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&&d0(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===f);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(oe(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Fy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!b0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(qy(ec(o,"addtrack"),ec(o,"removetrack"),ec(o,"change"),Uy(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=qy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Uy(["init"])).pipe(c0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){var s,n;let e=this.selectManifest();if(p0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=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&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Zl.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var Qy=F(Vr(),1),Fa=F(Vi(),1);import{assertNever as g0,assertNonNullable as Hy,debounce as v0,ErrorCategory as jy,isHigher as S0,isHigherOrEqual as y0,isInvariantQuality as Gy,isLowerOrEqual as T0,isNonNullable as I0,merge as E0,observableFrom as x0,Subscription as P0,map as A0}from"@vkontakte/videoplayer-shared/es2015";var qa=class{constructor(e){this.subscription=new P0;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Ne;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"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime: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"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return g0(e)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),(0,Qy.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Fa.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:jy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(A0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(at(this.video,t.isLooped,r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(_e(this.video,t.playbackRate,i.playbackRateState$,r)),s(qe(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.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&&I0(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 h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=E0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,x0(["init"])).pipe(v0(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),Te(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Hy(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Hy(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=xa(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:jy.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Fa.default)(this.trackUrls).find(d=>!Gy(d.track.quality)&&T0(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&&y0(c.quality,u.quality)&&(t=u),!t){let d=(0,Fa.default)(this.trackUrls).filter(p=>!Gy(p.track.quality)&&S0(p.track.quality,e)),h=d.length;h&&(t=d[h-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Fa.default)(this.trackUrls).map(l=>l.track);t=Bt(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as Yy,debounce as $0,merge as zy,observableFrom as L0,Subscription as M0,map as Ky,ValueSubject as C0,ErrorCategory as rc,VideoQuality as D0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as w0}from"@vkontakte/videoplayer-shared/es2015";var Wy=["stun:videostun.mycdn.me:80"],k0=1e3,R0=3,tc=()=>null,Mn=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=tc;this.externalStopCallback=tc;this.externalErrorCallback=tc;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 k(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 k(this,null,function*(){try{let e={iceServers:[{urls:Wy}]};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 k(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return k(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:w0.WTF,message:e.message})}onPeerConnectionStream(e){return k(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 k(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),k0)}normalizeOptions(e={}){let t={stunServerList:Wy,maxRetryNumber:R0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ua=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new C0(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"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return Yy(e)}};this.subscription=new M0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ye(e.container,e.tuning),this.liveStreamClient=new Mn(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Te(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:rc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};zy(this.videoState.stateChangeStarted$.pipe(Ky(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(Ky(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Ee(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(qe(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ie(this.video,t.volume,i.volumeState$,r)).add(i.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 Yy(n.to)}},r)).add(zy(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,L0(["init"])).pipe($0(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(oe(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:D0.INVARIANT}),this.video.srcObject=e,x(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:rc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:rc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ha=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ga,assertNonNullable as Ht,ErrorCategory as Cn,filter as rT,isNonNullable as iT,isNullable as U0,map as H0,merge as j0,once as G0,Subject as we,Subscription as aT,ValueSubject as B,flattenObject as sT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as O0,map as Jy,Subscription as V0,Subject as B0}from"@vkontakte/videoplayer-shared/es2015";var Xy=a=>new O0(e=>{let t=new V0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(Jy(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(Jy(({type:l})=>l!==void 0)),n=new B0,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.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),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as _0,Subscription as N0,combine as F0,filter as eT,once as tT}from"@vkontakte/videoplayer-shared/es2015";function Zy(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as q0}from"@vkontakte/videoplayer-shared/es2015";var ja=class ja{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new Me;this.subscriptions=new N0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(eT(s=>!!s.type),tT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){q0.isSafari&&e!=="MPEG"||this.subscriptions.add(F0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(eT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),tT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return k(this,null,function*(){let{volumeMultiplier:t}=this,r=Zy();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:ja.errorId,category:_0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${ja.errorId} exception`,thrown:e})}};ja.errorId="VolumeMultiplierManager";var si=ja;var Q0={chunkDuration:5e3,maxParallelRequests:5},Qa=class{constructor(e){this.current$=new B({type:void 0});this.providerError$=new we;this.noAvailableProvidersError$=new we;this.volumeMultiplierError$=new we;this.providerOutput={position$:new B(0),duration$:new B(1/0),volume$:new B({muted:!1,volume:1}),availableVideoStreams$:new B([]),currentVideoStream$:new B(void 0),availableVideoTracks$:new B([]),currentVideoTrack$:new B(void 0),availableAudioStreams$:new B([]),currentAudioStream$:new B(void 0),availableAudioTracks$:new B([]),currentVideoSegmentLength$:new B(0),currentAudioSegmentLength$:new B(0),isAudioAvailable$:new B(!0),autoVideoTrackLimitingAvailable$:new B(!1),autoVideoTrackLimits$:new B(void 0),currentBuffer$:new B(void 0),isBuffering$:new B(!0),error$:new we,warning$:new we,willSeekEvent$:new we,soundProhibitedEvent$:new we,seekedEvent$:new we,loopedEvent$:new we,endedEvent$:new we,firstBytesEvent$:new we,loadedMetadataEvent$:new we,firstFrameEvent$:new we,canplay$:new we,isLive$:new B(void 0),isLowLatency$:new B(!1),canChangePlaybackSpeed$:new B(!0),liveTime$:new B(void 0),liveBufferTime$:new B(void 0),liveLatency$:new B(void 0),availableTextTracks$:new B([]),currentTextTrack$:new B(void 0),hostname$:new B(void 0),httpConnectionType$:new B(void 0),httpConnectionReused$:new B(void 0),inPiP$:new B(!1),inFullscreen$:new B(!1),element$:new B(void 0),elementVisible$:new B(!0),availableSources$:new B(void 0),is3DVideo$:new B(!1),playbackState$:new B("")};this.subscription=new aT;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=$v([...Mv(this.params.tuning),...Lv(this.params.tuning)],this.params.tuning).filter(l=>iT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,ic.default)(i,l)),...t.filter(l=>(0,ic.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",sT(s)),this.screenFormatsIterator=new Ha(s);let n=[...pl(!0),...pl(!1)];this.chromecastFormatsIterator=new Ha(n.filter(l=>iT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&si.isSupported()&&(this.volumeMultiplierManager=new si(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(U0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Cn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ga(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Ht(o),new Da(M(P({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ht(o),new Oa(M(P({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Ht(o),Xr||!this.params.tuning.useHlsJs?new Na(M(P({},n),{source:o})):new Ba(M(P({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Ht(o),new _a(M(P({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Ht(o),new qa(M(P({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Ht(o),new Yg(M(P({},n),{source:o,config:M(P({},Q0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Ht(o),new Ua({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ga(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Ht(o),new Oi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,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 Ga(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ga(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 Ga(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);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 M(P({},e),{url:r(e.url)})}return(0,oT.default)((0,nT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new aT,t=!1,r=0;return e.add(j0(this.providerOutput.error$.pipe(rT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),Xy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(H0(i=>({id:`ProviderHangup:${i}`,category:Cn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(rT(({to:s})=>s==="playing"),G0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Cn.NETWORK,u=i.category===Cn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=M(P({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",sT(n))})),e}};import{fromEvent as Dn,once as W0,combine as Y0,Subscription as uT,ValueSubject as ac,map as z0,filter as K0,isNonNullable as On,now as De,safeStorage as sc}from"@vkontakte/videoplayer-shared/es2015";var J0=5e3,lT="one_video_throughput",cT="one_video_rtt",vt=window.navigator.connection,dT=()=>{let a=vt==null?void 0:vt.downlink;if(On(a)&&a!==10)return a*1e3},pT=()=>{let a=vt==null?void 0:vt.rtt;if(On(a)&&a!==3e3)return a},hT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},nc=class a{constructor(e){this.subscription=new uT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(lT)||(e.useBrowserEstimation?dT():void 0)||J0,r=(s=(i=a.load(cT))!=null?i:e.useBrowserEstimation?pT():void 0)!=null?s:0;if(this.throughput$=new ac(t),this.rtt$=new ac(r),this.rttAdjustedThroughput$=new ac(hT(t,r,e.rttPenaltyRequestSize)),this.throughput=hr.getSmoothedValue(t,-1,e),this.rtt=hr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=dT();u&&this.throughput.next(u);let l=pT();On(l)&&this.rtt.next(l)};vt&&"onchange"in vt&&this.subscription.add(Dn(vt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{sc.set(lT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{sc.set(cT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Y0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(z0(({throughput:n,rtt:o})=>hT(n,o,e.rttPenaltyRequestSize)),K0(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=De(),i=new uT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Dn(e,"progress").pipe(W0()).subscribe(s=>{t=s.loaded,r=De()}));break;case 1:case 0:i.add(Dn(e,"loadstart").subscribe(()=>{t=0,r=De()}));break}i.add(Dn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=De(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=De(),n=0,o=De(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>k(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,De()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=De();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=De()}else n+=d.byteLength;o=De()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&De()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,De()-o,this.concurrentDownloads.size),n=0,o=De());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,i=!1){if(a.sanityCheck(e,t,i)){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 i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=sc.get(e);if(On(t))return(r=parseInt(t,10))!=null?r:void 0}},fT=nc;import{fillWithDefault as X0,VideoQuality as mT}from"@vkontakte/videoplayer-shared/es2015";var bT={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:3e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:mT.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:mT.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:0,stallCountBeforeQualityDecrease:0,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,exposeInternalsToGlobal:!1},gT=a=>{var e;return M(P({},X0(a,bT)),{configName:[...(e=a.configName)!=null?e:[],...bT.configName]})};import{assertNonNullable as Vn,combine as St,ErrorCategory as Bn,filter as ve,filterChanged as G,fromEvent as uc,isNonNullable as sD,isNullable as nD,Logger as oD,map as U,mapTo as TT,merge as jt,now as _n,once as ot,Subject as Y,Subscription as IT,tap as ET,ValueSubject as A,isHigher as uD,isInvariantQuality as xT,flattenObject as Gt,throttle as lc,getTraceSubscriptionMethod as PT,Tracer as lD,InternalsExposure as cD}from"@vkontakte/videoplayer-shared/es2015";import{merge as Z0,map as eD,filter as vT,isNonNullable as tD}from"@vkontakte/videoplayer-shared/es2015";var oc=({seekState:a,position$:e})=>Z0(a.stateChangeEnded$.pipe(eD(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),vT(tD)),e.pipe(vT(()=>a.getState().state==="none")));import{assertNonNullable as rD}from"@vkontakte/videoplayer-shared/es2015";var ST=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return rD(e,`Wrong container or containerId {${a.container}}`),e};import{filter as iD,once as aD}from"@vkontakte/videoplayer-shared/es2015";var yT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(iD(i=>i.length>0),aD()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Nn=class{constructor(e={configName:[]},t=lD.createRootTracer(!1)){this.subscription=new IT;this.logger=new oD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new A(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new C("stopped"),seekState:new C({state:"none"}),volume:new C({volume:1,muted:!1}),videoTrack:new C(void 0),videoStream:new C(void 0),audioStream:new C(void 0),autoVideoTrackSwitching:new C(!0),autoVideoTrackLimits:new C({}),isLooped:new C(!1),isLowLatency: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 A("stopped"),position$:new A(0),duration$:new A(1/0),muted$:new A(!1),volume$:new A(1),availableVideoStreams$:new A([]),currentVideoStream$:new A(void 0),availableQualities$:new A([]),availableQualitiesFps$:new A({}),currentQuality$:new A(void 0),isAutoQualityEnabled$:new A(!0),autoQualityLimitingAvailable$:new A(!1),autoQualityLimits$:new A({}),availableAudioStreams$:new A([]),currentAudioStream$:new A(void 0),availableAudioTracks$:new A([]),isAudioAvailable$:new A(!0),currentPlaybackRate$:new A(1),currentBuffer$:new A({start:0,end:0}),isBuffering$:new A(!0),isStalled$:new A(!1),isEnded$:new A(!1),isLooped$:new A(!1),isLive$:new A(void 0),canChangePlaybackSpeed$:new A(void 0),atLiveEdge$:new A(void 0),atLiveDurationEdge$:new A(void 0),liveTime$:new A(void 0),liveBufferTime$:new A(void 0),liveLatency$:new A(void 0),currentFormat$:new A(void 0),availableTextTracks$:new A([]),currentTextTrack$:new A(void 0),throughputEstimation$:new A(void 0),rttEstimation$:new A(void 0),videoBitrate$:new A(void 0),hostname$:new A(void 0),httpConnectionType$:new A(void 0),httpConnectionReused$:new A(void 0),surface$:new A("none"),chromecastState$:new A("NOT_AVAILABLE"),chromecastDeviceName$:new A(void 0),intrinsicVideoSize$:new A(void 0),availableSources$:new A(void 0),is3DVideo$:new A(!1),currentVideoSegmentLength$:new A(0),currentAudioSegmentLength$:new A(0)};this.events={inited$:new Y,ready$:new Y,started$:new Y,playing$:new Y,paused$:new Y,stopped$:new Y,willStart$:new Y,willResume$:new Y,willPause$:new Y,willStop$:new Y,willDestruct$:new Y,watchCoverageRecord$:new Y,watchCoverageLive$:new Y,managedError$:new Y,fatalError$:new Y,ended$:new Y,looped$:new Y,seeked$:new Y,willSeek$:new Y,autoplaySoundProhibited$:new Y,firstBytes$:new Y,loadedMetadata$:new Y,firstFrame$:new Y,canplay$:new Y,log$:new Y};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:Eg};if(this.initLogs(),this.tuning=gT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new hs({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new fT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new cD("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,f)=>{let b=typeof f;return(0,AT.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Bn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=Gc(i,["container"]);return this.tracer.log("initVideo",Gt(r)),this.domContainer=ST(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Qa({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(u=this.internalsExposure)==null||u.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),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(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Gi()?(this.tracer.log("request play from hidden tab"),uc(document,"visibilitychange").pipe(ot()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Vn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ve(r=>r.length>0),ot()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Gt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Vn(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Gt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>P({type:"external"},t))),this}selectTextTrack(e){var t;return yT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",P({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.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(nD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return sD(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:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(jt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ve(({from:e})=>e==="stopped"),ot()).subscribe(()=>{this.initedAt=_n(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case"ready":this.events.ready$.next();break;case"playing":this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case"paused":this.events.paused$.next();break;case"stopped":this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case"paused":this.events.willPause$.next();break;case"playing":this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case"stopped":this.events.willStop$.next();break;default:}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("willSeekEvent",Gt(n)),n.state==="requested"?this.desiredState.seekState.setState(M(P({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Bn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ot()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Gt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(U(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(U(n=>n.destination),G()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(St({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(U(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>xT(u)?1:xT(l)?-1:uD(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(G()).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$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(G()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(G()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(G()).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(U(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(St({hasLiveOffsetByPaused:jt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(n=>n.to),G(),U(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(St({atLiveEdge:St({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:oc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(U(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),G(),ET(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(U(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(St({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(U(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),G(),ET(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(U(n=>n.muted),G()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(U(n=>n.volume),G()).subscribe(this.info.volume$)).add(oc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(jt(e.providerOutput.endedEvent$.pipe(TT(!0)),e.providerOutput.seekedEvent$.pipe(TT(!1))).pipe(G()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(U(n=>({id:n?`No${n}`:"NoProviders",category:Bn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ot(),U(n=>n!=null?n:_n()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ot(),U(()=>_n()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ot(),U(()=>_n()-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 A(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new A(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ve(({to:n})=>n==="playing"),ot()).subscribe(()=>r.next(!1)));let i=0,s=jt(e.providerOutput.isBuffering$,t,r).pipe(U(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),G());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(jt(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(jt(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(U(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 IT;this.subscription.add(t),this.subscription.add(e.current$.pipe(G((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ve(r=>r.length>0),ot()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Bt(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(jt(this.desiredState.videoTrack.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(U(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;Vn(this.providerContainer),Vn(e),Ig(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Tg(r)),this.providerContainer.current$.subscribe(({type:r})=>Ni("provider",r)),e.duration$.subscribe(r=>Ni("duration",r)),e.availableVideoTracks$.pipe(ve(r=>!!r.length),ot()).subscribe(r=>Ni("tracks",r)),this.events.fatalError$.subscribe(new be("fatalError")),this.events.managedError$.subscribe(new be("managedError")),e.position$.subscribe(new be("position")),e.currentVideoTrack$.pipe(U(r=>r==null?void 0:r.quality)).subscribe(new be("quality")),this.info.currentBuffer$.subscribe(new be("buffer")),e.isBuffering$.subscribe(new be("isBuffering"))].forEach(r=>this.subscription.add(r)),Ni("codecs",Rv())}initTracerSubscription(){let e=PT(this.tracer.log.bind(this.tracer)),t=PT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(G()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(St({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ve(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),G((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ve(r=>r>0),G()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ve(r=>r>0),G()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(St({currentBuffer:this.info.currentBuffer$.pipe(ve(r=>r.end>0),G((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(G())}).pipe(lc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(G()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(G()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(G()).subscribe(e("canChangePlaybackSpeed"))).add(St({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ve(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),lc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(G(),ve(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(G(),ve(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(G()).subscribe(e("muted"))).add(this.info.volume$.pipe(G()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(G(),ve(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(St({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ve(({throughputEstimation:r,rtt:i})=>!!r&&!!i),lc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(G(),ve(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>k(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Bn.DOM,message:String(i)})})});this.subscription.add(jt(uc(document,"visibilitychange"),uc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Gt({quality:t,availableTracks:Gt(e),track:Gt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as Jz,Observable as Xz,Subject as Zz,ValueSubject as e4,VideoQuality as t4}from"@vkontakte/videoplayer-shared/es2015";var r4=`@vkontakte/videoplayer-core@${Qc}`;export{os as ChromecastState,Yn as HttpConnectionType,Xz as Observable,Se as PlaybackState,Nn as Player,r4 as SDK_VERSION,Zz as Subject,Jz as Subscription,zn as Surface,Qc as VERSION,e4 as ValueSubject,kt as VideoFormat,t4 as VideoQuality};