@vkontakte/videoplayer-core 2.0.124-dev.30ad4406.0 → 2.0.124-dev.b2dae3ef.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,52 +1,52 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.124-dev.30ad4406.0
3
- * Thu, 16 Jan 2025 08:50:46 GMT
2
+ * @vkontakte/videoplayer-core v2.0.124-dev.b2dae3ef.0
3
+ * Wed, 22 Jan 2025 09:22:55 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-124/doc/
5
5
  */
6
- var YT=Object.create;var to=Object.defineProperty,zT=Object.defineProperties,KT=Object.getOwnPropertyDescriptor,XT=Object.getOwnPropertyDescriptors,JT=Object.getOwnPropertyNames,ms=Object.getOwnPropertySymbols,ZT=Object.getPrototypeOf,ro=Object.prototype.hasOwnProperty,rd=Object.prototype.propertyIsEnumerable;var eI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,td=(a,e,t)=>e in a?to(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,E=(a,e)=>{for(var t in e||(e={}))ro.call(e,t)&&td(a,t,e[t]);if(ms)for(var t of ms(e))rd.call(e,t)&&td(a,t,e[t]);return a},L=(a,e)=>zT(a,XT(e));var id=(a,e)=>{var t={};for(var r in a)ro.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&ms)for(var r of ms(a))e.indexOf(r)<0&&rd.call(a,r)&&(t[r]=a[r]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var tI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of JT(e))!ro.call(a,i)&&i!==t&&to(a,i,{get:()=>e[i],enumerable:!(r=KT(e,i))||r.enumerable});return a};var _=(a,e,t)=>(t=a!=null?YT(ZT(a)):{},tI(e||!a||!a.__esModule?to(t,"default",{value:a,enumerable:!0}):t,a));var A=(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())}),io=function(a,e){this[0]=a,this[1]=e},ae=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof io,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[eI("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var te=f((no,sd)=>{"use strict";var Ti=function(a){return a&&a.Math===Math&&a};sd.exports=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof global=="object"&&global)||Ti(typeof no=="object"&&no)||function(){return this}()||Function("return this")()});var de=f(($0,nd)=>{"use strict";nd.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ii=f((M0,od)=>{"use strict";var rI=de();od.exports=!rI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var oo=f((D0,dd)=>{"use strict";var iI=Ii(),cd=Function.prototype,ud=cd.apply,ld=cd.call;dd.exports=typeof Reflect=="object"&&Reflect.apply||(iI?ld.bind(ud):function(){return ld.apply(ud,arguments)})});var se=f((C0,md)=>{"use strict";var pd=Ii(),hd=Function.prototype,uo=hd.call,aI=pd&&hd.bind.bind(uo,uo);md.exports=pd?aI:function(a){return function(){return uo.apply(a,arguments)}}});var tr=f((V0,bd)=>{"use strict";var fd=se(),sI=fd({}.toString),nI=fd("".slice);bd.exports=function(a){return nI(sI(a),8,-1)}});var lo=f((O0,gd)=>{"use strict";var oI=tr(),uI=se();gd.exports=function(a){if(oI(a)==="Function")return uI(a)}});var Z=f((B0,vd)=>{"use strict";var co=typeof document=="object"&&document.all;vd.exports=typeof co=="undefined"&&co!==void 0?function(a){return typeof a=="function"||a===co}:function(a){return typeof a=="function"}});var De=f((_0,Sd)=>{"use strict";var lI=de();Sd.exports=!lI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Ce=f((N0,yd)=>{"use strict";var cI=Ii(),bs=Function.prototype.call;yd.exports=cI?bs.bind(bs):function(){return bs.apply(bs,arguments)}});var po=f(Ed=>{"use strict";var Td={}.propertyIsEnumerable,Id=Object.getOwnPropertyDescriptor,dI=Id&&!Td.call({1:2},1);Ed.f=dI?function(e){var t=Id(this,e);return!!t&&t.enumerable}:Td});var Ei=f((q0,xd)=>{"use strict";xd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var wd=f((U0,Pd)=>{"use strict";var pI=se(),hI=de(),mI=tr(),ho=Object,fI=pI("".split);Pd.exports=hI(function(){return!ho("z").propertyIsEnumerable(0)})?function(a){return mI(a)==="String"?fI(a,""):ho(a)}:ho});var Mr=f((H0,Ad)=>{"use strict";Ad.exports=function(a){return a==null}});var $t=f((j0,kd)=>{"use strict";var bI=Mr(),gI=TypeError;kd.exports=function(a){if(bI(a))throw new gI("Can't call method on "+a);return a}});var rr=f((Q0,Rd)=>{"use strict";var vI=wd(),SI=$t();Rd.exports=function(a){return vI(SI(a))}});var Ve=f((G0,Ld)=>{"use strict";var yI=Z();Ld.exports=function(a){return typeof a=="object"?a!==null:yI(a)}});var Dr=f((W0,$d)=>{"use strict";$d.exports={}});var pt=f((Y0,Dd)=>{"use strict";var mo=Dr(),fo=te(),TI=Z(),Md=function(a){return TI(a)?a:void 0};Dd.exports=function(a,e){return arguments.length<2?Md(mo[a])||Md(fo[a]):mo[a]&&mo[a][e]||fo[a]&&fo[a][e]}});var xi=f((z0,Cd)=>{"use strict";var II=se();Cd.exports=II({}.isPrototypeOf)});var ir=f((K0,Bd)=>{"use strict";var EI=te(),Vd=EI.navigator,Od=Vd&&Vd.userAgent;Bd.exports=Od?String(Od):""});var go=f((X0,Hd)=>{"use strict";var Ud=te(),bo=ir(),_d=Ud.process,Nd=Ud.Deno,Fd=_d&&_d.versions||Nd&&Nd.version,qd=Fd&&Fd.v8,Ye,gs;qd&&(Ye=qd.split("."),gs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!gs&&bo&&(Ye=bo.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=bo.match(/Chrome\/(\d+)/),Ye&&(gs=+Ye[1])));Hd.exports=gs});var vo=f((J0,Qd)=>{"use strict";var jd=go(),xI=de(),PI=te(),wI=PI.String;Qd.exports=!!Object.getOwnPropertySymbols&&!xI(function(){var a=Symbol("symbol detection");return!wI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&jd&&jd<41})});var So=f((Z0,Gd)=>{"use strict";var AI=vo();Gd.exports=AI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var yo=f((eV,Wd)=>{"use strict";var kI=pt(),RI=Z(),LI=xi(),$I=So(),MI=Object;Wd.exports=$I?function(a){return typeof a=="symbol"}:function(a){var e=kI("Symbol");return RI(e)&&LI(e.prototype,MI(a))}});var Pi=f((tV,Yd)=>{"use strict";var DI=String;Yd.exports=function(a){try{return DI(a)}catch(e){return"Object"}}});var st=f((rV,zd)=>{"use strict";var CI=Z(),VI=Pi(),OI=TypeError;zd.exports=function(a){if(CI(a))return a;throw new OI(VI(a)+" is not a function")}});var wi=f((iV,Kd)=>{"use strict";var BI=st(),_I=Mr();Kd.exports=function(a,e){var t=a[e];return _I(t)?void 0:BI(t)}});var Jd=f((aV,Xd)=>{"use strict";var To=Ce(),Io=Z(),Eo=Ve(),NI=TypeError;Xd.exports=function(a,e){var t,r;if(e==="string"&&Io(t=a.toString)&&!Eo(r=To(t,a))||Io(t=a.valueOf)&&!Eo(r=To(t,a))||e!=="string"&&Io(t=a.toString)&&!Eo(r=To(t,a)))return r;throw new NI("Can't convert object to primitive value")}});var ze=f((sV,Zd)=>{"use strict";Zd.exports=!0});var rp=f((nV,tp)=>{"use strict";var ep=te(),FI=Object.defineProperty;tp.exports=function(a,e){try{FI(ep,a,{value:e,configurable:!0,writable:!0})}catch(t){ep[a]=e}return e}});var Ai=f((oV,sp)=>{"use strict";var qI=ze(),UI=te(),HI=rp(),ip="__core-js_shared__",ap=sp.exports=UI[ip]||HI(ip,{});(ap.versions||(ap.versions=[])).push({version:"3.38.0",mode:qI?"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 xo=f((uV,op)=>{"use strict";var np=Ai();op.exports=function(a,e){return np[a]||(np[a]=e||{})}});var Cr=f((lV,up)=>{"use strict";var jI=$t(),QI=Object;up.exports=function(a){return QI(jI(a))}});var Ke=f((cV,lp)=>{"use strict";var GI=se(),WI=Cr(),YI=GI({}.hasOwnProperty);lp.exports=Object.hasOwn||function(e,t){return YI(WI(e),t)}});var Po=f((dV,cp)=>{"use strict";var zI=se(),KI=0,XI=Math.random(),JI=zI(1 .toString);cp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+JI(++KI+XI,36)}});var pe=f((pV,pp)=>{"use strict";var ZI=te(),eE=xo(),dp=Ke(),tE=Po(),rE=vo(),iE=So(),Vr=ZI.Symbol,wo=eE("wks"),aE=iE?Vr.for||Vr:Vr&&Vr.withoutSetter||tE;pp.exports=function(a){return dp(wo,a)||(wo[a]=rE&&dp(Vr,a)?Vr[a]:aE("Symbol."+a)),wo[a]}});var bp=f((hV,fp)=>{"use strict";var sE=Ce(),hp=Ve(),mp=yo(),nE=wi(),oE=Jd(),uE=pe(),lE=TypeError,cE=uE("toPrimitive");fp.exports=function(a,e){if(!hp(a)||mp(a))return a;var t=nE(a,cE),r;if(t){if(e===void 0&&(e="default"),r=sE(t,a,e),!hp(r)||mp(r))return r;throw new lE("Can't convert object to primitive value")}return e===void 0&&(e="number"),oE(a,e)}});var Ao=f((mV,gp)=>{"use strict";var dE=bp(),pE=yo();gp.exports=function(a){var e=dE(a,"string");return pE(e)?e:e+""}});var vs=f((fV,Sp)=>{"use strict";var hE=te(),vp=Ve(),ko=hE.document,mE=vp(ko)&&vp(ko.createElement);Sp.exports=function(a){return mE?ko.createElement(a):{}}});var Ro=f((bV,yp)=>{"use strict";var fE=De(),bE=de(),gE=vs();yp.exports=!fE&&!bE(function(){return Object.defineProperty(gE("div"),"a",{get:function(){return 7}}).a!==7})});var Ep=f(Ip=>{"use strict";var vE=De(),SE=Ce(),yE=po(),TE=Ei(),IE=rr(),EE=Ao(),xE=Ke(),PE=Ro(),Tp=Object.getOwnPropertyDescriptor;Ip.f=vE?Tp:function(e,t){if(e=IE(e),t=EE(t),PE)try{return Tp(e,t)}catch(r){}if(xE(e,t))return TE(!SE(yE.f,e,t),e[t])}});var Lo=f((vV,xp)=>{"use strict";var wE=de(),AE=Z(),kE=/#|\.prototype\./,ki=function(a,e){var t=LE[RE(a)];return t===ME?!0:t===$E?!1:AE(e)?wE(e):!!e},RE=ki.normalize=function(a){return String(a).replace(kE,".").toLowerCase()},LE=ki.data={},$E=ki.NATIVE="N",ME=ki.POLYFILL="P";xp.exports=ki});var Or=f((SV,wp)=>{"use strict";var Pp=lo(),DE=st(),CE=Ii(),VE=Pp(Pp.bind);wp.exports=function(a,e){return DE(a),e===void 0?a:CE?VE(a,e):function(){return a.apply(e,arguments)}}});var $o=f((yV,Ap)=>{"use strict";var OE=De(),BE=de();Ap.exports=OE&&BE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=f((TV,kp)=>{"use strict";var _E=Ve(),NE=String,FE=TypeError;kp.exports=function(a){if(_E(a))return a;throw new FE(NE(a)+" is not an object")}});var ar=f(Lp=>{"use strict";var qE=De(),UE=Ro(),HE=$o(),Ss=nt(),Rp=Ao(),jE=TypeError,Mo=Object.defineProperty,QE=Object.getOwnPropertyDescriptor,Do="enumerable",Co="configurable",Vo="writable";Lp.f=qE?HE?function(e,t,r){if(Ss(e),t=Rp(t),Ss(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Vo in r&&!r[Vo]){var i=QE(e,t);i&&i[Vo]&&(e[t]=r.value,r={configurable:Co in r?r[Co]:i[Co],enumerable:Do in r?r[Do]:i[Do],writable:!1})}return Mo(e,t,r)}:Mo:function(e,t,r){if(Ss(e),t=Rp(t),Ss(r),UE)try{return Mo(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new jE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Br=f((EV,$p)=>{"use strict";var GE=De(),WE=ar(),YE=Ei();$p.exports=GE?function(a,e,t){return WE.f(a,e,YE(1,t))}:function(a,e,t){return a[e]=t,a}});var ie=f((xV,Dp)=>{"use strict";var Ri=te(),zE=oo(),KE=lo(),XE=Z(),JE=Ep().f,ZE=Lo(),_r=Dr(),ex=Or(),Nr=Br(),Mp=Ke();Ai();var tx=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 zE(a,this,arguments)};return e.prototype=a.prototype,e};Dp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Ri:i?Ri[t]:Ri[t]&&Ri[t].prototype,o=r?_r:_r[t]||Nr(_r,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=ZE(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Mp(n,p),m=o[p],c&&(a.dontCallGetSet?(v=JE(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?g=ex(h,Ri):a.wrap&&c?g=tx(h):s&&XE(h)?g=KE(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&Nr(g,"sham",!0),Nr(o,p,g),s&&(d=t+"Prototype",Mp(_r,d)||Nr(_r,d,{}),Nr(_r[d],p,h),a.real&&u&&(l||!u[p])&&Nr(u,p,h)))}});var Vp=f((PV,Cp)=>{"use strict";var rx=Math.ceil,ix=Math.floor;Cp.exports=Math.trunc||function(e){var t=+e;return(t>0?ix:rx)(t)}});var Li=f((wV,Op)=>{"use strict";var ax=Vp();Op.exports=function(a){var e=+a;return e!==e||e===0?0:ax(e)}});var _p=f((AV,Bp)=>{"use strict";var sx=Li(),nx=Math.max,ox=Math.min;Bp.exports=function(a,e){var t=sx(a);return t<0?nx(t+e,0):ox(t,e)}});var Oo=f((kV,Np)=>{"use strict";var ux=Li(),lx=Math.min;Np.exports=function(a){var e=ux(a);return e>0?lx(e,9007199254740991):0}});var Fr=f((RV,Fp)=>{"use strict";var cx=Oo();Fp.exports=function(a){return cx(a.length)}});var Bo=f((LV,Up)=>{"use strict";var dx=rr(),px=_p(),hx=Fr(),qp=function(a){return function(e,t,r){var i=dx(e),s=hx(i);if(s===0)return!a&&-1;var n=px(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}};Up.exports={includes:qp(!0),indexOf:qp(!1)}});var $i=f(($V,Hp)=>{"use strict";Hp.exports=function(){}});var jp=f(()=>{"use strict";var mx=ie(),fx=Bo().includes,bx=de(),gx=$i(),vx=bx(function(){return!Array(1).includes()});mx({target:"Array",proto:!0,forced:vx},{includes:function(e){return fx(this,e,arguments.length>1?arguments[1]:void 0)}});gx("includes")});var Mt=f((CV,Qp)=>{"use strict";var Sx=pt();Qp.exports=Sx});var Wp=f((VV,Gp)=>{"use strict";jp();var yx=Mt();Gp.exports=yx("Array","includes")});var zp=f((OV,Yp)=>{"use strict";var Tx=Wp();Yp.exports=Tx});var Xe=f((BV,Kp)=>{"use strict";var Ix=zp();Kp.exports=Ix});var Is=f((zV,ah)=>{"use strict";var Lx=xo(),$x=Po(),ih=Lx("keys");ah.exports=function(a){return ih[a]||(ih[a]=$x(a))}});var nh=f((KV,sh)=>{"use strict";var Mx=de();sh.exports=!Mx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Es=f((XV,uh)=>{"use strict";var Dx=Ke(),Cx=Z(),Vx=Cr(),Ox=Is(),Bx=nh(),oh=Ox("IE_PROTO"),Fo=Object,_x=Fo.prototype;uh.exports=Bx?Fo.getPrototypeOf:function(a){var e=Vx(a);if(Dx(e,oh))return e[oh];var t=e.constructor;return Cx(t)&&e instanceof t?t.prototype:e instanceof Fo?_x:null}});var xs=f((JV,lh)=>{"use strict";lh.exports={}});var ph=f((ZV,dh)=>{"use strict";var Nx=se(),qo=Ke(),Fx=rr(),qx=Bo().indexOf,Ux=xs(),ch=Nx([].push);dh.exports=function(a,e){var t=Fx(a),r=0,i=[],s;for(s in t)!qo(Ux,s)&&qo(t,s)&&ch(i,s);for(;e.length>r;)qo(t,s=e[r++])&&(~qx(i,s)||ch(i,s));return i}});var Uo=f((eO,hh)=>{"use strict";hh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Ho=f((tO,mh)=>{"use strict";var Hx=ph(),jx=Uo();mh.exports=Object.keys||function(e){return Hx(e,jx)}});var jo=f((rO,Sh)=>{"use strict";var bh=De(),Qx=de(),gh=se(),Gx=Es(),Wx=Ho(),Yx=rr(),zx=po().f,vh=gh(zx),Kx=gh([].push),Xx=bh&&Qx(function(){var a=Object.create(null);return a[2]=2,!vh(a,2)}),fh=function(a){return function(e){for(var t=Yx(e),r=Wx(t),i=Xx&&Gx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!bh||(i?u in t:vh(t,u)))&&Kx(o,a?[u,t[u]]:t[u]);return o}};Sh.exports={entries:fh(!0),values:fh(!1)}});var yh=f(()=>{"use strict";var Jx=ie(),Zx=jo().entries;Jx({target:"Object",stat:!0},{entries:function(e){return Zx(e)}})});var Ih=f((sO,Th)=>{"use strict";yh();var eP=Dr();Th.exports=eP.Object.entries});var xh=f((nO,Eh)=>{"use strict";var tP=Ih();Eh.exports=tP});var qr=f((oO,Ph)=>{"use strict";var rP=xh();Ph.exports=rP});var sr=f((uO,wh)=>{"use strict";wh.exports={}});var Rh=f((lO,kh)=>{"use strict";var iP=te(),aP=Z(),Ah=iP.WeakMap;kh.exports=aP(Ah)&&/native code/.test(String(Ah))});var Yo=f((cO,Mh)=>{"use strict";var sP=Rh(),$h=te(),nP=Ve(),oP=Br(),Qo=Ke(),Go=Ai(),uP=Is(),lP=xs(),Lh="Object already initialized",Wo=$h.TypeError,cP=$h.WeakMap,Ps,Mi,ws,dP=function(a){return ws(a)?Mi(a):Ps(a,{})},pP=function(a){return function(e){var t;if(!nP(e)||(t=Mi(e)).type!==a)throw new Wo("Incompatible receiver, "+a+" required");return t}};sP||Go.state?(Je=Go.state||(Go.state=new cP),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,Ps=function(a,e){if(Je.has(a))throw new Wo(Lh);return e.facade=a,Je.set(a,e),e},Mi=function(a){return Je.get(a)||{}},ws=function(a){return Je.has(a)}):(nr=uP("state"),lP[nr]=!0,Ps=function(a,e){if(Qo(a,nr))throw new Wo(Lh);return e.facade=a,oP(a,nr,e),e},Mi=function(a){return Qo(a,nr)?a[nr]:{}},ws=function(a){return Qo(a,nr)});var Je,nr;Mh.exports={set:Ps,get:Mi,has:ws,enforce:dP,getterFor:pP}});var Xo=f((dO,Ch)=>{"use strict";var zo=De(),hP=Ke(),Dh=Function.prototype,mP=zo&&Object.getOwnPropertyDescriptor,Ko=hP(Dh,"name"),fP=Ko&&function(){}.name==="something",bP=Ko&&(!zo||zo&&mP(Dh,"name").configurable);Ch.exports={EXISTS:Ko,PROPER:fP,CONFIGURABLE:bP}});var Oh=f(Vh=>{"use strict";var gP=De(),vP=$o(),SP=ar(),yP=nt(),TP=rr(),IP=Ho();Vh.f=gP&&!vP?Object.defineProperties:function(e,t){yP(e);for(var r=TP(t),i=IP(t),s=i.length,n=0,o;s>n;)SP.f(e,o=i[n++],r[o]);return e}});var Jo=f((hO,Bh)=>{"use strict";var EP=pt();Bh.exports=EP("document","documentElement")});var ru=f((mO,jh)=>{"use strict";var xP=nt(),PP=Oh(),_h=Uo(),wP=xs(),AP=Jo(),kP=vs(),RP=Is(),Nh=">",Fh="<",eu="prototype",tu="script",Uh=RP("IE_PROTO"),Zo=function(){},Hh=function(a){return Fh+tu+Nh+a+Fh+"/"+tu+Nh},qh=function(a){a.write(Hh("")),a.close();var e=a.parentWindow.Object;return a=null,e},LP=function(){var a=kP("iframe"),e="java"+tu+":",t;return a.style.display="none",AP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Hh("document.F=Object")),t.close(),t.F},As,ks=function(){try{As=new ActiveXObject("htmlfile")}catch(e){}ks=typeof document!="undefined"?document.domain&&As?qh(As):LP():qh(As);for(var a=_h.length;a--;)delete ks[eu][_h[a]];return ks()};wP[Uh]=!0;jh.exports=Object.create||function(e,t){var r;return e!==null?(Zo[eu]=xP(e),r=new Zo,Zo[eu]=null,r[Uh]=e):r=ks(),t===void 0?r:PP.f(r,t)}});var Ur=f((fO,Qh)=>{"use strict";var $P=Br();Qh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:$P(a,e,t),a}});var nu=f((bO,Yh)=>{"use strict";var MP=de(),DP=Z(),CP=Ve(),VP=ru(),Gh=Es(),OP=Ur(),BP=pe(),_P=ze(),su=BP("iterator"),Wh=!1,ht,iu,au;[].keys&&(au=[].keys(),"next"in au?(iu=Gh(Gh(au)),iu!==Object.prototype&&(ht=iu)):Wh=!0);var NP=!CP(ht)||MP(function(){var a={};return ht[su].call(a)!==a});NP?ht={}:_P&&(ht=VP(ht));DP(ht[su])||OP(ht,su,function(){return this});Yh.exports={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:Wh}});var Rs=f((gO,Kh)=>{"use strict";var FP=pe(),qP=FP("toStringTag"),zh={};zh[qP]="z";Kh.exports=String(zh)==="[object z]"});var Di=f((vO,Xh)=>{"use strict";var UP=Rs(),HP=Z(),Ls=tr(),jP=pe(),QP=jP("toStringTag"),GP=Object,WP=Ls(function(){return arguments}())==="Arguments",YP=function(a,e){try{return a[e]}catch(t){}};Xh.exports=UP?Ls:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=YP(e=GP(a),QP))=="string"?t:WP?Ls(e):(r=Ls(e))==="Object"&&HP(e.callee)?"Arguments":r}});var Zh=f((SO,Jh)=>{"use strict";var zP=Rs(),KP=Di();Jh.exports=zP?{}.toString:function(){return"[object "+KP(this)+"]"}});var Ci=f((yO,tm)=>{"use strict";var XP=Rs(),JP=ar().f,ZP=Br(),ew=Ke(),tw=Zh(),rw=pe(),em=rw("toStringTag");tm.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(ew(i,em)||JP(i,em,{configurable:!0,value:e}),r&&!XP&&ZP(i,"toString",tw))}});var im=f((TO,rm)=>{"use strict";var iw=nu().IteratorPrototype,aw=ru(),sw=Ei(),nw=Ci(),ow=sr(),uw=function(){return this};rm.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=aw(iw,{next:sw(+!r,t)}),nw(a,i,!1,!0),ow[i]=uw,a}});var sm=f((IO,am)=>{"use strict";var lw=se(),cw=st();am.exports=function(a,e,t){try{return lw(cw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var om=f((EO,nm)=>{"use strict";var dw=Ve();nm.exports=function(a){return dw(a)||a===null}});var lm=f((xO,um)=>{"use strict";var pw=om(),hw=String,mw=TypeError;um.exports=function(a){if(pw(a))return a;throw new mw("Can't set "+hw(a)+" as a prototype")}});var ou=f((PO,cm)=>{"use strict";var fw=sm(),bw=Ve(),gw=$t(),vw=lm();cm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=fw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return gw(i),vw(s),bw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Tm=f((wO,ym)=>{"use strict";var Sw=ie(),yw=Ce(),$s=ze(),vm=Xo(),Tw=Z(),Iw=im(),dm=Es(),pm=ou(),Ew=Ci(),xw=Br(),uu=Ur(),Pw=pe(),hm=sr(),Sm=nu(),ww=vm.PROPER,Aw=vm.CONFIGURABLE,mm=Sm.IteratorPrototype,Ms=Sm.BUGGY_SAFARI_ITERATORS,Vi=Pw("iterator"),fm="keys",Oi="values",bm="entries",gm=function(){return this};ym.exports=function(a,e,t,r,i,s,n){Iw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Ms&&v&&v in c)return c[v];switch(v){case fm:return function(){return new t(this,v)};case Oi:return function(){return new t(this,v)};case bm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Vi]||c["@@iterator"]||i&&c[i],p=!Ms&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=dm(h.call(new a)),m!==Object.prototype&&m.next&&(!$s&&dm(m)!==mm&&(pm?pm(m,mm):Tw(m[Vi])||uu(m,Vi,gm)),Ew(m,u,!0,!0),$s&&(hm[u]=gm))),ww&&i===Oi&&d&&d.name!==Oi&&(!$s&&Aw?xw(c,"name",Oi):(l=!0,p=function(){return yw(d,this)})),i)if(b={values:o(Oi),keys:s?p:o(fm),entries:o(bm)},n)for(g in b)(Ms||l||!(g in c))&&uu(c,g,b[g]);else Sw({target:e,proto:!0,forced:Ms||l},b);return(!$s||n)&&c[Vi]!==p&&uu(c,Vi,p,{name:i}),hm[e]=p,b}});var Em=f((AO,Im)=>{"use strict";Im.exports=function(a,e){return{value:a,done:e}}});var cu=f((kO,km)=>{"use strict";var kw=rr(),lu=$i(),xm=sr(),wm=Yo(),Rw=ar().f,Lw=Tm(),Ds=Em(),$w=ze(),Mw=De(),Am="Array Iterator",Dw=wm.set,Cw=wm.getterFor(Am);km.exports=Lw(Array,"Array",function(a,e){Dw(this,{type:Am,target:kw(a),index:0,kind:e})},function(){var a=Cw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ds(void 0,!0);switch(a.kind){case"keys":return Ds(t,!1);case"values":return Ds(e[t],!1)}return Ds([t,e[t]],!1)},"values");var Pm=xm.Arguments=xm.Array;lu("keys");lu("values");lu("entries");if(!$w&&Mw&&Pm.name!=="values")try{Rw(Pm,"name",{value:"values"})}catch(a){}});var Lm=f((RO,Rm)=>{"use strict";var Vw=pe(),Ow=sr(),Bw=Vw("iterator"),_w=Array.prototype;Rm.exports=function(a){return a!==void 0&&(Ow.Array===a||_w[Bw]===a)}});var du=f((LO,Mm)=>{"use strict";var Nw=Di(),$m=wi(),Fw=Mr(),qw=sr(),Uw=pe(),Hw=Uw("iterator");Mm.exports=function(a){if(!Fw(a))return $m(a,Hw)||$m(a,"@@iterator")||qw[Nw(a)]}});var Cm=f(($O,Dm)=>{"use strict";var jw=Ce(),Qw=st(),Gw=nt(),Ww=Pi(),Yw=du(),zw=TypeError;Dm.exports=function(a,e){var t=arguments.length<2?Yw(a):e;if(Qw(t))return Gw(jw(t,a));throw new zw(Ww(a)+" is not iterable")}});var Bm=f((MO,Om)=>{"use strict";var Kw=Ce(),Vm=nt(),Xw=wi();Om.exports=function(a,e,t){var r,i;Vm(a);try{if(r=Xw(a,"return"),!r){if(e==="throw")throw t;return t}r=Kw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Vm(r),t}});var Vs=f((DO,qm)=>{"use strict";var Jw=Or(),Zw=Ce(),eA=nt(),tA=Pi(),rA=Lm(),iA=Fr(),_m=xi(),aA=Cm(),sA=du(),Nm=Bm(),nA=TypeError,Cs=function(a,e){this.stopped=a,this.result=e},Fm=Cs.prototype;qm.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=Jw(e,r),l,c,d,p,h,m,b,g=function(S){return l&&Nm(l,"normal",S),new Cs(!0,S)},v=function(S){return i?(eA(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=sA(a),!c)throw new nA(tA(a)+" is not iterable");if(rA(c)){for(d=0,p=iA(a);p>d;d++)if(h=v(a[d]),h&&_m(Fm,h))return h;return new Cs(!1)}l=aA(a,c)}for(m=s?a.next:l.next;!(b=Zw(m,l)).done;){try{h=v(b.value)}catch(S){Nm(l,"throw",S)}if(typeof h=="object"&&h&&_m(Fm,h))return h}return new Cs(!1)}});var Hm=f((CO,Um)=>{"use strict";var oA=De(),uA=ar(),lA=Ei();Um.exports=function(a,e,t){oA?uA.f(a,e,lA(0,t)):a[e]=t}});var jm=f(()=>{"use strict";var cA=ie(),dA=Vs(),pA=Hm();cA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return dA(e,function(r,i){pA(t,r,i)},{AS_ENTRIES:!0}),t}})});var Gm=f((BO,Qm)=>{"use strict";cu();jm();var hA=Dr();Qm.exports=hA.Object.fromEntries});var Ym=f((_O,Wm)=>{"use strict";Wm.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 Km=f(()=>{"use strict";cu();var mA=Ym(),fA=te(),bA=Ci(),zm=sr();for(Os in mA)bA(fA[Os],Os),zm[Os]=zm.Array;var Os});var Jm=f((qO,Xm)=>{"use strict";var gA=Gm();Km();Xm.exports=gA});var pu=f((UO,Zm)=>{"use strict";var vA=Jm();Zm.exports=vA});var ef=f(()=>{"use strict"});var hu=f((QO,tf)=>{"use strict";var Bi=te(),SA=ir(),yA=tr(),Bs=function(a){return SA.slice(0,a.length)===a};tf.exports=function(){return Bs("Bun/")?"BUN":Bs("Cloudflare-Workers")?"CLOUDFLARE":Bs("Deno/")?"DENO":Bs("Node.js/")?"NODE":Bi.Bun&&typeof Bun.version=="string"?"BUN":Bi.Deno&&typeof Deno.version=="object"?"DENO":yA(Bi.process)==="process"?"NODE":Bi.window&&Bi.document?"BROWSER":"REST"}()});var _s=f((GO,rf)=>{"use strict";var TA=hu();rf.exports=TA==="NODE"});var sf=f((WO,af)=>{"use strict";var IA=ar();af.exports=function(a,e,t){return IA.f(a,e,t)}});var uf=f((YO,of)=>{"use strict";var EA=pt(),xA=sf(),PA=pe(),wA=De(),nf=PA("species");of.exports=function(a){var e=EA(a);wA&&e&&!e[nf]&&xA(e,nf,{configurable:!0,get:function(){return this}})}});var cf=f((zO,lf)=>{"use strict";var AA=xi(),kA=TypeError;lf.exports=function(a,e){if(AA(e,a))return a;throw new kA("Incorrect invocation")}});var fu=f((KO,df)=>{"use strict";var RA=se(),LA=Z(),mu=Ai(),$A=RA(Function.toString);LA(mu.inspectSource)||(mu.inspectSource=function(a){return $A(a)});df.exports=mu.inspectSource});var gu=f((XO,bf)=>{"use strict";var MA=se(),DA=de(),pf=Z(),CA=Di(),VA=pt(),OA=fu(),hf=function(){},mf=VA("Reflect","construct"),bu=/^\s*(?:class|function)\b/,BA=MA(bu.exec),_A=!bu.test(hf),_i=function(e){if(!pf(e))return!1;try{return mf(hf,[],e),!0}catch(t){return!1}},ff=function(e){if(!pf(e))return!1;switch(CA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return _A||!!BA(bu,OA(e))}catch(t){return!0}};ff.sham=!0;bf.exports=!mf||DA(function(){var a;return _i(_i.call)||!_i(Object)||!_i(function(){a=!0})||a})?ff:_i});var vf=f((JO,gf)=>{"use strict";var NA=gu(),FA=Pi(),qA=TypeError;gf.exports=function(a){if(NA(a))return a;throw new qA(FA(a)+" is not a constructor")}});var vu=f((ZO,yf)=>{"use strict";var Sf=nt(),UA=vf(),HA=Mr(),jA=pe(),QA=jA("species");yf.exports=function(a,e){var t=Sf(a).constructor,r;return t===void 0||HA(r=Sf(t)[QA])?e:UA(r)}});var If=f((eB,Tf)=>{"use strict";var GA=se();Tf.exports=GA([].slice)});var xf=f((tB,Ef)=>{"use strict";var WA=TypeError;Ef.exports=function(a,e){if(a<e)throw new WA("Not enough arguments");return a}});var Su=f((rB,Pf)=>{"use strict";var YA=ir();Pf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(YA)});var ku=f((iB,Cf)=>{"use strict";var Oe=te(),zA=oo(),KA=Or(),wf=Z(),XA=Ke(),Df=de(),Af=Jo(),JA=If(),kf=vs(),ZA=xf(),ek=Su(),tk=_s(),Pu=Oe.setImmediate,wu=Oe.clearImmediate,rk=Oe.process,yu=Oe.Dispatch,ik=Oe.Function,Rf=Oe.MessageChannel,ak=Oe.String,Tu=0,Ni={},Lf="onreadystatechange",Fi,or,Iu,Eu;Df(function(){Fi=Oe.location});var Au=function(a){if(XA(Ni,a)){var e=Ni[a];delete Ni[a],e()}},xu=function(a){return function(){Au(a)}},$f=function(a){Au(a.data)},Mf=function(a){Oe.postMessage(ak(a),Fi.protocol+"//"+Fi.host)};(!Pu||!wu)&&(Pu=function(e){ZA(arguments.length,1);var t=wf(e)?e:ik(e),r=JA(arguments,1);return Ni[++Tu]=function(){zA(t,void 0,r)},or(Tu),Tu},wu=function(e){delete Ni[e]},tk?or=function(a){rk.nextTick(xu(a))}:yu&&yu.now?or=function(a){yu.now(xu(a))}:Rf&&!ek?(Iu=new Rf,Eu=Iu.port2,Iu.port1.onmessage=$f,or=KA(Eu.postMessage,Eu)):Oe.addEventListener&&wf(Oe.postMessage)&&!Oe.importScripts&&Fi&&Fi.protocol!=="file:"&&!Df(Mf)?(or=Mf,Oe.addEventListener("message",$f,!1)):Lf in kf("script")?or=function(a){Af.appendChild(kf("script"))[Lf]=function(){Af.removeChild(this),Au(a)}}:or=function(a){setTimeout(xu(a),0)});Cf.exports={set:Pu,clear:wu}});var Bf=f((aB,Of)=>{"use strict";var Vf=te(),sk=De(),nk=Object.getOwnPropertyDescriptor;Of.exports=function(a){if(!sk)return Vf[a];var e=nk(Vf,a);return e&&e.value}});var Ru=f((sB,Nf)=>{"use strict";var _f=function(){this.head=null,this.tail=null};_f.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}}};Nf.exports=_f});var qf=f((nB,Ff)=>{"use strict";var ok=ir();Ff.exports=/ipad|iphone|ipod/i.test(ok)&&typeof Pebble!="undefined"});var Hf=f((oB,Uf)=>{"use strict";var uk=ir();Uf.exports=/web0s(?!.*chrome)/i.test(uk)});var Kf=f((uB,zf)=>{"use strict";var jr=te(),lk=Bf(),jf=Or(),Lu=ku().set,ck=Ru(),dk=Su(),pk=qf(),hk=Hf(),$u=_s(),Qf=jr.MutationObserver||jr.WebKitMutationObserver,Gf=jr.document,Wf=jr.process,Ns=jr.Promise,Cu=lk("queueMicrotask"),Hr,Mu,Du,Fs,Yf;Cu||(qi=new ck,Ui=function(){var a,e;for($u&&(a=Wf.domain)&&a.exit();e=qi.get();)try{e()}catch(t){throw qi.head&&Hr(),t}a&&a.enter()},!dk&&!$u&&!hk&&Qf&&Gf?(Mu=!0,Du=Gf.createTextNode(""),new Qf(Ui).observe(Du,{characterData:!0}),Hr=function(){Du.data=Mu=!Mu}):!pk&&Ns&&Ns.resolve?(Fs=Ns.resolve(void 0),Fs.constructor=Ns,Yf=jf(Fs.then,Fs),Hr=function(){Yf(Ui)}):$u?Hr=function(){Wf.nextTick(Ui)}:(Lu=jf(Lu,jr),Hr=function(){Lu(Ui)}),Cu=function(a){qi.head||Hr(),qi.add(a)});var qi,Ui;zf.exports=Cu});var Jf=f((lB,Xf)=>{"use strict";Xf.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var qs=f((cB,Zf)=>{"use strict";Zf.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var ur=f((dB,eb)=>{"use strict";var mk=te();eb.exports=mk.Promise});var Qr=f((pB,ab)=>{"use strict";var fk=te(),Hi=ur(),bk=Z(),gk=Lo(),vk=fu(),Sk=pe(),tb=hu(),yk=ze(),Vu=go(),rb=Hi&&Hi.prototype,Tk=Sk("species"),Ou=!1,ib=bk(fk.PromiseRejectionEvent),Ik=gk("Promise",function(){var a=vk(Hi),e=a!==String(Hi);if(!e&&Vu===66||yk&&!(rb.catch&&rb.finally))return!0;if(!Vu||Vu<51||!/native code/.test(a)){var t=new Hi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Tk]=r,Ou=t.then(function(){})instanceof r,!Ou)return!0}return!e&&(tb==="BROWSER"||tb==="DENO")&&!ib});ab.exports={CONSTRUCTOR:Ik,REJECTION_EVENT:ib,SUBCLASSING:Ou}});var Gr=f((hB,nb)=>{"use strict";var sb=st(),Ek=TypeError,xk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Ek("Bad Promise constructor");e=r,t=i}),this.resolve=sb(e),this.reject=sb(t)};nb.exports.f=function(a){return new xk(a)}});var Pb=f(()=>{"use strict";var Pk=ie(),wk=ze(),Qs=_s(),Dt=te(),Kr=Ce(),ob=Ur(),ub=ou(),Ak=Ci(),kk=uf(),Rk=st(),js=Z(),Lk=Ve(),$k=cf(),Mk=vu(),hb=ku().set,qu=Kf(),Dk=Jf(),Ck=qs(),Vk=Ru(),mb=Yo(),Gs=ur(),Uu=Qr(),fb=Gr(),Ws="Promise",bb=Uu.CONSTRUCTOR,Ok=Uu.REJECTION_EVENT,Bk=Uu.SUBCLASSING,Bu=mb.getterFor(Ws),_k=mb.set,Wr=Gs&&Gs.prototype,lr=Gs,Us=Wr,gb=Dt.TypeError,_u=Dt.document,Hu=Dt.process,Nu=fb.f,Nk=Nu,Fk=!!(_u&&_u.createEvent&&Dt.dispatchEvent),vb="unhandledrejection",qk="rejectionhandled",lb=0,Sb=1,Uk=2,ju=1,yb=2,Hs,cb,Hk,db,Tb=function(a){var e;return Lk(a)&&js(e=a.then)?e:!1},Ib=function(a,e){var t=e.value,r=e.state===Sb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===yb&&Qk(e),e.rejection=ju),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new gb("Promise-chain cycle")):(l=Tb(u))?Kr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Eb=function(a,e){a.notified||(a.notified=!0,qu(function(){for(var t=a.reactions,r;r=t.get();)Ib(r,a);a.notified=!1,e&&!a.rejection&&jk(a)}))},xb=function(a,e,t){var r,i;Fk?(r=_u.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Dt.dispatchEvent(r)):r={promise:e,reason:t},!Ok&&(i=Dt["on"+a])?i(r):a===vb&&Dk("Unhandled promise rejection",t)},jk=function(a){Kr(hb,Dt,function(){var e=a.facade,t=a.value,r=pb(a),i;if(r&&(i=Ck(function(){Qs?Hu.emit("unhandledRejection",t,e):xb(vb,e,t)}),a.rejection=Qs||pb(a)?yb:ju,i.error))throw i.value})},pb=function(a){return a.rejection!==ju&&!a.parent},Qk=function(a){Kr(hb,Dt,function(){var e=a.facade;Qs?Hu.emit("rejectionHandled",e):xb(qk,e,a.value)})},Yr=function(a,e,t){return function(r){a(e,r,t)}},zr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Uk,Eb(a,!0))},Fu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new gb("Promise can't be resolved itself");var r=Tb(e);r?qu(function(){var i={done:!1};try{Kr(r,e,Yr(Fu,i,a),Yr(zr,i,a))}catch(s){zr(i,s,a)}}):(a.value=e,a.state=Sb,Eb(a,!1))}catch(i){zr({done:!1},i,a)}}};if(bb&&(lr=function(e){$k(this,Us),Rk(e),Kr(Hs,this);var t=Bu(this);try{e(Yr(Fu,t),Yr(zr,t))}catch(r){zr(t,r)}},Us=lr.prototype,Hs=function(e){_k(this,{type:Ws,done:!1,notified:!1,parent:!1,reactions:new Vk,rejection:!1,state:lb,value:void 0})},Hs.prototype=ob(Us,"then",function(e,t){var r=Bu(this),i=Nu(Mk(this,lr));return r.parent=!0,i.ok=js(e)?e:!0,i.fail=js(t)&&t,i.domain=Qs?Hu.domain:void 0,r.state===lb?r.reactions.add(i):qu(function(){Ib(i,r)}),i.promise}),cb=function(){var a=new Hs,e=Bu(a);this.promise=a,this.resolve=Yr(Fu,e),this.reject=Yr(zr,e)},fb.f=Nu=function(a){return a===lr||a===Hk?new cb(a):Nk(a)},!wk&&js(Gs)&&Wr!==Object.prototype)){db=Wr.then,Bk||ob(Wr,"then",function(e,t){var r=this;return new lr(function(i,s){Kr(db,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Wr.constructor}catch(a){}ub&&ub(Wr,Us)}Pk({global:!0,constructor:!0,wrap:!0,forced:bb},{Promise:lr});Ak(lr,Ws,!1,!0);kk(Ws)});var Lb=f((bB,Rb)=>{"use strict";var Gk=pe(),Ab=Gk("iterator"),kb=!1;try{wb=0,Qu={next:function(){return{done:!!wb++}},return:function(){kb=!0}},Qu[Ab]=function(){return this},Array.from(Qu,function(){throw 2})}catch(a){}var wb,Qu;Rb.exports=function(a,e){try{if(!e&&!kb)return!1}catch(i){return!1}var t=!1;try{var r={};r[Ab]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Gu=f((gB,$b)=>{"use strict";var Wk=ur(),Yk=Lb(),zk=Qr().CONSTRUCTOR;$b.exports=zk||!Yk(function(a){Wk.all(a).then(void 0,function(){})})});var Mb=f(()=>{"use strict";var Kk=ie(),Xk=Ce(),Jk=st(),Zk=Gr(),eR=qs(),tR=Vs(),rR=Gu();Kk({target:"Promise",stat:!0,forced:rR},{all:function(e){var t=this,r=Zk.f(t),i=r.resolve,s=r.reject,n=eR(function(){var o=Jk(t.resolve),u=[],l=0,c=1;tR(e,function(d){var p=l++,h=!1;c++,Xk(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Cb=f(()=>{"use strict";var iR=ie(),aR=ze(),sR=Qr().CONSTRUCTOR,Yu=ur(),nR=pt(),oR=Z(),uR=Ur(),Db=Yu&&Yu.prototype;iR({target:"Promise",proto:!0,forced:sR,real:!0},{catch:function(a){return this.then(void 0,a)}});!aR&&oR(Yu)&&(Wu=nR("Promise").prototype.catch,Db.catch!==Wu&&uR(Db,"catch",Wu,{unsafe:!0}));var Wu});var Vb=f(()=>{"use strict";var lR=ie(),cR=Ce(),dR=st(),pR=Gr(),hR=qs(),mR=Vs(),fR=Gu();lR({target:"Promise",stat:!0,forced:fR},{race:function(e){var t=this,r=pR.f(t),i=r.reject,s=hR(function(){var n=dR(t.resolve);mR(e,function(o){cR(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Ob=f(()=>{"use strict";var bR=ie(),gR=Gr(),vR=Qr().CONSTRUCTOR;bR({target:"Promise",stat:!0,forced:vR},{reject:function(e){var t=gR.f(this),r=t.reject;return r(e),t.promise}})});var zu=f((wB,Bb)=>{"use strict";var SR=nt(),yR=Ve(),TR=Gr();Bb.exports=function(a,e){if(SR(a),yR(e)&&e.constructor===a)return e;var t=TR.f(a),r=t.resolve;return r(e),t.promise}});var Fb=f(()=>{"use strict";var IR=ie(),ER=pt(),_b=ze(),xR=ur(),Nb=Qr().CONSTRUCTOR,PR=zu(),wR=ER("Promise"),AR=_b&&!Nb;IR({target:"Promise",stat:!0,forced:_b||Nb},{resolve:function(e){return PR(AR&&this===wR?xR:this,e)}})});var qb=f(()=>{"use strict";Pb();Mb();Cb();Vb();Ob();Fb()});var Qb=f(()=>{"use strict";var kR=ie(),RR=ze(),Ys=ur(),LR=de(),Hb=pt(),jb=Z(),$R=vu(),Ub=zu(),MR=Ur(),Xu=Ys&&Ys.prototype,DR=!!Ys&&LR(function(){Xu.finally.call({then:function(){}},function(){})});kR({target:"Promise",proto:!0,real:!0,forced:DR},{finally:function(a){var e=$R(this,Hb("Promise")),t=jb(a);return this.then(t?function(r){return Ub(e,a()).then(function(){return r})}:a,t?function(r){return Ub(e,a()).then(function(){throw r})}:a)}});!RR&&jb(Ys)&&(Ku=Hb("Promise").prototype.finally,Xu.finally!==Ku&&MR(Xu,"finally",Ku,{unsafe:!0}));var Ku});var Wb=f((DB,Gb)=>{"use strict";ef();qb();Qb();var CR=Mt();Gb.exports=CR("Promise","finally")});var zb=f((CB,Yb)=>{"use strict";var VR=Wb();Yb.exports=VR});var zs=f((VB,Kb)=>{"use strict";var OR=zb();Kb.exports=OR});var lg=f(()=>{"use strict";var KR=ie(),XR=jo().values;KR({target:"Object",stat:!0},{values:function(e){return XR(e)}})});var dg=f((S_,cg)=>{"use strict";lg();var JR=Dr();cg.exports=JR.Object.values});var hg=f((y_,pg)=>{"use strict";var ZR=dg();pg.exports=ZR});var Jr=f((T_,mg)=>{"use strict";var eL=hg();mg.exports=eL});var Ag=f(()=>{"use strict";var bL=ie(),gL=Cr(),vL=Fr(),SL=Li(),yL=$i();bL({target:"Array",proto:!0},{at:function(e){var t=gL(this),r=vL(t),i=SL(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});yL("at")});var Rg=f((z_,kg)=>{"use strict";Ag();var TL=Mt();kg.exports=TL("Array","at")});var $g=f((K_,Lg)=>{"use strict";var IL=Rg();Lg.exports=IL});var ei=f((X_,Mg)=>{"use strict";var EL=$g();Mg.exports=EL});var yl=f((DF,lv)=>{"use strict";var s$=tr();lv.exports=Array.isArray||function(e){return s$(e)==="Array"}});var dv=f((CF,cv)=>{"use strict";var n$=TypeError,o$=9007199254740991;cv.exports=function(a){if(a>o$)throw n$("Maximum allowed index exceeded");return a}});var mv=f((VF,hv)=>{"use strict";var u$=yl(),l$=Fr(),c$=dv(),d$=Or(),pv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?d$(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&u$(d)?(p=l$(d),u=pv(a,e,d,p,u,s-1)-1):(c$(u+1),a[u]=d),u++),l++;return u};hv.exports=pv});var vv=f((OF,gv)=>{"use strict";var fv=yl(),p$=gu(),h$=Ve(),m$=pe(),f$=m$("species"),bv=Array;gv.exports=function(a){var e;return fv(a)&&(e=a.constructor,p$(e)&&(e===bv||fv(e.prototype))?e=void 0:h$(e)&&(e=e[f$],e===null&&(e=void 0))),e===void 0?bv:e}});var yv=f((BF,Sv)=>{"use strict";var b$=vv();Sv.exports=function(a,e){return new(b$(a))(e===0?0:e)}});var Tv=f(()=>{"use strict";var g$=ie(),v$=mv(),S$=st(),y$=Cr(),T$=Fr(),I$=yv();g$({target:"Array",proto:!0},{flatMap:function(e){var t=y$(this),r=T$(t),i;return S$(e),i=I$(t,0),i.length=v$(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var Iv=f(()=>{"use strict";var E$=$i();E$("flatMap")});var xv=f((UF,Ev)=>{"use strict";Tv();Iv();var x$=Mt();Ev.exports=x$("Array","flatMap")});var wv=f((HF,Pv)=>{"use strict";var P$=xv();Pv.exports=P$});var Tl=f((jF,Av)=>{"use strict";var w$=wv();Av.exports=w$});var aa=f((tq,Wv)=>{"use strict";var C$=Di(),V$=String;Wv.exports=function(a){if(C$(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return V$(a)}});var El=f((rq,Yv)=>{"use strict";Yv.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 Xv=f((iq,Kv)=>{"use strict";var O$=se(),B$=$t(),_$=aa(),Pl=El(),zv=O$("".replace),N$=RegExp("^["+Pl+"]+"),F$=RegExp("(^|[^"+Pl+"])["+Pl+"]+$"),xl=function(a){return function(e){var t=_$(B$(e));return a&1&&(t=zv(t,N$,"")),a&2&&(t=zv(t,F$,"$1")),t}};Kv.exports={start:xl(1),end:xl(2),trim:xl(3)}});var tS=f((aq,eS)=>{"use strict";var q$=Xo().PROPER,U$=de(),Jv=El(),Zv="\u200B\x85\u180E";eS.exports=function(a){return U$(function(){return!!Jv[a]()||Zv[a]()!==Zv||q$&&Jv[a].name!==a})}});var wl=f((sq,rS)=>{"use strict";var H$=Xv().start,j$=tS();rS.exports=j$("trimStart")?function(){return H$(this)}:"".trimStart});var aS=f(()=>{"use strict";var Q$=ie(),iS=wl();Q$({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==iS},{trimLeft:iS})});var nS=f(()=>{"use strict";aS();var G$=ie(),sS=wl();G$({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==sS},{trimStart:sS})});var uS=f((cq,oS)=>{"use strict";nS();var W$=Mt();oS.exports=W$("String","trimLeft")});var cS=f((dq,lS)=>{"use strict";var Y$=uS();lS.exports=Y$});var pS=f((pq,dS)=>{"use strict";var z$=cS();dS.exports=z$});var kS=f(()=>{"use strict"});var RS=f(()=>{"use strict"});var $S=f((N1,LS)=>{"use strict";var vM=Ve(),SM=tr(),yM=pe(),TM=yM("match");LS.exports=function(a){var e;return vM(a)&&((e=a[TM])!==void 0?!!e:SM(a)==="RegExp")}});var DS=f((F1,MS)=>{"use strict";var IM=nt();MS.exports=function(){var a=IM(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 OS=f((q1,VS)=>{"use strict";var EM=Ce(),xM=Ke(),PM=xi(),wM=DS(),CS=RegExp.prototype;VS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in CS)&&!xM(a,"flags")&&PM(CS,a)?EM(wM,a):e}});var _S=f((U1,BS)=>{"use strict";var Vl=se(),AM=Cr(),kM=Math.floor,Dl=Vl("".charAt),RM=Vl("".replace),Cl=Vl("".slice),LM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,$M=/\$([$&'`]|\d{1,2})/g;BS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=$M;return i!==void 0&&(i=AM(i),u=LM),RM(s,u,function(l,c){var d;switch(Dl(c,0)){case"$":return"$";case"&":return a;case"`":return Cl(e,0,t);case"'":return Cl(e,n);case"<":d=i[Cl(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=kM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Dl(c,1):r[h-1]+Dl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var qS=f(()=>{"use strict";var MM=ie(),DM=Ce(),Bl=se(),NS=$t(),CM=Z(),VM=Mr(),OM=$S(),ni=aa(),BM=wi(),_M=OS(),NM=_S(),FM=pe(),qM=ze(),UM=FM("replace"),HM=TypeError,Ol=Bl("".indexOf),jM=Bl("".replace),FS=Bl("".slice),QM=Math.max;MM({target:"String",proto:!0},{replaceAll:function(e,t){var r=NS(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!VM(e)){if(i=OM(e),i&&(s=ni(NS(_M(e))),!~Ol(s,"g")))throw new HM("`.replaceAll` does not allow non-global regexes");if(n=BM(e,UM),n)return DM(n,e,r,t);if(qM&&i)return jM(ni(r),e,t)}for(o=ni(r),u=ni(e),l=CM(t),l||(t=ni(t)),c=u.length,d=QM(1,c),p=Ol(o,u);p!==-1;)h=l?ni(t(u,p,o)):NM(u,o,p,[],void 0,t),b+=FS(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Ol(o,u,p+d);return m<o.length&&(b+=FS(o,m)),b}})});var HS=f((Q1,US)=>{"use strict";kS();RS();qS();var GM=Mt();US.exports=GM("String","replaceAll")});var QS=f((G1,jS)=>{"use strict";var WM=HS();jS.exports=WM});var WS=f((W1,GS)=>{"use strict";var YM=QS();GS.exports=YM});var zS=f((Y1,YS)=>{"use strict";var zM=Li(),KM=aa(),XM=$t(),JM=RangeError;YS.exports=function(e){var t=KM(XM(this)),r="",i=zM(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 ey=f((z1,ZS)=>{"use strict";var JS=se(),ZM=Oo(),KS=aa(),eD=zS(),tD=$t(),rD=JS(eD),iD=JS("".slice),aD=Math.ceil,XS=function(a){return function(e,t,r){var i=KS(tD(e)),s=ZM(t),n=i.length,o=r===void 0?" ":KS(r),u,l;return s<=n||o===""?i:(u=s-n,l=rD(o,aD(u/o.length)),l.length>u&&(l=iD(l,0,u)),a?i+l:l+i)}};ZS.exports={start:XS(!1),end:XS(!0)}});var ry=f((K1,ty)=>{"use strict";var sD=ir();ty.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(sD)});var iy=f(()=>{"use strict";var nD=ie(),oD=ey().start,uD=ry();nD({target:"String",proto:!0,forced:uD},{padStart:function(e){return oD(this,e,arguments.length>1?arguments[1]:void 0)}})});var sy=f((Z1,ay)=>{"use strict";iy();var lD=Mt();ay.exports=lD("String","padStart")});var oy=f((eH,ny)=>{"use strict";var cD=sy();ny.exports=cD});var ly=f((tH,uy)=>{"use strict";var dD=oy();uy.exports=dD});var ad="2.0.124-dev.30ad4406.0";var Te=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Te||{}),Lt=(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))(Lt||{});var fs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(fs||{}),ao=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(ao||{});var so=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(so||{}),yi=(r=>(r.TRAFFIC_SAVING="traffic_saving",r.HIGH_QUALITY="high_quality",r.UNKNOWN="unknown",r))(yi||{});var NT=_(Xe(),1);import{assertNever as rh,assertNonNullable as Ex,isNonNullable as ys,ValueSubject as _o,Subject as xx,Subscription as Px,merge as wx,observableFrom as Ax,fromEvent as Jp,map as Zp,tap as eh,filterChanged as kx,isNullable as No,ErrorCategory as th}from"@vkontakte/videoplayer-shared/es2015";var Xp=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 Ts=class{constructor(e){this.connection$=new _o(void 0);this.castState$=new _o("NOT_AVAILABLE");this.errorEvent$=new xx;this.realCastState$=new _o("NOT_AVAILABLE");this.subscription=new Px;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=ys((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||Xp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:th.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(){ys(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();No(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();No(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(Jp(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 rh(i.sessionState)}})).add(wx(Jp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(eh(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Zp(i=>i.castState)),Ax([r.getCastState()])).pipe(kx(),Zp(Rx),eh(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=ys(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Ex(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(No(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"?ys(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:th.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Rx=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 rh(a)}};var fc=_(Xe(),1),yT=_(qr(),1),TT=_(pu(),1);var ng=_(zs(),1);import{assertNever as Xb}from"@vkontakte/videoplayer-shared/es2015";var he=(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:Xb(t)}return a},Ks=(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:Xb(e)}};var P=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as BR,Subject as Xs,merge as Jb}from"@vkontakte/videoplayer-shared/es2015";var C=class{constructor(e){this.transitionStarted$=new Xs;this.transitionEnded$=new Xs;this.transitionUpdated$=new Xs;this.forceChanged$=new Xs;this.stateChangeStarted$=Jb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Jb(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||BR(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 Zb=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 Xr,assertNonNullable as cr,debounce as eg,ErrorCategory as tg,fromEvent as dr,isNonNullable as rg,map as ig,merge as ag,observableFrom as NR,Subject as FR,Subscription as Ju,timeout as qR,getHighestQuality as UR}from"@vkontakte/videoplayer-shared/es2015";var HR=5,jR=5,QR=500,sg=7e3,ji=class{constructor(e){this.subscription=new Ju;this.loadMediaTimeoutSubscription=new Ju;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:Xr(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:Xr(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:Xr(e)}break}default:Xr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Zb(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 Ju;this.subscription.add(e),this.subscription.add(ag(this.videoState.stateChangeStarted$.pipe(ig(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(ig(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 FR;e.add(i.pipe(eg(QR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(dr(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)>HR)&&i.next(o),s=o})),e.add(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(dr(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<jR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:Xr(n)}}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(dr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=ag(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,NR(["init"])).pipe(eg(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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"),P(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"),P(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"&&P(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];cr(c);let d=UR(Object.keys(c));cr(d);let p=c[d];cr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];cr(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];cr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];cr(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];cr(c),r=he(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:tg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Xr(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 rg(o)&&(n.metadata.title=o),rg(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(qR(sg).subscribe(()=>s(`timeout(${sg})`)))});(0,ng.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:tg.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var vl=_(Xe(),1);import{clearVideoElement as ug}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as GR}from"@vkontakte/videoplayer-shared/es2015";var og=a=>{try{a.pause(),a.playbackRate=0,GR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as WR,Subscription as YR}from"@vkontakte/videoplayer-shared/es2015";var Zu=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)}},el=window.WeakMap?new WeakMap:new Zu,tl=window.WeakMap?new WeakMap:new Map,zR=(a,e=20)=>{let t=0;return WR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ie=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?ug(t):(t=document.createElement("video"),a.appendChild(t)),el.set(t,r);let i=new YR;return i.add(zR(t,e)),tl.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Ee=a=>{let e=tl.get(a);e==null||e.unsubscribe(),tl.delete(a);let t=el.get(a);el.delete(a),t?ug(a):og(a)};var il=_(Jr(),1);import{assertNonNullable as Qi,isNonNullable as ut,isNullable as iL,fromEvent as Zr,merge as fg,observableFrom as bg,filterChanged as gg,map as Gi,Subject as vg,Subscription as aL,ValueSubject as sL,ErrorCategory as nL}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as rl,isNullable as tL,Subscription as rL}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=tL(i),l=new rL;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},ot=(a,e,t)=>Js(e,()=>a.loop,r=>{rl(r)&&(a.loop=r)},{onError:t}),xe=(a,e,t,r)=>Js(e,()=>({muted:a.muted,volume:a.volume}),i=>{rl(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}),Ne=(a,e,t,r)=>Js(e,()=>a.playbackRate,i=>{rl(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ct=Js;var oL=a=>["__",a.language,a.label].join("|"),uL=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},al=class a{constructor(e){this.available$=new vg;this.current$=new sL(void 0);this.error$=new vg;this.subscription=new aL;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:nL.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(Ct(t.internalTextTracks,()=>(0,il.default)(this.internalTracks),s=>{ut(s)&&this.setInternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Gi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Ct(t.externalTextTracks,()=>(0,il.default)(this.externalTracks),s=>{ut(s)&&this.setExternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Gi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Ct(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(Ct(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Qi(this.video);let{textTracks:e}=this.video;this.subscription.add(Zr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(fg(Zr(e,"addtrack"),Zr(e,"removetrack"),bg(["init"])).pipe(Gi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),gg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(fg(Zr(e,"change"),bg(["init"])).pipe(Gi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Gi(r=>r&&this.htmlTextTrackToITextTrack(r).id),gg()).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(Zr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Zr(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;ut(t.align)&&(i.align=t.align),ut(t.position)&&(i.position=t.position),ut(t.size)&&(i.size=t.size),ut(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Qi(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:oL(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){Qi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(iL(e)||!uL(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){Qi(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Qi(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)}},Fe=al;var ft=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 Sg=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},sl=a=>{let e=Sg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},yg=a=>{let e=Sg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as qe,map as Vt,merge as Ig,filterChanged as cL,isNonNullable as Eg,Subject as dL,filter as xg,mapTo as Pg,combine as pL,once as hL,ErrorCategory as mL,ValueSubject as wg,clientChecker as fL}from"@vkontakte/videoplayer-shared/es2015";var lL=3,Tg=(a,e,t=lL)=>{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 Pe=a=>{let e=y=>qe(a,y).pipe(Pg(void 0)),r=Ig(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>qe(a,y))).pipe(Vt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),cL()),i=Ig(qe(a,"progress"),qe(a,"timeupdate")).pipe(Vt(()=>Tg(a.buffered,a.currentTime))),s=fL.isSafari?pL({play:e("play").pipe(hL()),playing:e("playing")}).pipe(Pg(void 0)):e("playing"),n=qe(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=qe(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=qe(a,"error").pipe(xg(()=>!!(a.error||a.played.length)),Vt(()=>{var I;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:mL.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=qe(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new dL,d=.3,p;l.subscribe(y=>{a.loop&&Eg(p)&&Eg(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(xg(()=>!a.error&&p!==a.duration)),m=qe(a,"enterpictureinpicture"),b=qe(a,"leavepictureinpicture"),g=new wg(yg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new wg(sl(a));return qe(a,"fullscreenchange").pipe(Vt(()=>sl(a))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:qe(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as Ot}from"@vkontakte/videoplayer-shared/es2015";var Bt=a=>{switch(a){case"mobile":return Ot.Q_144P;case"lowest":return Ot.Q_240P;case"low":return Ot.Q_360P;case"sd":case"medium":return Ot.Q_480P;case"hd":case"high":return Ot.Q_720P;case"fullhd":case"full":return Ot.Q_1080P;case"quadhd":case"quad":return Ot.Q_1440P;case"ultrahd":case"ultra":return Ot.Q_2160P}};var _t=_(ei(),1),Ng=_(Xe(),1),en=_(qr(),1);import{isNonNullable as ne,isNullable as ol,now as Fg,isHigher as ul,isHigherOrEqual as ll,isInvariantQuality as Og,isLower as Bg,isLowerOrEqual as cl,videoSizeToQuality as xL,assertNotEmptyArray as qg,assertNonNullable as PL}from"@vkontakte/videoplayer-shared/es2015";var nl=!1,bt={},Dg=a=>{nl=a},Cg=()=>{bt={}},Vg=a=>{a(bt)},Wi=(a,e)=>{var t;nl&&(bt.meta=(t=bt.meta)!=null?t:{},bt.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var r,i;if(!nl)return;bt.series=(r=bt.series)!=null?r:{};let t=(i=bt.series[this.name])!=null?i:[];t.push([Date.now(),e]),bt.series[this.name]=t}};function Zs({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}var wL=new ve("best_bitrate"),Ug=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var dl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Yi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Fg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Hg='Assertion "ABR Tracks is empty array" failed',tn=(a,e,t,r)=>{var u;let i=[...e].sort(dl(1)),s=[...t].sort(dl(1)),n=s.filter(l=>ne(l.bitrate)&&ne(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,_t.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,_t.default)(s,-1);return o&&(0,Ng.default)(n,o)?o:n.length?(0,_t.default)(n,-1):(0,_t.default)(s,0)},_g=a=>"quality"in a,jg=(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]&&Fg()-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=_g(o)?"video":"audio",l=_g(o)?o.quality:o.bitrate;return e({message:`
6
+ var GT=Object.create;var Zn=Object.defineProperty,QT=Object.defineProperties,WT=Object.getOwnPropertyDescriptor,YT=Object.getOwnPropertyDescriptors,zT=Object.getOwnPropertyNames,hs=Object.getOwnPropertySymbols,KT=Object.getPrototypeOf,eo=Object.prototype.hasOwnProperty,Zc=Object.prototype.propertyIsEnumerable;var XT=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,Jc=(a,e,t)=>e in a?Zn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,I=(a,e)=>{for(var t in e||(e={}))eo.call(e,t)&&Jc(a,t,e[t]);if(hs)for(var t of hs(e))Zc.call(e,t)&&Jc(a,t,e[t]);return a},$=(a,e)=>QT(a,YT(e));var ed=(a,e)=>{var t={};for(var r in a)eo.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&hs)for(var r of hs(a))e.indexOf(r)<0&&Zc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var JT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of zT(e))!eo.call(a,i)&&i!==t&&Zn(a,i,{get:()=>e[i],enumerable:!(r=WT(e,i))||r.enumerable});return a};var B=(a,e,t)=>(t=a!=null?GT(KT(a)):{},JT(e||!a||!a.__esModule?Zn(t,"default",{value:a,enumerable:!0}):t,a));var w=(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())}),fs=function(a,e){this[0]=a,this[1]=e},ae=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof fs,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[XT("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var re=m((io,rd)=>{"use strict";var Ti=function(a){return a&&a.Math===Math&&a};rd.exports=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof global=="object"&&global)||Ti(typeof io=="object"&&io)||function(){return this}()||Function("return this")()});var pe=m((A0,id)=>{"use strict";id.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ii=m((k0,ad)=>{"use strict";var ZT=pe();ad.exports=!ZT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var ao=m((R0,ud)=>{"use strict";var eI=Ii(),od=Function.prototype,sd=od.apply,nd=od.call;ud.exports=typeof Reflect=="object"&&Reflect.apply||(eI?nd.bind(sd):function(){return nd.apply(sd,arguments)})});var ne=m(($0,dd)=>{"use strict";var ld=Ii(),cd=Function.prototype,so=cd.call,tI=ld&&cd.bind.bind(so,so);dd.exports=ld?tI:function(a){return function(){return so.apply(a,arguments)}}});var ir=m((L0,hd)=>{"use strict";var pd=ne(),rI=pd({}.toString),iI=pd("".slice);hd.exports=function(a){return iI(rI(a),8,-1)}});var no=m((M0,fd)=>{"use strict";var aI=ir(),sI=ne();fd.exports=function(a){if(aI(a)==="Function")return sI(a)}});var ee=m((D0,md)=>{"use strict";var oo=typeof document=="object"&&document.all;md.exports=typeof oo=="undefined"&&oo!==void 0?function(a){return typeof a=="function"||a===oo}:function(a){return typeof a=="function"}});var Me=m((C0,bd)=>{"use strict";var nI=pe();bd.exports=!nI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var De=m((O0,gd)=>{"use strict";var oI=Ii(),bs=Function.prototype.call;gd.exports=oI?bs.bind(bs):function(){return bs.apply(bs,arguments)}});var uo=m(yd=>{"use strict";var vd={}.propertyIsEnumerable,Sd=Object.getOwnPropertyDescriptor,uI=Sd&&!vd.call({1:2},1);yd.f=uI?function(e){var t=Sd(this,e);return!!t&&t.enumerable}:vd});var Ei=m((B0,Td)=>{"use strict";Td.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Ed=m((_0,Id)=>{"use strict";var lI=ne(),cI=pe(),dI=ir(),lo=Object,pI=lI("".split);Id.exports=cI(function(){return!lo("z").propertyIsEnumerable(0)})?function(a){return dI(a)==="String"?pI(a,""):lo(a)}:lo});var Dr=m((N0,xd)=>{"use strict";xd.exports=function(a){return a==null}});var Mt=m((F0,Pd)=>{"use strict";var hI=Dr(),fI=TypeError;Pd.exports=function(a){if(hI(a))throw new fI("Can't call method on "+a);return a}});var ar=m((q0,wd)=>{"use strict";var mI=Ed(),bI=Mt();wd.exports=function(a){return mI(bI(a))}});var Ce=m((U0,Ad)=>{"use strict";var gI=ee();Ad.exports=function(a){return typeof a=="object"?a!==null:gI(a)}});var Cr=m((H0,kd)=>{"use strict";kd.exports={}});var pt=m((j0,$d)=>{"use strict";var co=Cr(),po=re(),vI=ee(),Rd=function(a){return vI(a)?a:void 0};$d.exports=function(a,e){return arguments.length<2?Rd(co[a])||Rd(po[a]):co[a]&&co[a][e]||po[a]&&po[a][e]}});var xi=m((G0,Ld)=>{"use strict";var SI=ne();Ld.exports=SI({}.isPrototypeOf)});var sr=m((Q0,Cd)=>{"use strict";var yI=re(),Md=yI.navigator,Dd=Md&&Md.userAgent;Cd.exports=Dd?String(Dd):""});var fo=m((W0,Fd)=>{"use strict";var Nd=re(),ho=sr(),Od=Nd.process,Vd=Nd.Deno,Bd=Od&&Od.versions||Vd&&Vd.version,_d=Bd&&Bd.v8,Ye,gs;_d&&(Ye=_d.split("."),gs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!gs&&ho&&(Ye=ho.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=ho.match(/Chrome\/(\d+)/),Ye&&(gs=+Ye[1])));Fd.exports=gs});var mo=m((Y0,Ud)=>{"use strict";var qd=fo(),TI=pe(),II=re(),EI=II.String;Ud.exports=!!Object.getOwnPropertySymbols&&!TI(function(){var a=Symbol("symbol detection");return!EI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&qd&&qd<41})});var bo=m((z0,Hd)=>{"use strict";var xI=mo();Hd.exports=xI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var go=m((K0,jd)=>{"use strict";var PI=pt(),wI=ee(),AI=xi(),kI=bo(),RI=Object;jd.exports=kI?function(a){return typeof a=="symbol"}:function(a){var e=PI("Symbol");return wI(e)&&AI(e.prototype,RI(a))}});var Pi=m((X0,Gd)=>{"use strict";var $I=String;Gd.exports=function(a){try{return $I(a)}catch(e){return"Object"}}});var st=m((J0,Qd)=>{"use strict";var LI=ee(),MI=Pi(),DI=TypeError;Qd.exports=function(a){if(LI(a))return a;throw new DI(MI(a)+" is not a function")}});var wi=m((Z0,Wd)=>{"use strict";var CI=st(),OI=Dr();Wd.exports=function(a,e){var t=a[e];return OI(t)?void 0:CI(t)}});var zd=m((eO,Yd)=>{"use strict";var vo=De(),So=ee(),yo=Ce(),VI=TypeError;Yd.exports=function(a,e){var t,r;if(e==="string"&&So(t=a.toString)&&!yo(r=vo(t,a))||So(t=a.valueOf)&&!yo(r=vo(t,a))||e!=="string"&&So(t=a.toString)&&!yo(r=vo(t,a)))return r;throw new VI("Can't convert object to primitive value")}});var ze=m((tO,Kd)=>{"use strict";Kd.exports=!0});var Zd=m((rO,Jd)=>{"use strict";var Xd=re(),BI=Object.defineProperty;Jd.exports=function(a,e){try{BI(Xd,a,{value:e,configurable:!0,writable:!0})}catch(t){Xd[a]=e}return e}});var Ai=m((iO,rp)=>{"use strict";var _I=ze(),NI=re(),FI=Zd(),ep="__core-js_shared__",tp=rp.exports=NI[ep]||FI(ep,{});(tp.versions||(tp.versions=[])).push({version:"3.38.0",mode:_I?"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 To=m((aO,ap)=>{"use strict";var ip=Ai();ap.exports=function(a,e){return ip[a]||(ip[a]=e||{})}});var Or=m((sO,sp)=>{"use strict";var qI=Mt(),UI=Object;sp.exports=function(a){return UI(qI(a))}});var Ke=m((nO,np)=>{"use strict";var HI=ne(),jI=Or(),GI=HI({}.hasOwnProperty);np.exports=Object.hasOwn||function(e,t){return GI(jI(e),t)}});var Io=m((oO,op)=>{"use strict";var QI=ne(),WI=0,YI=Math.random(),zI=QI(1 .toString);op.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+zI(++WI+YI,36)}});var he=m((uO,lp)=>{"use strict";var KI=re(),XI=To(),up=Ke(),JI=Io(),ZI=mo(),eE=bo(),Vr=KI.Symbol,Eo=XI("wks"),tE=eE?Vr.for||Vr:Vr&&Vr.withoutSetter||JI;lp.exports=function(a){return up(Eo,a)||(Eo[a]=ZI&&up(Vr,a)?Vr[a]:tE("Symbol."+a)),Eo[a]}});var hp=m((lO,pp)=>{"use strict";var rE=De(),cp=Ce(),dp=go(),iE=wi(),aE=zd(),sE=he(),nE=TypeError,oE=sE("toPrimitive");pp.exports=function(a,e){if(!cp(a)||dp(a))return a;var t=iE(a,oE),r;if(t){if(e===void 0&&(e="default"),r=rE(t,a,e),!cp(r)||dp(r))return r;throw new nE("Can't convert object to primitive value")}return e===void 0&&(e="number"),aE(a,e)}});var xo=m((cO,fp)=>{"use strict";var uE=hp(),lE=go();fp.exports=function(a){var e=uE(a,"string");return lE(e)?e:e+""}});var vs=m((dO,bp)=>{"use strict";var cE=re(),mp=Ce(),Po=cE.document,dE=mp(Po)&&mp(Po.createElement);bp.exports=function(a){return dE?Po.createElement(a):{}}});var wo=m((pO,gp)=>{"use strict";var pE=Me(),hE=pe(),fE=vs();gp.exports=!pE&&!hE(function(){return Object.defineProperty(fE("div"),"a",{get:function(){return 7}}).a!==7})});var yp=m(Sp=>{"use strict";var mE=Me(),bE=De(),gE=uo(),vE=Ei(),SE=ar(),yE=xo(),TE=Ke(),IE=wo(),vp=Object.getOwnPropertyDescriptor;Sp.f=mE?vp:function(e,t){if(e=SE(e),t=yE(t),IE)try{return vp(e,t)}catch(r){}if(TE(e,t))return vE(!bE(gE.f,e,t),e[t])}});var Ao=m((fO,Tp)=>{"use strict";var EE=pe(),xE=ee(),PE=/#|\.prototype\./,ki=function(a,e){var t=AE[wE(a)];return t===RE?!0:t===kE?!1:xE(e)?EE(e):!!e},wE=ki.normalize=function(a){return String(a).replace(PE,".").toLowerCase()},AE=ki.data={},kE=ki.NATIVE="N",RE=ki.POLYFILL="P";Tp.exports=ki});var Br=m((mO,Ep)=>{"use strict";var Ip=no(),$E=st(),LE=Ii(),ME=Ip(Ip.bind);Ep.exports=function(a,e){return $E(a),e===void 0?a:LE?ME(a,e):function(){return a.apply(e,arguments)}}});var ko=m((bO,xp)=>{"use strict";var DE=Me(),CE=pe();xp.exports=DE&&CE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=m((gO,Pp)=>{"use strict";var OE=Ce(),VE=String,BE=TypeError;Pp.exports=function(a){if(OE(a))return a;throw new BE(VE(a)+" is not an object")}});var nr=m(Ap=>{"use strict";var _E=Me(),NE=wo(),FE=ko(),Ss=nt(),wp=xo(),qE=TypeError,Ro=Object.defineProperty,UE=Object.getOwnPropertyDescriptor,$o="enumerable",Lo="configurable",Mo="writable";Ap.f=_E?FE?function(e,t,r){if(Ss(e),t=wp(t),Ss(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Mo in r&&!r[Mo]){var i=UE(e,t);i&&i[Mo]&&(e[t]=r.value,r={configurable:Lo in r?r[Lo]:i[Lo],enumerable:$o in r?r[$o]:i[$o],writable:!1})}return Ro(e,t,r)}:Ro:function(e,t,r){if(Ss(e),t=wp(t),Ss(r),NE)try{return Ro(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new qE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var _r=m((SO,kp)=>{"use strict";var HE=Me(),jE=nr(),GE=Ei();kp.exports=HE?function(a,e,t){return jE.f(a,e,GE(1,t))}:function(a,e,t){return a[e]=t,a}});var se=m((yO,$p)=>{"use strict";var Ri=re(),QE=ao(),WE=no(),YE=ee(),zE=yp().f,KE=Ao(),Nr=Cr(),XE=Br(),Fr=_r(),Rp=Ke();Ai();var JE=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};$p.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?Ri:i?Ri[t]:Ri[t]&&Ri[t].prototype,o=r?Nr:Nr[t]||Fr(Nr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,v;for(p in e)l=KE(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Rp(n,p),f=o[p],c&&(a.dontCallGetSet?(v=zE(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=XE(h,Ri):a.wrap&&c?g=JE(h):s&&YE(h)?g=WE(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Fr(g,"sham",!0),Fr(o,p,g),s&&(d=t+"Prototype",Rp(Nr,d)||Fr(Nr,d,{}),Fr(Nr[d],p,h),a.real&&u&&(l||!u[p])&&Fr(u,p,h)))}});var Mp=m((TO,Lp)=>{"use strict";var ZE=Math.ceil,ex=Math.floor;Lp.exports=Math.trunc||function(e){var t=+e;return(t>0?ex:ZE)(t)}});var $i=m((IO,Dp)=>{"use strict";var tx=Mp();Dp.exports=function(a){var e=+a;return e!==e||e===0?0:tx(e)}});var Op=m((EO,Cp)=>{"use strict";var rx=$i(),ix=Math.max,ax=Math.min;Cp.exports=function(a,e){var t=rx(a);return t<0?ix(t+e,0):ax(t,e)}});var Do=m((xO,Vp)=>{"use strict";var sx=$i(),nx=Math.min;Vp.exports=function(a){var e=sx(a);return e>0?nx(e,9007199254740991):0}});var qr=m((PO,Bp)=>{"use strict";var ox=Do();Bp.exports=function(a){return ox(a.length)}});var Co=m((wO,Np)=>{"use strict";var ux=ar(),lx=Op(),cx=qr(),_p=function(a){return function(e,t,r){var i=ux(e),s=cx(i);if(s===0)return!a&&-1;var n=lx(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}};Np.exports={includes:_p(!0),indexOf:_p(!1)}});var Li=m((AO,Fp)=>{"use strict";Fp.exports=function(){}});var qp=m(()=>{"use strict";var dx=se(),px=Co().includes,hx=pe(),fx=Li(),mx=hx(function(){return!Array(1).includes()});dx({target:"Array",proto:!0,forced:mx},{includes:function(e){return px(this,e,arguments.length>1?arguments[1]:void 0)}});fx("includes")});var Dt=m(($O,Up)=>{"use strict";var bx=pt();Up.exports=bx});var jp=m((LO,Hp)=>{"use strict";qp();var gx=Dt();Hp.exports=gx("Array","includes")});var Qp=m((MO,Gp)=>{"use strict";var vx=jp();Gp.exports=vx});var Xe=m((DO,Wp)=>{"use strict";var Sx=Qp();Wp.exports=Sx});var Is=m((GO,th)=>{"use strict";var Ax=To(),kx=Io(),eh=Ax("keys");th.exports=function(a){return eh[a]||(eh[a]=kx(a))}});var ih=m((QO,rh)=>{"use strict";var Rx=pe();rh.exports=!Rx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Es=m((WO,sh)=>{"use strict";var $x=Ke(),Lx=ee(),Mx=Or(),Dx=Is(),Cx=ih(),ah=Dx("IE_PROTO"),Bo=Object,Ox=Bo.prototype;sh.exports=Cx?Bo.getPrototypeOf:function(a){var e=Mx(a);if($x(e,ah))return e[ah];var t=e.constructor;return Lx(t)&&e instanceof t?t.prototype:e instanceof Bo?Ox:null}});var xs=m((YO,nh)=>{"use strict";nh.exports={}});var lh=m((zO,uh)=>{"use strict";var Vx=ne(),_o=Ke(),Bx=ar(),_x=Co().indexOf,Nx=xs(),oh=Vx([].push);uh.exports=function(a,e){var t=Bx(a),r=0,i=[],s;for(s in t)!_o(Nx,s)&&_o(t,s)&&oh(i,s);for(;e.length>r;)_o(t,s=e[r++])&&(~_x(i,s)||oh(i,s));return i}});var No=m((KO,ch)=>{"use strict";ch.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var Fo=m((XO,dh)=>{"use strict";var Fx=lh(),qx=No();dh.exports=Object.keys||function(e){return Fx(e,qx)}});var qo=m((JO,bh)=>{"use strict";var hh=Me(),Ux=pe(),fh=ne(),Hx=Es(),jx=Fo(),Gx=ar(),Qx=uo().f,mh=fh(Qx),Wx=fh([].push),Yx=hh&&Ux(function(){var a=Object.create(null);return a[2]=2,!mh(a,2)}),ph=function(a){return function(e){for(var t=Gx(e),r=jx(t),i=Yx&&Hx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!hh||(i?u in t:mh(t,u)))&&Wx(o,a?[u,t[u]]:t[u]);return o}};bh.exports={entries:ph(!0),values:ph(!1)}});var gh=m(()=>{"use strict";var zx=se(),Kx=qo().entries;zx({target:"Object",stat:!0},{entries:function(e){return Kx(e)}})});var Sh=m((tV,vh)=>{"use strict";gh();var Xx=Cr();vh.exports=Xx.Object.entries});var Th=m((rV,yh)=>{"use strict";var Jx=Sh();yh.exports=Jx});var Ur=m((iV,Ih)=>{"use strict";var Zx=Th();Ih.exports=Zx});var or=m((aV,Eh)=>{"use strict";Eh.exports={}});var wh=m((sV,Ph)=>{"use strict";var eP=re(),tP=ee(),xh=eP.WeakMap;Ph.exports=tP(xh)&&/native code/.test(String(xh))});var Go=m((nV,Rh)=>{"use strict";var rP=wh(),kh=re(),iP=Ce(),aP=_r(),Uo=Ke(),Ho=Ai(),sP=Is(),nP=xs(),Ah="Object already initialized",jo=kh.TypeError,oP=kh.WeakMap,Ps,Mi,ws,uP=function(a){return ws(a)?Mi(a):Ps(a,{})},lP=function(a){return function(e){var t;if(!iP(e)||(t=Mi(e)).type!==a)throw new jo("Incompatible receiver, "+a+" required");return t}};rP||Ho.state?(Je=Ho.state||(Ho.state=new oP),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,Ps=function(a,e){if(Je.has(a))throw new jo(Ah);return e.facade=a,Je.set(a,e),e},Mi=function(a){return Je.get(a)||{}},ws=function(a){return Je.has(a)}):(ur=sP("state"),nP[ur]=!0,Ps=function(a,e){if(Uo(a,ur))throw new jo(Ah);return e.facade=a,aP(a,ur,e),e},Mi=function(a){return Uo(a,ur)?a[ur]:{}},ws=function(a){return Uo(a,ur)});var Je,ur;Rh.exports={set:Ps,get:Mi,has:ws,enforce:uP,getterFor:lP}});var Yo=m((oV,Lh)=>{"use strict";var Qo=Me(),cP=Ke(),$h=Function.prototype,dP=Qo&&Object.getOwnPropertyDescriptor,Wo=cP($h,"name"),pP=Wo&&function(){}.name==="something",hP=Wo&&(!Qo||Qo&&dP($h,"name").configurable);Lh.exports={EXISTS:Wo,PROPER:pP,CONFIGURABLE:hP}});var Dh=m(Mh=>{"use strict";var fP=Me(),mP=ko(),bP=nr(),gP=nt(),vP=ar(),SP=Fo();Mh.f=fP&&!mP?Object.defineProperties:function(e,t){gP(e);for(var r=vP(t),i=SP(t),s=i.length,n=0,o;s>n;)bP.f(e,o=i[n++],r[o]);return e}});var zo=m((lV,Ch)=>{"use strict";var yP=pt();Ch.exports=yP("document","documentElement")});var Zo=m((cV,qh)=>{"use strict";var TP=nt(),IP=Dh(),Oh=No(),EP=xs(),xP=zo(),PP=vs(),wP=Is(),Vh=">",Bh="<",Xo="prototype",Jo="script",Nh=wP("IE_PROTO"),Ko=function(){},Fh=function(a){return Bh+Jo+Vh+a+Bh+"/"+Jo+Vh},_h=function(a){a.write(Fh("")),a.close();var e=a.parentWindow.Object;return a=null,e},AP=function(){var a=PP("iframe"),e="java"+Jo+":",t;return a.style.display="none",xP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Fh("document.F=Object")),t.close(),t.F},As,ks=function(){try{As=new ActiveXObject("htmlfile")}catch(e){}ks=typeof document!="undefined"?document.domain&&As?_h(As):AP():_h(As);for(var a=Oh.length;a--;)delete ks[Xo][Oh[a]];return ks()};EP[Nh]=!0;qh.exports=Object.create||function(e,t){var r;return e!==null?(Ko[Xo]=TP(e),r=new Ko,Ko[Xo]=null,r[Nh]=e):r=ks(),t===void 0?r:IP.f(r,t)}});var Hr=m((dV,Uh)=>{"use strict";var kP=_r();Uh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:kP(a,e,t),a}});var iu=m((pV,Gh)=>{"use strict";var RP=pe(),$P=ee(),LP=Ce(),MP=Zo(),Hh=Es(),DP=Hr(),CP=he(),OP=ze(),ru=CP("iterator"),jh=!1,ht,eu,tu;[].keys&&(tu=[].keys(),"next"in tu?(eu=Hh(Hh(tu)),eu!==Object.prototype&&(ht=eu)):jh=!0);var VP=!LP(ht)||RP(function(){var a={};return ht[ru].call(a)!==a});VP?ht={}:OP&&(ht=MP(ht));$P(ht[ru])||DP(ht,ru,function(){return this});Gh.exports={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:jh}});var Rs=m((hV,Wh)=>{"use strict";var BP=he(),_P=BP("toStringTag"),Qh={};Qh[_P]="z";Wh.exports=String(Qh)==="[object z]"});var Di=m((fV,Yh)=>{"use strict";var NP=Rs(),FP=ee(),$s=ir(),qP=he(),UP=qP("toStringTag"),HP=Object,jP=$s(function(){return arguments}())==="Arguments",GP=function(a,e){try{return a[e]}catch(t){}};Yh.exports=NP?$s:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=GP(e=HP(a),UP))=="string"?t:jP?$s(e):(r=$s(e))==="Object"&&FP(e.callee)?"Arguments":r}});var Kh=m((mV,zh)=>{"use strict";var QP=Rs(),WP=Di();zh.exports=QP?{}.toString:function(){return"[object "+WP(this)+"]"}});var Ci=m((bV,Jh)=>{"use strict";var YP=Rs(),zP=nr().f,KP=_r(),XP=Ke(),JP=Kh(),ZP=he(),Xh=ZP("toStringTag");Jh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(XP(i,Xh)||zP(i,Xh,{configurable:!0,value:e}),r&&!YP&&KP(i,"toString",JP))}});var ef=m((gV,Zh)=>{"use strict";var ew=iu().IteratorPrototype,tw=Zo(),rw=Ei(),iw=Ci(),aw=or(),sw=function(){return this};Zh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=tw(ew,{next:rw(+!r,t)}),iw(a,i,!1,!0),aw[i]=sw,a}});var rf=m((vV,tf)=>{"use strict";var nw=ne(),ow=st();tf.exports=function(a,e,t){try{return nw(ow(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var sf=m((SV,af)=>{"use strict";var uw=Ce();af.exports=function(a){return uw(a)||a===null}});var of=m((yV,nf)=>{"use strict";var lw=sf(),cw=String,dw=TypeError;nf.exports=function(a){if(lw(a))return a;throw new dw("Can't set "+cw(a)+" as a prototype")}});var au=m((TV,uf)=>{"use strict";var pw=rf(),hw=Ce(),fw=Mt(),mw=of();uf.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=pw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return fw(i),mw(s),hw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var Sf=m((IV,vf)=>{"use strict";var bw=se(),gw=De(),Ls=ze(),bf=Yo(),vw=ee(),Sw=ef(),lf=Es(),cf=au(),yw=Ci(),Tw=_r(),su=Hr(),Iw=he(),df=or(),gf=iu(),Ew=bf.PROPER,xw=bf.CONFIGURABLE,pf=gf.IteratorPrototype,Ms=gf.BUGGY_SAFARI_ITERATORS,Oi=Iw("iterator"),hf="keys",Vi="values",ff="entries",mf=function(){return this};vf.exports=function(a,e,t,r,i,s,n){Sw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!Ms&&v&&v in c)return c[v];switch(v){case hf:return function(){return new t(this,v)};case Vi:return function(){return new t(this,v)};case ff:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Oi]||c["@@iterator"]||i&&c[i],p=!Ms&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=lf(h.call(new a)),f!==Object.prototype&&f.next&&(!Ls&&lf(f)!==pf&&(cf?cf(f,pf):vw(f[Oi])||su(f,Oi,mf)),yw(f,u,!0,!0),Ls&&(df[u]=mf))),Ew&&i===Vi&&d&&d.name!==Vi&&(!Ls&&xw?Tw(c,"name",Vi):(l=!0,p=function(){return gw(d,this)})),i)if(b={values:o(Vi),keys:s?p:o(hf),entries:o(ff)},n)for(g in b)(Ms||l||!(g in c))&&su(c,g,b[g]);else bw({target:e,proto:!0,forced:Ms||l},b);return(!Ls||n)&&c[Oi]!==p&&su(c,Oi,p,{name:i}),df[e]=p,b}});var Tf=m((EV,yf)=>{"use strict";yf.exports=function(a,e){return{value:a,done:e}}});var ou=m((xV,wf)=>{"use strict";var Pw=ar(),nu=Li(),If=or(),xf=Go(),ww=nr().f,Aw=Sf(),Ds=Tf(),kw=ze(),Rw=Me(),Pf="Array Iterator",$w=xf.set,Lw=xf.getterFor(Pf);wf.exports=Aw(Array,"Array",function(a,e){$w(this,{type:Pf,target:Pw(a),index:0,kind:e})},function(){var a=Lw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ds(void 0,!0);switch(a.kind){case"keys":return Ds(t,!1);case"values":return Ds(e[t],!1)}return Ds([t,e[t]],!1)},"values");var Ef=If.Arguments=If.Array;nu("keys");nu("values");nu("entries");if(!kw&&Rw&&Ef.name!=="values")try{ww(Ef,"name",{value:"values"})}catch(a){}});var kf=m((PV,Af)=>{"use strict";var Mw=he(),Dw=or(),Cw=Mw("iterator"),Ow=Array.prototype;Af.exports=function(a){return a!==void 0&&(Dw.Array===a||Ow[Cw]===a)}});var uu=m((wV,$f)=>{"use strict";var Vw=Di(),Rf=wi(),Bw=Dr(),_w=or(),Nw=he(),Fw=Nw("iterator");$f.exports=function(a){if(!Bw(a))return Rf(a,Fw)||Rf(a,"@@iterator")||_w[Vw(a)]}});var Mf=m((AV,Lf)=>{"use strict";var qw=De(),Uw=st(),Hw=nt(),jw=Pi(),Gw=uu(),Qw=TypeError;Lf.exports=function(a,e){var t=arguments.length<2?Gw(a):e;if(Uw(t))return Hw(qw(t,a));throw new Qw(jw(a)+" is not iterable")}});var Of=m((kV,Cf)=>{"use strict";var Ww=De(),Df=nt(),Yw=wi();Cf.exports=function(a,e,t){var r,i;Df(a);try{if(r=Yw(a,"return"),!r){if(e==="throw")throw t;return t}r=Ww(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Df(r),t}});var Os=m((RV,Nf)=>{"use strict";var zw=Br(),Kw=De(),Xw=nt(),Jw=Pi(),Zw=kf(),eA=qr(),Vf=xi(),tA=Mf(),rA=uu(),Bf=Of(),iA=TypeError,Cs=function(a,e){this.stopped=a,this.result=e},_f=Cs.prototype;Nf.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=zw(e,r),l,c,d,p,h,f,b,g=function(S){return l&&Bf(l,"normal",S),new Cs(!0,S)},v=function(S){return i?(Xw(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=rA(a),!c)throw new iA(Jw(a)+" is not iterable");if(Zw(c)){for(d=0,p=eA(a);p>d;d++)if(h=v(a[d]),h&&Vf(_f,h))return h;return new Cs(!1)}l=tA(a,c)}for(f=s?a.next:l.next;!(b=Kw(f,l)).done;){try{h=v(b.value)}catch(S){Bf(l,"throw",S)}if(typeof h=="object"&&h&&Vf(_f,h))return h}return new Cs(!1)}});var qf=m(($V,Ff)=>{"use strict";var aA=Me(),sA=nr(),nA=Ei();Ff.exports=function(a,e,t){aA?sA.f(a,e,nA(0,t)):a[e]=t}});var Uf=m(()=>{"use strict";var oA=se(),uA=Os(),lA=qf();oA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return uA(e,function(r,i){lA(t,r,i)},{AS_ENTRIES:!0}),t}})});var jf=m((DV,Hf)=>{"use strict";ou();Uf();var cA=Cr();Hf.exports=cA.Object.fromEntries});var Qf=m((CV,Gf)=>{"use strict";Gf.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 Yf=m(()=>{"use strict";ou();var dA=Qf(),pA=re(),hA=Ci(),Wf=or();for(Vs in dA)hA(pA[Vs],Vs),Wf[Vs]=Wf.Array;var Vs});var Kf=m((BV,zf)=>{"use strict";var fA=jf();Yf();zf.exports=fA});var lu=m((_V,Xf)=>{"use strict";var mA=Kf();Xf.exports=mA});var Jf=m(()=>{"use strict"});var cu=m((qV,Zf)=>{"use strict";var Bi=re(),bA=sr(),gA=ir(),Bs=function(a){return bA.slice(0,a.length)===a};Zf.exports=function(){return Bs("Bun/")?"BUN":Bs("Cloudflare-Workers")?"CLOUDFLARE":Bs("Deno/")?"DENO":Bs("Node.js/")?"NODE":Bi.Bun&&typeof Bun.version=="string"?"BUN":Bi.Deno&&typeof Deno.version=="object"?"DENO":gA(Bi.process)==="process"?"NODE":Bi.window&&Bi.document?"BROWSER":"REST"}()});var _s=m((UV,em)=>{"use strict";var vA=cu();em.exports=vA==="NODE"});var rm=m((HV,tm)=>{"use strict";var SA=nr();tm.exports=function(a,e,t){return SA.f(a,e,t)}});var sm=m((jV,am)=>{"use strict";var yA=pt(),TA=rm(),IA=he(),EA=Me(),im=IA("species");am.exports=function(a){var e=yA(a);EA&&e&&!e[im]&&TA(e,im,{configurable:!0,get:function(){return this}})}});var om=m((GV,nm)=>{"use strict";var xA=xi(),PA=TypeError;nm.exports=function(a,e){if(xA(e,a))return a;throw new PA("Incorrect invocation")}});var pu=m((QV,um)=>{"use strict";var wA=ne(),AA=ee(),du=Ai(),kA=wA(Function.toString);AA(du.inspectSource)||(du.inspectSource=function(a){return kA(a)});um.exports=du.inspectSource});var fu=m((WV,hm)=>{"use strict";var RA=ne(),$A=pe(),lm=ee(),LA=Di(),MA=pt(),DA=pu(),cm=function(){},dm=MA("Reflect","construct"),hu=/^\s*(?:class|function)\b/,CA=RA(hu.exec),OA=!hu.test(cm),_i=function(e){if(!lm(e))return!1;try{return dm(cm,[],e),!0}catch(t){return!1}},pm=function(e){if(!lm(e))return!1;switch(LA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return OA||!!CA(hu,DA(e))}catch(t){return!0}};pm.sham=!0;hm.exports=!dm||$A(function(){var a;return _i(_i.call)||!_i(Object)||!_i(function(){a=!0})||a})?pm:_i});var mm=m((YV,fm)=>{"use strict";var VA=fu(),BA=Pi(),_A=TypeError;fm.exports=function(a){if(VA(a))return a;throw new _A(BA(a)+" is not a constructor")}});var mu=m((zV,gm)=>{"use strict";var bm=nt(),NA=mm(),FA=Dr(),qA=he(),UA=qA("species");gm.exports=function(a,e){var t=bm(a).constructor,r;return t===void 0||FA(r=bm(t)[UA])?e:NA(r)}});var Sm=m((KV,vm)=>{"use strict";var HA=ne();vm.exports=HA([].slice)});var Tm=m((XV,ym)=>{"use strict";var jA=TypeError;ym.exports=function(a,e){if(a<e)throw new jA("Not enough arguments");return a}});var bu=m((JV,Im)=>{"use strict";var GA=sr();Im.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(GA)});var Pu=m((ZV,Lm)=>{"use strict";var Oe=re(),QA=ao(),WA=Br(),Em=ee(),YA=Ke(),$m=pe(),xm=zo(),zA=Sm(),Pm=vs(),KA=Tm(),XA=bu(),JA=_s(),Iu=Oe.setImmediate,Eu=Oe.clearImmediate,ZA=Oe.process,gu=Oe.Dispatch,ek=Oe.Function,wm=Oe.MessageChannel,tk=Oe.String,vu=0,Ni={},Am="onreadystatechange",Fi,lr,Su,yu;$m(function(){Fi=Oe.location});var xu=function(a){if(YA(Ni,a)){var e=Ni[a];delete Ni[a],e()}},Tu=function(a){return function(){xu(a)}},km=function(a){xu(a.data)},Rm=function(a){Oe.postMessage(tk(a),Fi.protocol+"//"+Fi.host)};(!Iu||!Eu)&&(Iu=function(e){KA(arguments.length,1);var t=Em(e)?e:ek(e),r=zA(arguments,1);return Ni[++vu]=function(){QA(t,void 0,r)},lr(vu),vu},Eu=function(e){delete Ni[e]},JA?lr=function(a){ZA.nextTick(Tu(a))}:gu&&gu.now?lr=function(a){gu.now(Tu(a))}:wm&&!XA?(Su=new wm,yu=Su.port2,Su.port1.onmessage=km,lr=WA(yu.postMessage,yu)):Oe.addEventListener&&Em(Oe.postMessage)&&!Oe.importScripts&&Fi&&Fi.protocol!=="file:"&&!$m(Rm)?(lr=Rm,Oe.addEventListener("message",km,!1)):Am in Pm("script")?lr=function(a){xm.appendChild(Pm("script"))[Am]=function(){xm.removeChild(this),xu(a)}}:lr=function(a){setTimeout(Tu(a),0)});Lm.exports={set:Iu,clear:Eu}});var Cm=m((eB,Dm)=>{"use strict";var Mm=re(),rk=Me(),ik=Object.getOwnPropertyDescriptor;Dm.exports=function(a){if(!rk)return Mm[a];var e=ik(Mm,a);return e&&e.value}});var wu=m((tB,Vm)=>{"use strict";var Om=function(){this.head=null,this.tail=null};Om.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}}};Vm.exports=Om});var _m=m((rB,Bm)=>{"use strict";var ak=sr();Bm.exports=/ipad|iphone|ipod/i.test(ak)&&typeof Pebble!="undefined"});var Fm=m((iB,Nm)=>{"use strict";var sk=sr();Nm.exports=/web0s(?!.*chrome)/i.test(sk)});var Wm=m((aB,Qm)=>{"use strict";var Gr=re(),nk=Cm(),qm=Br(),Au=Pu().set,ok=wu(),uk=bu(),lk=_m(),ck=Fm(),ku=_s(),Um=Gr.MutationObserver||Gr.WebKitMutationObserver,Hm=Gr.document,jm=Gr.process,Ns=Gr.Promise,Lu=nk("queueMicrotask"),jr,Ru,$u,Fs,Gm;Lu||(qi=new ok,Ui=function(){var a,e;for(ku&&(a=jm.domain)&&a.exit();e=qi.get();)try{e()}catch(t){throw qi.head&&jr(),t}a&&a.enter()},!uk&&!ku&&!ck&&Um&&Hm?(Ru=!0,$u=Hm.createTextNode(""),new Um(Ui).observe($u,{characterData:!0}),jr=function(){$u.data=Ru=!Ru}):!lk&&Ns&&Ns.resolve?(Fs=Ns.resolve(void 0),Fs.constructor=Ns,Gm=qm(Fs.then,Fs),jr=function(){Gm(Ui)}):ku?jr=function(){jm.nextTick(Ui)}:(Au=qm(Au,Gr),jr=function(){Au(Ui)}),Lu=function(a){qi.head||jr(),qi.add(a)});var qi,Ui;Qm.exports=Lu});var zm=m((sB,Ym)=>{"use strict";Ym.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var qs=m((nB,Km)=>{"use strict";Km.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var cr=m((oB,Xm)=>{"use strict";var dk=re();Xm.exports=dk.Promise});var Qr=m((uB,tb)=>{"use strict";var pk=re(),Hi=cr(),hk=ee(),fk=Ao(),mk=pu(),bk=he(),Jm=cu(),gk=ze(),Mu=fo(),Zm=Hi&&Hi.prototype,vk=bk("species"),Du=!1,eb=hk(pk.PromiseRejectionEvent),Sk=fk("Promise",function(){var a=mk(Hi),e=a!==String(Hi);if(!e&&Mu===66||gk&&!(Zm.catch&&Zm.finally))return!0;if(!Mu||Mu<51||!/native code/.test(a)){var t=new Hi(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[vk]=r,Du=t.then(function(){})instanceof r,!Du)return!0}return!e&&(Jm==="BROWSER"||Jm==="DENO")&&!eb});tb.exports={CONSTRUCTOR:Sk,REJECTION_EVENT:eb,SUBCLASSING:Du}});var Wr=m((lB,ib)=>{"use strict";var rb=st(),yk=TypeError,Tk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new yk("Bad Promise constructor");e=r,t=i}),this.resolve=rb(e),this.reject=rb(t)};ib.exports.f=function(a){return new Tk(a)}});var Ib=m(()=>{"use strict";var Ik=se(),Ek=ze(),Gs=_s(),Ct=re(),Xr=De(),ab=Hr(),sb=au(),xk=Ci(),Pk=sm(),wk=st(),js=ee(),Ak=Ce(),kk=om(),Rk=mu(),cb=Pu().set,_u=Wm(),$k=zm(),Lk=qs(),Mk=wu(),db=Go(),Qs=cr(),Nu=Qr(),pb=Wr(),Ws="Promise",hb=Nu.CONSTRUCTOR,Dk=Nu.REJECTION_EVENT,Ck=Nu.SUBCLASSING,Cu=db.getterFor(Ws),Ok=db.set,Yr=Qs&&Qs.prototype,dr=Qs,Us=Yr,fb=Ct.TypeError,Ou=Ct.document,Fu=Ct.process,Vu=pb.f,Vk=Vu,Bk=!!(Ou&&Ou.createEvent&&Ct.dispatchEvent),mb="unhandledrejection",_k="rejectionhandled",nb=0,bb=1,Nk=2,qu=1,gb=2,Hs,ob,Fk,ub,vb=function(a){var e;return Ak(a)&&js(e=a.then)?e:!1},Sb=function(a,e){var t=e.value,r=e.state===bb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===gb&&Uk(e),e.rejection=qu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new fb("Promise-chain cycle")):(l=vb(u))?Xr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},yb=function(a,e){a.notified||(a.notified=!0,_u(function(){for(var t=a.reactions,r;r=t.get();)Sb(r,a);a.notified=!1,e&&!a.rejection&&qk(a)}))},Tb=function(a,e,t){var r,i;Bk?(r=Ou.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Ct.dispatchEvent(r)):r={promise:e,reason:t},!Dk&&(i=Ct["on"+a])?i(r):a===mb&&$k("Unhandled promise rejection",t)},qk=function(a){Xr(cb,Ct,function(){var e=a.facade,t=a.value,r=lb(a),i;if(r&&(i=Lk(function(){Gs?Fu.emit("unhandledRejection",t,e):Tb(mb,e,t)}),a.rejection=Gs||lb(a)?gb:qu,i.error))throw i.value})},lb=function(a){return a.rejection!==qu&&!a.parent},Uk=function(a){Xr(cb,Ct,function(){var e=a.facade;Gs?Fu.emit("rejectionHandled",e):Tb(_k,e,a.value)})},zr=function(a,e,t){return function(r){a(e,r,t)}},Kr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Nk,yb(a,!0))},Bu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new fb("Promise can't be resolved itself");var r=vb(e);r?_u(function(){var i={done:!1};try{Xr(r,e,zr(Bu,i,a),zr(Kr,i,a))}catch(s){Kr(i,s,a)}}):(a.value=e,a.state=bb,yb(a,!1))}catch(i){Kr({done:!1},i,a)}}};if(hb&&(dr=function(e){kk(this,Us),wk(e),Xr(Hs,this);var t=Cu(this);try{e(zr(Bu,t),zr(Kr,t))}catch(r){Kr(t,r)}},Us=dr.prototype,Hs=function(e){Ok(this,{type:Ws,done:!1,notified:!1,parent:!1,reactions:new Mk,rejection:!1,state:nb,value:void 0})},Hs.prototype=ab(Us,"then",function(e,t){var r=Cu(this),i=Vu(Rk(this,dr));return r.parent=!0,i.ok=js(e)?e:!0,i.fail=js(t)&&t,i.domain=Gs?Fu.domain:void 0,r.state===nb?r.reactions.add(i):_u(function(){Sb(i,r)}),i.promise}),ob=function(){var a=new Hs,e=Cu(a);this.promise=a,this.resolve=zr(Bu,e),this.reject=zr(Kr,e)},pb.f=Vu=function(a){return a===dr||a===Fk?new ob(a):Vk(a)},!Ek&&js(Qs)&&Yr!==Object.prototype)){ub=Yr.then,Ck||ab(Yr,"then",function(e,t){var r=this;return new dr(function(i,s){Xr(ub,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Yr.constructor}catch(a){}sb&&sb(Yr,Us)}Ik({global:!0,constructor:!0,wrap:!0,forced:hb},{Promise:dr});xk(dr,Ws,!1,!0);Pk(Ws)});var Ab=m((pB,wb)=>{"use strict";var Hk=he(),xb=Hk("iterator"),Pb=!1;try{Eb=0,Uu={next:function(){return{done:!!Eb++}},return:function(){Pb=!0}},Uu[xb]=function(){return this},Array.from(Uu,function(){throw 2})}catch(a){}var Eb,Uu;wb.exports=function(a,e){try{if(!e&&!Pb)return!1}catch(i){return!1}var t=!1;try{var r={};r[xb]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Hu=m((hB,kb)=>{"use strict";var jk=cr(),Gk=Ab(),Qk=Qr().CONSTRUCTOR;kb.exports=Qk||!Gk(function(a){jk.all(a).then(void 0,function(){})})});var Rb=m(()=>{"use strict";var Wk=se(),Yk=De(),zk=st(),Kk=Wr(),Xk=qs(),Jk=Os(),Zk=Hu();Wk({target:"Promise",stat:!0,forced:Zk},{all:function(e){var t=this,r=Kk.f(t),i=r.resolve,s=r.reject,n=Xk(function(){var o=zk(t.resolve),u=[],l=0,c=1;Jk(e,function(d){var p=l++,h=!1;c++,Yk(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Lb=m(()=>{"use strict";var eR=se(),tR=ze(),rR=Qr().CONSTRUCTOR,Gu=cr(),iR=pt(),aR=ee(),sR=Hr(),$b=Gu&&Gu.prototype;eR({target:"Promise",proto:!0,forced:rR,real:!0},{catch:function(a){return this.then(void 0,a)}});!tR&&aR(Gu)&&(ju=iR("Promise").prototype.catch,$b.catch!==ju&&sR($b,"catch",ju,{unsafe:!0}));var ju});var Mb=m(()=>{"use strict";var nR=se(),oR=De(),uR=st(),lR=Wr(),cR=qs(),dR=Os(),pR=Hu();nR({target:"Promise",stat:!0,forced:pR},{race:function(e){var t=this,r=lR.f(t),i=r.reject,s=cR(function(){var n=uR(t.resolve);dR(e,function(o){oR(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Db=m(()=>{"use strict";var hR=se(),fR=Wr(),mR=Qr().CONSTRUCTOR;hR({target:"Promise",stat:!0,forced:mR},{reject:function(e){var t=fR.f(this),r=t.reject;return r(e),t.promise}})});var Qu=m((IB,Cb)=>{"use strict";var bR=nt(),gR=Ce(),vR=Wr();Cb.exports=function(a,e){if(bR(a),gR(e)&&e.constructor===a)return e;var t=vR.f(a),r=t.resolve;return r(e),t.promise}});var Bb=m(()=>{"use strict";var SR=se(),yR=pt(),Ob=ze(),TR=cr(),Vb=Qr().CONSTRUCTOR,IR=Qu(),ER=yR("Promise"),xR=Ob&&!Vb;SR({target:"Promise",stat:!0,forced:Ob||Vb},{resolve:function(e){return IR(xR&&this===ER?TR:this,e)}})});var _b=m(()=>{"use strict";Ib();Rb();Lb();Mb();Db();Bb()});var Ub=m(()=>{"use strict";var PR=se(),wR=ze(),Ys=cr(),AR=pe(),Fb=pt(),qb=ee(),kR=mu(),Nb=Qu(),RR=Hr(),Yu=Ys&&Ys.prototype,$R=!!Ys&&AR(function(){Yu.finally.call({then:function(){}},function(){})});PR({target:"Promise",proto:!0,real:!0,forced:$R},{finally:function(a){var e=kR(this,Fb("Promise")),t=qb(a);return this.then(t?function(r){return Nb(e,a()).then(function(){return r})}:a,t?function(r){return Nb(e,a()).then(function(){throw r})}:a)}});!wR&&qb(Ys)&&(Wu=Fb("Promise").prototype.finally,Yu.finally!==Wu&&RR(Yu,"finally",Wu,{unsafe:!0}));var Wu});var jb=m((RB,Hb)=>{"use strict";Jf();_b();Ub();var LR=Dt();Hb.exports=LR("Promise","finally")});var Qb=m(($B,Gb)=>{"use strict";var MR=jb();Gb.exports=MR});var zs=m((LB,Wb)=>{"use strict";var DR=Qb();Wb.exports=DR});var ng=m(()=>{"use strict";var WR=se(),YR=qo().values;WR({target:"Object",stat:!0},{values:function(e){return YR(e)}})});var ug=m((m_,og)=>{"use strict";ng();var zR=Cr();og.exports=zR.Object.values});var cg=m((b_,lg)=>{"use strict";var KR=ug();lg.exports=KR});var Zr=m((g_,dg)=>{"use strict";var XR=cg();dg.exports=XR});var xg=m(()=>{"use strict";var h$=se(),f$=Or(),m$=qr(),b$=$i(),g$=Li();h$({target:"Array",proto:!0},{at:function(e){var t=f$(this),r=m$(t),i=b$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});g$("at")});var wg=m((G_,Pg)=>{"use strict";xg();var v$=Dt();Pg.exports=v$("Array","at")});var kg=m((Q_,Ag)=>{"use strict";var S$=wg();Ag.exports=S$});var ti=m((W_,Rg)=>{"use strict";var y$=kg();Rg.exports=y$});var gl=m((IF,sv)=>{"use strict";var tL=ir();sv.exports=Array.isArray||function(e){return tL(e)==="Array"}});var ov=m((EF,nv)=>{"use strict";var rL=TypeError,iL=9007199254740991;nv.exports=function(a){if(a>iL)throw rL("Maximum allowed index exceeded");return a}});var cv=m((xF,lv)=>{"use strict";var aL=gl(),sL=qr(),nL=ov(),oL=Br(),uv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?oL(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&aL(d)?(p=sL(d),u=uv(a,e,d,p,u,s-1)-1):(nL(u+1),a[u]=d),u++),l++;return u};lv.exports=uv});var fv=m((PF,hv)=>{"use strict";var dv=gl(),uL=fu(),lL=Ce(),cL=he(),dL=cL("species"),pv=Array;hv.exports=function(a){var e;return dv(a)&&(e=a.constructor,uL(e)&&(e===pv||dv(e.prototype))?e=void 0:lL(e)&&(e=e[dL],e===null&&(e=void 0))),e===void 0?pv:e}});var bv=m((wF,mv)=>{"use strict";var pL=fv();mv.exports=function(a,e){return new(pL(a))(e===0?0:e)}});var gv=m(()=>{"use strict";var hL=se(),fL=cv(),mL=st(),bL=Or(),gL=qr(),vL=bv();hL({target:"Array",proto:!0},{flatMap:function(e){var t=bL(this),r=gL(t),i;return mL(e),i=vL(t,0),i.length=fL(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var vv=m(()=>{"use strict";var SL=Li();SL("flatMap")});var yv=m((LF,Sv)=>{"use strict";gv();vv();var yL=Dt();Sv.exports=yL("Array","flatMap")});var Iv=m((MF,Tv)=>{"use strict";var TL=yv();Tv.exports=TL});var vl=m((DF,Ev)=>{"use strict";var IL=Iv();Ev.exports=IL});var aa=m((jF,Hv)=>{"use strict";var $L=Di(),LL=String;Hv.exports=function(a){if($L(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return LL(a)}});var yl=m((GF,jv)=>{"use strict";jv.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 Wv=m((QF,Qv)=>{"use strict";var ML=ne(),DL=Mt(),CL=aa(),Il=yl(),Gv=ML("".replace),OL=RegExp("^["+Il+"]+"),VL=RegExp("(^|[^"+Il+"])["+Il+"]+$"),Tl=function(a){return function(e){var t=CL(DL(e));return a&1&&(t=Gv(t,OL,"")),a&2&&(t=Gv(t,VL,"$1")),t}};Qv.exports={start:Tl(1),end:Tl(2),trim:Tl(3)}});var Xv=m((WF,Kv)=>{"use strict";var BL=Yo().PROPER,_L=pe(),Yv=yl(),zv="\u200B\x85\u180E";Kv.exports=function(a){return _L(function(){return!!Yv[a]()||zv[a]()!==zv||BL&&Yv[a].name!==a})}});var El=m((YF,Jv)=>{"use strict";var NL=Wv().start,FL=Xv();Jv.exports=FL("trimStart")?function(){return NL(this)}:"".trimStart});var eS=m(()=>{"use strict";var qL=se(),Zv=El();qL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Zv},{trimLeft:Zv})});var rS=m(()=>{"use strict";eS();var UL=se(),tS=El();UL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==tS},{trimStart:tS})});var aS=m((ZF,iS)=>{"use strict";rS();var HL=Dt();iS.exports=HL("String","trimLeft")});var nS=m((eq,sS)=>{"use strict";var jL=aS();sS.exports=jL});var uS=m((tq,oS)=>{"use strict";var GL=nS();oS.exports=GL});var xS=m(()=>{"use strict"});var PS=m(()=>{"use strict"});var AS=m((k1,wS)=>{"use strict";var fM=Ce(),mM=ir(),bM=he(),gM=bM("match");wS.exports=function(a){var e;return fM(a)&&((e=a[gM])!==void 0?!!e:mM(a)==="RegExp")}});var RS=m((R1,kS)=>{"use strict";var vM=nt();kS.exports=function(){var a=vM(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 MS=m(($1,LS)=>{"use strict";var SM=De(),yM=Ke(),TM=xi(),IM=RS(),$S=RegExp.prototype;LS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in $S)&&!yM(a,"flags")&&TM($S,a)?SM(IM,a):e}});var CS=m((L1,DS)=>{"use strict";var Ml=ne(),EM=Or(),xM=Math.floor,$l=Ml("".charAt),PM=Ml("".replace),Ll=Ml("".slice),wM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,AM=/\$([$&'`]|\d{1,2})/g;DS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=AM;return i!==void 0&&(i=EM(i),u=wM),PM(s,u,function(l,c){var d;switch($l(c,0)){case"$":return"$";case"&":return a;case"`":return Ll(e,0,t);case"'":return Ll(e,n);case"<":d=i[Ll(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=xM(p/10);return h===0?l:h<=o?r[h-1]===void 0?$l(c,1):r[h-1]+$l(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var BS=m(()=>{"use strict";var kM=se(),RM=De(),Cl=ne(),OS=Mt(),$M=ee(),LM=Dr(),MM=AS(),oi=aa(),DM=wi(),CM=MS(),OM=CS(),VM=he(),BM=ze(),_M=VM("replace"),NM=TypeError,Dl=Cl("".indexOf),FM=Cl("".replace),VS=Cl("".slice),qM=Math.max;kM({target:"String",proto:!0},{replaceAll:function(e,t){var r=OS(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!LM(e)){if(i=MM(e),i&&(s=oi(OS(CM(e))),!~Dl(s,"g")))throw new NM("`.replaceAll` does not allow non-global regexes");if(n=DM(e,_M),n)return RM(n,e,r,t);if(BM&&i)return FM(oi(r),e,t)}for(o=oi(r),u=oi(e),l=$M(t),l||(t=oi(t)),c=u.length,d=qM(1,c),p=Dl(o,u);p!==-1;)h=l?oi(t(u,p,o)):OM(u,o,p,[],void 0,t),b+=VS(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Dl(o,u,p+d);return f<o.length&&(b+=VS(o,f)),b}})});var NS=m((C1,_S)=>{"use strict";xS();PS();BS();var UM=Dt();_S.exports=UM("String","replaceAll")});var qS=m((O1,FS)=>{"use strict";var HM=NS();FS.exports=HM});var HS=m((V1,US)=>{"use strict";var jM=qS();US.exports=jM});var GS=m((B1,jS)=>{"use strict";var GM=$i(),QM=aa(),WM=Mt(),YM=RangeError;jS.exports=function(e){var t=QM(WM(this)),r="",i=GM(e);if(i<0||i===1/0)throw new YM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var KS=m((_1,zS)=>{"use strict";var YS=ne(),zM=Do(),QS=aa(),KM=GS(),XM=Mt(),JM=YS(KM),ZM=YS("".slice),eD=Math.ceil,WS=function(a){return function(e,t,r){var i=QS(XM(e)),s=zM(t),n=i.length,o=r===void 0?" ":QS(r),u,l;return s<=n||o===""?i:(u=s-n,l=JM(o,eD(u/o.length)),l.length>u&&(l=ZM(l,0,u)),a?i+l:l+i)}};zS.exports={start:WS(!1),end:WS(!0)}});var JS=m((N1,XS)=>{"use strict";var tD=sr();XS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(tD)});var ZS=m(()=>{"use strict";var rD=se(),iD=KS().start,aD=JS();rD({target:"String",proto:!0,forced:aD},{padStart:function(e){return iD(this,e,arguments.length>1?arguments[1]:void 0)}})});var ty=m((U1,ey)=>{"use strict";ZS();var sD=Dt();ey.exports=sD("String","padStart")});var iy=m((H1,ry)=>{"use strict";var nD=ty();ry.exports=nD});var sy=m((j1,ay)=>{"use strict";var oD=iy();ay.exports=oD});var td="2.0.124-dev.b2dae3ef.0";var Ie=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Ie||{}),Lt=(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))(Lt||{});var ms=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(ms||{}),to=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(to||{});var ro=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(ro||{});var VT=B(Xe(),1);import{assertNever as Zp,assertNonNullable as yx,isNonNullable as ys,ValueSubject as Oo,Subject as Tx,Subscription as Ix,merge as Ex,observableFrom as xx,fromEvent as zp,map as Kp,tap as Xp,filterChanged as Px,isNullable as Vo,ErrorCategory as Jp}from"@vkontakte/videoplayer-shared/es2015";var Yp=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 Ts=class{constructor(e){this.connection$=new Oo(void 0);this.castState$=new Oo("NOT_AVAILABLE");this.errorEvent$=new Tx;this.realCastState$=new Oo("NOT_AVAILABLE");this.subscription=new Ix;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=ys((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||Yp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Jp.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(){ys(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Vo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Vo(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(zp(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 Zp(i.sessionState)}})).add(Ex(zp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Xp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Kp(i=>i.castState)),xx([r.getCastState()])).pipe(Px(),Kp(wx),Xp(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=ys(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();yx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Vo(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"?ys(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:Jp.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},wx=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 Zp(a)}};var pc=B(Xe(),1),bT=B(Ur(),1),gT=B(lu(),1);var ig=B(zs(),1);import{assertNever as Yb}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:Yb(t)}return a},Ks=(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:Yb(e)}};var P=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as CR,Subject as Xs,merge as zb}from"@vkontakte/videoplayer-shared/es2015";var C=class{constructor(e){this.transitionStarted$=new Xs;this.transitionEnded$=new Xs;this.transitionUpdated$=new Xs;this.forceChanged$=new Xs;this.stateChangeStarted$=zb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=zb(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||CR(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 OR}from"@vkontakte/videoplayer-shared/es2015";var Kb=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 OR(a)}};import{assertNever as Jr,assertNonNullable as pr,debounce as Xb,ErrorCategory as Jb,fromEvent as hr,isNonNullable as Zb,map as eg,merge as tg,observableFrom as VR,Subject as BR,Subscription as zu,timeout as _R,getHighestQuality as NR}from"@vkontakte/videoplayer-shared/es2015";var FR=5,qR=5,UR=500,rg=7e3,ji=class{constructor(e){this.subscription=new zu;this.loadMediaTimeoutSubscription=new zu;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:Jr(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:Jr(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:Jr(e)}break}default:Jr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Kb(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 zu;this.subscription.add(e),this.subscription.add(tg(this.videoState.stateChangeStarted$.pipe(eg(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(eg(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 BR;e.add(i.pipe(Xb(UR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(hr(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)>FR)&&i.next(o),s=o})),e.add(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(hr(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<qR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:Jr(n)}}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(hr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=tg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,VR(["init"])).pipe(Xb(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"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(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"),P(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"),P(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"&&P(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];pr(c);let d=NR(Object.keys(c));pr(d);let p=c[d];pr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];pr(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];pr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];pr(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];pr(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:Jb.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Jr(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 Zb(o)&&(n.metadata.title=o),Zb(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(_R(rg).subscribe(()=>s(`timeout(${rg})`)))});(0,ig.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:Jb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ml=B(Xe(),1);import{clearVideoElement as sg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as HR}from"@vkontakte/videoplayer-shared/es2015";var ag=a=>{try{a.pause(),a.playbackRate=0,HR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as jR,Subscription as GR}from"@vkontakte/videoplayer-shared/es2015";var Ku=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)}},Xu=window.WeakMap?new WeakMap:new Ku,Ju=window.WeakMap?new WeakMap:new Map,QR=(a,e=20)=>{let t=0;return jR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ee=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?sg(t):(t=document.createElement("video"),a.appendChild(t)),Xu.set(t,r);let i=new GR;return i.add(QR(t,e)),Ju.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.setAttribute("x-yandex-pip","false"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},xe=a=>{let e=Ju.get(a);e==null||e.unsubscribe(),Ju.delete(a);let t=Xu.get(a);Xu.delete(a),t?sg(a):ag(a)};var el=B(Zr(),1);import{assertNonNullable as Gi,isNonNullable as ut,isNullable as e$,fromEvent as ei,merge as pg,observableFrom as hg,filterChanged as fg,map as Qi,Subject as mg,Subscription as t$,ValueSubject as r$,ErrorCategory as i$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Zu,isNullable as JR,Subscription as ZR}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=JR(i),l=new ZR;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},ot=(a,e,t)=>Js(e,()=>a.loop,r=>{Zu(r)&&(a.loop=r)},{onError:t}),Pe=(a,e,t,r)=>Js(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}),Fe=(a,e,t,r)=>Js(e,()=>a.playbackRate,i=>{Zu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ot=Js;var a$=a=>["__",a.language,a.label].join("|"),s$=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},tl=class a{constructor(e){this.available$=new mg;this.current$=new r$(void 0);this.error$=new mg;this.subscription=new t$;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:i$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ot(t.internalTextTracks,()=>(0,el.default)(this.internalTracks),s=>{ut(s)&&this.setInternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Qi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Ot(t.externalTextTracks,()=>(0,el.default)(this.externalTracks),s=>{ut(s)&&this.setExternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Qi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Ot(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Ot(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){Gi(this.video);let{textTracks:e}=this.video;this.subscription.add(ei(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(pg(ei(e,"addtrack"),ei(e,"removetrack"),hg(["init"])).pipe(Qi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),fg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(pg(ei(e,"change"),hg(["init"])).pipe(Qi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Qi(r=>r&&this.htmlTextTrackToITextTrack(r).id),fg()).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(ei(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(ei(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;ut(t.align)&&(i.align=t.align),ut(t.position)&&(i.position=t.position),ut(t.size)&&(i.size=t.size),ut(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){Gi(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:a$(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){Gi(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(e$(e)||!s$(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){Gi(this.video);let t=document.createElement("track");this.baseURL?t.setAttribute("src",new URL(e.url,this.baseURL).toString()):t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){Gi(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)}},qe=tl;var mt=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 bg=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},rl=a=>{let e=bg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},gg=a=>{let e=bg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Ue,map as Vt,merge as Sg,filterChanged as o$,isNonNullable as yg,Subject as u$,filter as Tg,mapTo as Ig,combine as l$,once as c$,ErrorCategory as d$,ValueSubject as Eg,clientChecker as p$}from"@vkontakte/videoplayer-shared/es2015";var n$=3,vg=(a,e,t=n$)=>{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 we=a=>{let e=y=>Ue(a,y).pipe(Ig(void 0)),r=Sg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>Ue(a,y))).pipe(Vt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),o$()),i=Sg(Ue(a,"progress"),Ue(a,"timeupdate")).pipe(Vt(()=>vg(a.buffered,a.currentTime))),s=p$.isSafari?l$({play:e("play").pipe(c$()),playing:e("playing")}).pipe(Ig(void 0)):e("playing"),n=Ue(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=Ue(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=Ue(a,"error").pipe(Tg(()=>!!(a.error||a.played.length)),Vt(()=>{var x;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:d$.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(x=a.error)!=null?x:void 0}})),l=Ue(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new u$,d=.3,p;l.subscribe(y=>{a.loop&&yg(p)&&yg(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(Tg(()=>!a.error&&p!==a.duration)),f=Ue(a,"enterpictureinpicture"),b=Ue(a,"leavepictureinpicture"),g=new Eg(gg(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Eg(rl(a));return Ue(a,"fullscreenchange").pipe(Vt(()=>rl(a))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:Ue(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:f,leavePip$:b}};import{VideoQuality as Bt}from"@vkontakte/videoplayer-shared/es2015";var _t=a=>{switch(a){case"mobile":return Bt.Q_144P;case"lowest":return Bt.Q_240P;case"low":return Bt.Q_360P;case"sd":case"medium":return Bt.Q_480P;case"hd":case"high":return Bt.Q_720P;case"fullhd":case"full":return Bt.Q_1080P;case"quadhd":case"quad":return Bt.Q_1440P;case"ultrahd":case"ultra":return Bt.Q_2160P}};var Nt=B(ti(),1),Vg=B(Xe(),1),Zs=B(Ur(),1);import{isNonNullable as oe,isNullable as al,now as Bg,isHigher as sl,isHigherOrEqual as nl,isInvariantQuality as Dg,isLower as Cg,isLowerOrEqual as ol,videoSizeToQuality as T$,assertNotEmptyArray as _g,assertNonNullable as I$}from"@vkontakte/videoplayer-shared/es2015";var il=!1,bt={},$g=a=>{il=a},Lg=()=>{bt={}},Mg=a=>{a(bt)},Wi=(a,e)=>{var t;il&&(bt.meta=(t=bt.meta)!=null?t:{},bt.meta[a]=e)},ve=class{constructor(e){this.name=e}next(e){var r,i;if(!il)return;bt.series=(r=bt.series)!=null?r:{};let t=(i=bt.series[this.name])!=null?i:[];t.push([Date.now(),e]),bt.series[this.name]=t}};var E$=new ve("best_bitrate"),Ng=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var ul=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Yi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Bg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Fg='Assertion "ABR Tracks is empty array" failed',en=(a,e,t,r)=>{var u;let i=[...e].sort(ul(1)),s=[...t].sort(ul(1)),n=s.filter(l=>oe(l.bitrate)&&oe(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,Vg.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},Og=a=>"quality"in a,qg=(a,e,t,r)=>{var n;let i=oe((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&oe(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Bg()-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=Og(o)?"video":"audio",l=Og(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return r==null||r.recordSwitch(t),t},AL=(a,e)=>Math.log(e)/Math.log(a),kL=({tuning:a,container:e,limits:t})=>{let r=a.containerSizeFactor;if(a.usePixelRatio&&window.devicePixelRatio){let i=window.devicePixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(i-1)+1;else{let s=a.pixelRatioLogBase,[n=0,o=0,u=0]=a.pixelRatioLogCoefficients,l=AL(s,n*i+o)+u;Number.isFinite(l)&&(r*=l)}}return Gg({tuning:a,limits:t})&&(r*=2),{containerSizeLimit:a.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*r,height:e.height*r}:void 0,containerSizeFactor:r}},Nt=(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:p,stallsPredictedThroughput:h,abrLogger:m})=>{var q,R,U,N,W,k;qg(a,Hg);let{containerSizeFactor:b,containerSizeLimit:g}=kL({container:e,tuning:r,limits:i}),v=r.considerPlaybackRate&&ne(o)?o:1,S=a.filter(T=>!Og(T.quality)).sort((T,B)=>ul(T.quality,B.quality)?-1:1),y=(q=(0,_t.default)(S,-1))==null?void 0:q.quality,I=(R=(0,_t.default)(S,0))==null?void 0:R.quality,x=ol(i)||ne(i.min)&&ne(i.max)&&Bg(i.max,i.min)||ne(i.min)&&I&&ul(i.min,I)||ne(i.max)&&y&&Bg(i.max,y),$=v*Ug(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),V={},M=S.filter(T=>{let B=!0;if(g)if(T.size)B=T.size.width<=g.width&&T.size.height<=g.height;else{let be=g&&xL(g);B=be?cl(T.quality,be):!0}if(!B)return V[T.quality]="FitsContainer",!1;let D=h||t,le=ne(D)&&isFinite(D)&&ne(T.bitrate)?D-s>=T.bitrate*$:!0,Me=Gg({tuning:r,limits:i})&&(i==null?void 0:i.min)===T.quality;if(!le&&!Me)return V[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&ne(r.minBufferToSwitchUp)&&u&&!Og(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&ul(T.quality,u.quality))return V[T.quality]="Buffer",!1;if(!!d&&ll(T.quality,d)&&!Me)return V[T.quality]="DroppedFramesLimit",!1;if(!!p&&ll(T.quality,p)&&!Me)return V[T.quality]="StallsLimit",!1;let ce=x||(ol(i.max)||cl(T.quality,i.max))&&(ol(i.min)||ll(T.quality,i.min)),fe=ne(c)&&!c?cl(T.quality,r.backgroundVideoQualityLimit):!0;return!ce||!fe?(V[T.quality]="FitsQualityLimits",!1):!0})[0];M&&M.bitrate&&wL.next(M.bitrate);let F=(U=M!=null?M:(0,_t.default)(S,-1))!=null?U:a[0];return F.quality!==((N=l==null?void 0:l.last)==null?void 0:N.quality)&&m({message:`
9
+ `}),o}return r==null||r.recordSwitch(t),t},x$=(a,e)=>Math.log(e)/Math.log(a),Ft=(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:p,stallsPredictedThroughput:h,abrLogger:f})=>{var F,R,q,_,Y,k;_g(a,Fg);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let T=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(T-1)+1;else{let D=r.pixelRatioLogBase,[Q=0,H=0,Be=0]=r.pixelRatioLogCoefficients,It=x$(D,Q*T+H)+Be;Number.isFinite(It)&&(b*=It)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,v=r.considerPlaybackRate&&oe(o)?o:1,S=a.filter(T=>!Dg(T.quality)).sort((T,D)=>sl(T.quality,D.quality)?-1:1),y=(F=(0,Nt.default)(S,-1))==null?void 0:F.quality,x=(R=(0,Nt.default)(S,0))==null?void 0:R.quality,E=al(i)||oe(i.min)&&oe(i.max)&&Cg(i.max,i.min)||oe(i.min)&&x&&sl(i.min,x)||oe(i.max)&&y&&Cg(i.max,y),L=v*Ng(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),O={},M=S.filter(T=>{let D=!0;if(g)if(T.size)D=T.size.width<=g.width&&T.size.height<=g.height;else{let de=g&&T$(g);D=de?ol(T.quality,de):!0}if(!D)return O[T.quality]="FitsContainer",!1;let Q=h||t;if(!(oe(Q)&&isFinite(Q)&&oe(T.bitrate)?Q-s>=T.bitrate*L:!0))return O[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&oe(r.minBufferToSwitchUp)&&u&&!Dg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&sl(T.quality,u.quality))return O[T.quality]="Buffer",!1;if(!!d&&nl(T.quality,d))return O[T.quality]="DroppedFramesLimit",!1;if(!!p&&nl(T.quality,p))return O[T.quality]="StallsLimit",!1;let j=E||(al(i.max)||ol(T.quality,i.max))&&(al(i.min)||nl(T.quality,i.min)),ce=oe(c)&&!c?ol(T.quality,r.backgroundVideoQualityLimit):!0;return!j||!ce?(O[T.quality]="FitsQualityLimits",!1):!0})[0];M&&M.bitrate&&E$.next(M.bitrate);let N=(q=M!=null?M:(0,Nt.default)(S,-1))!=null?q:a[0];return N.quality!==((_=l==null?void 0:l.last)==null?void 0:_.quality)&&f({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${a.map(T=>{var B,D;return`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${(B=T.size)==null?void 0:B.width}:${(D=T.size)==null?void 0:D.height} }`}).join(`
12
+ ${a.map(T=>{var D,Q;return`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${(D=T.size)==null?void 0:D.width}:${(Q=T.size)==null?void 0:Q.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,en.default)(r!=null?r:{}).map(([T,B])=>`${T}: ${B}`).join(`
16
+ ${(0,Zs.default)(r!=null?r:{}).map(([T,D])=>`${T}: ${D}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
20
  containerSizeFactor: ${b},
21
- containerSizeLimit: ${(W=g==null?void 0:g.width)!=null?W:0} x ${(k=g==null?void 0:g.height)!=null?k:0},
21
+ containerSizeLimit: ${(Y=g==null?void 0:g.width)!=null?Y:0} x ${(k=g==null?void 0:g.height)!=null?k:0},
22
22
  estimatedThroughput: ${t},
23
23
  stallsPredictedThroughput: ${h},
24
24
  reserve: ${s},
25
25
  playbackRate: ${o},
26
26
  playbackRateFactor: ${v},
27
27
  forwardBufferHealth: ${n},
28
- bitrateFactor: ${$},
28
+ bitrateFactor: ${L},
29
29
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
30
30
  droppedVideoMaxQualityLimit: ${d},
31
31
  stallsVideoMaxQualityLimit: ${p},
32
- limitsAreInvalid: ${x},
32
+ limitsAreInvalid: ${E},
33
33
  maxQualityLimit: ${i==null?void 0:i.max},
34
34
  minQualityLimit: ${i==null?void 0:i.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,en.default)(V).map(([T,B])=>`${T}: ${B}`).join(`
37
+ ${(0,Zs.default)(O).map(([T,D])=>`${T}: ${D}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
40
  [best video track] ${M==null?void 0:M.quality}
41
- [selected video track] ${F==null?void 0:F.quality}
42
- `}),jg(r,m,F,l)},Qg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;qg(t,Hg);let c=i.considerPlaybackRate&&ne(s)?s:1,d=[...t].sort(dl(-1)),p=a.bitrate;PL(p);let h=c*Ug(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,b=tn(a,e,t,i.minVideoAudioRatio),g=l||r;return ne(g)&&isFinite(g)&&(m=d.find(S=>ne(S.bitrate)&&ne(b==null?void 0:b.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),m||(m=b),(m==null?void 0:m.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
41
+ [selected video track] ${N==null?void 0:N.quality}
42
+ `}),qg(r,f,N,l)},Ug=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;_g(t,Fg);let c=i.considerPlaybackRate&&oe(s)?s:1,d=[...t].sort(ul(-1)),p=a.bitrate;I$(p);let h=c*Ng(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,b=en(a,e,t,i.minVideoAudioRatio),g=l||r;return oe(g)&&isFinite(g)&&(f=d.find(S=>oe(S.bitrate)&&oe(b==null?void 0:b.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),f||(f=b),(f==null?void 0:f.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
43
43
  [AUDIO TRACKS ABR]
44
44
  [available audio tracks]
45
45
  ${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,en.default)(i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
49
+ ${(0,Zs.default)(i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
@@ -59,15 +59,15 @@ var YT=Object.create;var to=Object.defineProperty,zT=Object.defineProperties,KT=
59
59
  bitrateFactor: ${h},
60
60
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
61
61
 
62
- [selected audio track] ${m==null?void 0:m.id}
63
- `}),m&&jg(i,u,m,o)};function Gg({limits:a,tuning:{highQualityLimit:e,trafficSavingLimit:t}}){return!!a&&Zs({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}var oe=a=>new URL(a).hostname;import{assertNever as rv,assertNonNullable as iv,combine as zL,debounce as KL,ErrorCategory as av,filter as sv,filterChanged as XL,isNonNullable as bl,map as on,merge as nv,observableFrom as JL,once as ZL,Subscription as e$,ValueSubject as gl,videoQualityToHeight as t$,videoSizeToQuality as r$}from"@vkontakte/videoplayer-shared/es2015";var Yg=_(Xe(),1);var Wg=a=>{if(a instanceof DOMException&&(0,Yg.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"))},we=(a,e)=>A(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!Wg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return Wg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as an,isNullable as $L,assertNonNullable as Xi}from"@vkontakte/videoplayer-shared/es2015";var Kg=_(Jr(),1);import{isNonNullable as zg,assertNonNullable as rn,now as RL}from"@vkontakte/videoplayer-shared/es2015";function ue(){return RL()}function pl(a){return ue()-a}function hl(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 Xg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ti(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;rn(c);let R=pl(c),U;if(R<b){U=b-R,setTimeout(g,U);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,$()},v=R=>(s=R,q),S=R=>(d=R,q),y=()=>(h="json",q),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},x=R=>(p=R,q),$=()=>{c=ue(),n=new i,n.open("get",a);let R=0,U,N=0,W=()=>(rn(c),Math.max(c,Math.max(U||0,N||0)));if(s&&n.addEventListener("progress",k=>{let T=ue();s.updateChunk&&k.loaded>R&&(s.updateChunk(W(),k.loaded-R),R=k.loaded,U=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;rn(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let T=n.response.byteLength-R;T&&s.updateChunk&&s.updateChunk(W(),T)}n.responseType==="json"&&!(0,Kg.default)(n.response).length?I():(d&&d(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),p){let k=()=>{rn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(N=ue(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),q},q={withBitrateReporting:v,withParallel:x,withJSONResponse:y,withRetryCount:R=>(l=R,q),withRetryInterval:(R,U)=>(zg(R)&&(b=R),zg(U)&&(m=U),q),withTimeout:R=>(o=R,q),withFinally:S,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return q}var zi=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 Jg=_(Jr(),1);var Ki=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=ti(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,Jg.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 ML}from"@vkontakte/videoplayer-shared/es2015";var sn=1e4,ml=3;var DL=6e4,CL=10,VL=1,OL=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 ML,this.chunkRateEstimator=new zi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=hl(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=hl(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||an(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=()=>{Xg(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 Ki(ml,sn,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},p=(I,x,$)=>{u&&u.abort(),u=ti(this.urlResolver.resolve(I,!1),x,$,()=>this._retryCallback()).withTimeout(sn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ml).withFinally(()=>{u=null}).send()},h=(I,x,$)=>{Xi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),x,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let x=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${x}=>${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 $=ue()-1e4,V=0;for(let M=0;M<this.bufferStates.length;M++){let F=this.bufferStates[M];I=Math.min(I,F.buf),F.ts<$&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${I} drop=${V} jitter=${this.sourceJitter}`);let X=I-VL;this.sourceJitter>=0?X-=this.sourceJitter/2:this.sourceJitter-=1,X>3?m(1.15):X>1?m(1.1):X>.3?m(1.05):m(1)}},v=I=>{let x,$=()=>x&&x.start?x.start.length:0,V=k=>x.start[k]/1e3,X=k=>x.dur[k]/1e3,M=k=>x.fragIndex+k,F=(k,T)=>({chunkIdx:M(k),startTS:V(k),dur:X(k),discontinuity:T}),q=()=>{let k=0;if(x&&x.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,B=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,D=T;this.sourceJitter>1&&(D+=this.sourceJitter-1);let le=x.dur.length-1;for(;le>=0&&(D-=x.dur[le],!(D<=0));--le);k=Math.min(le,x.dur.length-1-B),k=Math.max(k,0)}return F(k,!0)},R=k=>{let T=$();if(!(T<=0)){if(an(k)){for(let B=0;B<T;B++)if(V(B)>k)return F(B)}return q()}},U=k=>{let T=$(),B=k?k.chunkIdx+1:0,D=B-x.fragIndex;if(!(T<=0)){if(!k||D<0||D-T>CL)return t(`Resync: offset=${D} bChunks=${T} chunk=`+JSON.stringify(k)),q();if(!(D>=T))return F(B-x.fragIndex,!1)}},N=(k,T,B)=>{l&&l.abort(),l=ti(this.urlResolver.resolve(k,!0,this.lowLatency),T,B,()=>this._retryCallback()).withTimeout(sn).withRetryCount(ml).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,T)=>{N(I,B=>{if(!d())return;x=B;let D=!!x.lowLatency;D!==this.lowLatency&&b(D);let le=0;for(let Me=0;Me<x.dur.length;++Me)le+=x.dur[Me];le>0&&(Xi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(le/x.dur.length)),i({name:"index",zeroTime:x.zeroTime,shiftDuration:x.shiftDuration}),this.sourceJitter=x.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,x.jitter/1e3)):1,k(R(T))},()=>this._handleNetworkError())},nextChunk:U}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Xi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:x,logger:$}=this.params,V=v(e.jidxUrl),X,M,F,q,R=0,U,N,W,k=()=>{U&&(clearTimeout(U),U=void 0);let j=Math.max(OL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ce=R+j,fe=ue(),be=Math.min(1e4,ce-fe);R=fe;let It=()=>{l||d()&&V.seek(()=>{d()&&(R=ue(),T(),k())})};be>0?U=window.setTimeout(()=>{this.paused?k():It()},be):It()},T=()=>{let j;for(;j=V.nextChunk(q);)q=j,pi(j);let ce=V.nextChunk(F);if(ce){if(F&&ce.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?k():(S(),this._initPlayerWith(e));return}Me(ce)}else k()},B=(j,ce)=>{if(!d()||!this.sourceBuffer)return;let fe,be,It,xr=Et=>{window.setTimeout(()=>{d()&&B(j,ce)},Et)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),xr(100);else{let Et=ue(),Yt=x.currentTime;!this.paused&&x.buffered.length>1&&N===Yt&&Et-W>500&&($("Stall suspected; trying to fix"),this._fixupStall()),N!==Yt&&(N=Yt,W=Et);let Pr=this._getBufferSizeSec();if(Pr>30)$(`Buffered ${Pr} seconds; delaying appendBuffer`),xr(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:Et,buf:Pr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ce&&ce()}catch(hi){if(hi.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),It=this.sourceBuffer.buffered.length,It!==0&&(fe=this.sourceBuffer.buffered.start(0),be=Yt,be-fe>4&&this.sourceBuffer.remove(fe,be-3)),xr(1e3);else throw hi}}},D=()=>{M&&X&&($([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(F)]),B(M,function(){M=null,T()}))},le=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),Me=j=>{d()&&h(le(j),(ce,fe)=>{if(d()){if(fe/=1e3,M=ce,F=j,n=j.startTS,fe){let be=Math.min(10,j.dur/fe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*be:be}D()}},()=>this._handleNetworkError())},pi=j=>{d()&&(Xi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(le(j),!1)))},Er=j=>{d()&&(e.cachedHeader=j,B(j,()=>{X=!0,D()}))};s=!0,V.seek(j=>{if(d()){if(R=ue(),!j){k();return}q=j,!$L(I)||j.startTS>I?Me(j):(F=j,T())}},I),e.cachedHeader?Er(e.cachedHeader):p(e.headerUrl,Er,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),an(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,Xi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return an(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=ue();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&pl(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=ue();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ti(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(sn).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;we(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))},DL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var tv=_(qr(),1);import{debounce as BL,filter as Zg,fromEvent as _L,interval as NL,isHigher as FL,isInvariantQuality as qL,isLower as UL,merge as HL,Subject as ev,Subscription as jL}from"@vkontakte/videoplayer-shared/es2015";var fl=class{constructor(){this.onDroopedVideoFramesLimit$=new ev;this.subscription=new jL;this.playing=!1;this.tracks=[];this.forceChecker$=new ev;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&&!qL(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&&FL(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(_L(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=NL(this.droppedFramesChecker.checkTime).pipe(Zg(()=>this.playing),Zg(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(BL(this.droppedFramesChecker.checkTime)),r=HL(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,tv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>UL(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}},nn=fl;import{map as QL,Observable as GL}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as WL}from"@vkontakte/videoplayer-shared/es2015";var Zi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var YL=(a,e)=>new GL(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Zi()))},E(E({},r),e));i.observe(a);let s=WL(document,"visibilitychange").pipe(QL(n=>!document.hidden||Zi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ue=YL;var i$=["paused","playing","ready"],a$=["paused","playing","ready"],ea=class{constructor(e){this.subscription=new e$;this.videoState=new C("stopped");this.representations$=new gl([]);this.droppedFramesManager=new nn;this.maxSeekBackTime$=new gl(1/0);this.zeroTime$=new gl(void 0);this.liveOffset=new ft;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:av.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=Bt(u.name))!=null?r:r$(u.video),d=u.bitrate/1e3,p=E({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((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),bl(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,vl.default)(a$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,vl.default)(i$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(he(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(he(this.params.source.url,u))}return;default:return rv(e)}};this.textTracksManager=new Fe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:av.WTF,message:"DashLiveProvider internal logic error",thrown:i})};nv(this.videoState.stateChangeStarted$.pipe(on(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(on(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Ie(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=Pe(this.video);this.subscription.add(this.representations$.pipe(on(i=>i.map(({track:s})=>s)),sv(i=>!!i.length),ZL()).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(XL(),on(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(zL({zeroTime:this.zeroTime$.pipe(sv(bl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(xe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ne(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(Ue(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&t$(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 rv(i.to)}},t)).add(nv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,JL(["init"])).pipe(KL(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ee(this.video)}createLiveDashPlayer(){let e=new 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,p,h,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=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&bl(t)?t:Nt(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=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.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;iv(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;iv(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(he(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var ov=ea;var jy=_(Xe(),1);var lt=(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 GD,assertNonNullable as WD,debounce as YD,ErrorCategory as ac,filter as qy,filterChanged as Ua,fromEvent as zD,isNonNullable as Uy,map as sc,merge as Cn,observableFrom as nc,once as Hy,Subscription as KD}from"@vkontakte/videoplayer-shared/es2015";var un=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}},ri=class extends un{constructor(){super(),this.listeners||un.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)}},ta=class{constructor(){Object.defineProperty(this,"signal",{value:new ri,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&&(ta.prototype[Symbol.toStringTag]="AbortController",ri.prototype[Symbol.toStringTag]="AbortSignal");function ln(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 Sl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!ln({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 p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ra=ln({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),uv=ra?Sl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=ra?uv.fetch:window.fetch,LF=ra?uv.Request:window.Request,me=ra?ta:window.AbortController,$F=ra?ri:window.AbortSignal;var ec=_(Tl(),1);var vn=_(ei(),1);var gt=()=>window.ManagedMediaSource||window.MediaSource,cn=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},kv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Rv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as yn,clientChecker as Sn}from"@vkontakte/videoplayer-shared/es2015";var He=document.createElement("video"),R$='video/mp4; codecs="avc1.42000a,mp4a.40.2"',L$='video/mp4; codecs="hev1.1.6.L93.B0"',Fv='video/webm; codecs="vp09.00.10.08"',qv='video/webm; codecs="av01.0.00M.08"',$$='audio/mp4; codecs="mp4a.40.2"',M$='audio/webm; codecs="opus"',Lv,$v,ia={mms:cn(),mse:kv(),hls:!!((Lv=He.canPlayType)!=null&&Lv.call(He,"application/x-mpegurl")||($v=He.canPlayType)!=null&&$v.call(He,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Mv,Dv,Ae={mp4:!!((Mv=He.canPlayType)!=null&&Mv.call(He,"video/mp4")),webm:!!((Dv=He.canPlayType)!=null&&Dv.call(He,"video/webm")),cmaf:!0},pn,Cv,hn,Vv,mn,Ov,fn,Bv,bn,_v,gn,Nv,ke={h264:!!((Cv=(pn=gt())==null?void 0:pn.isTypeSupported)!=null&&Cv.call(pn,R$)),h265:!!((Vv=(hn=gt())==null?void 0:hn.isTypeSupported)!=null&&Vv.call(hn,L$)),vp9:!!((Ov=(mn=gt())==null?void 0:mn.isTypeSupported)!=null&&Ov.call(mn,Fv)),av1:!!((Bv=(fn=gt())==null?void 0:fn.isTypeSupported)!=null&&Bv.call(fn,qv)),aac:!!((_v=(bn=gt())==null?void 0:bn.isTypeSupported)!=null&&_v.call(bn,$$)),opus:!!((Nv=(gn=gt())==null?void 0:gn.isTypeSupported)!=null&&Nv.call(gn,M$))},ii=(ke.h264||ke.h265)&&ke.aac,pr,D$=()=>A(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(L(E({},a),{video:L(E({},a.video),{contentType:qv})})),window.navigator.mediaCapabilities.decodingInfo(L(E({},a),{video:L(E({},a.video),{contentType:Fv})}))]);pr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{D$()}catch(a){console.error(a)}var ai=ia.hls&&Ae.mp4,Uv=()=>Object.keys(ke).filter(a=>ke[a]),Hv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ia.mse&&(!r||!!window.MediaStreamTrack)||ia.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Ae.mp4&&ii;case"DASH_WEBM":return i&&Ae.webm&&ke.vp9&&ke.opus;case"DASH_WEBM_AV1":return i&&Ae.webm&&ke.av1&&ke.opus;case"DASH_STREAMS":return i&&(Ae.mp4&&ii||Ae.webm&&(ke.vp9||ke.av1)&&(ke.opus||ke.aac));case"DASH_LIVE":return i&&Ae.mp4&&ii;case"DASH_LIVE_CMAF":return i&&Ae.mp4&&ii&&Ae.cmaf;case"DASH_ONDEMAND":return i&&Ae.mp4&&ii;case"HLS":case"HLS_ONDEMAND":return ai||e&&i&&Ae.mp4&&ii;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ai;case"MPEG":return Ae.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ia.webrtc&&ia.ws&&ke.h264&&(Ae.mp4||Ae.webm);default:return yn(s)}})},dn=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 pr?pr[t].smooth?[t,e]:pr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return pr?pr[t].powerEfficient?[t,e]:pr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:yn(a)}return[e,t]},jv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...dn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(Sn.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",...dn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...dn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...dn(a),...i,"HLS","HLS_ONDEMAND"];default:yn(e)}return ai?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Qv=({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=Sn.isMac&&Sn.isSafari;if(Sn.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:yn(a)}else ai&&!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"]},Il=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Gv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,vn.default)(t.value.split("."),0)}for(let t of a){let r=(0,vn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,vn.default)(e.value.split("."),0)};var hS=_(pS(),1);import{ErrorCategory as sa}from"@vkontakte/videoplayer-shared/es2015";var mS=a=>{if(!a)return{id:"EmptyResponse",category:sa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:sa.NETWORK,message:`UV Error ${a}`};let e=(0,hS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:sa.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:sa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:sa.PARSER,message:"Response is valid XML, but parser failed"}};var Ft=(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 Sr,clientChecker as wD,combine as li,ErrorCategory as jt,filter as _a,filterChanged as kn,flattenObject as Na,fromEvent as yr,getTraceSubscriptionMethod as AD,interval as Zl,isNonNullable as Dy,map as Fa,merge as Tr,now as kD,Subject as Cy,Subscription as Vy,tap as RD,throttle as LD,ValueSubject as re}from"@vkontakte/videoplayer-shared/es2015";var In=_(Xe(),1),oi=_(ei(),1),En=_(Tl(),1);var K$=(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)},X$=a=>window.clearTimeout(a),fS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),bS=!fS(window.requestIdleCallback)||!fS(window.cancelIdleCallback),Al=bS?K$:window.requestIdleCallback,na=bS?X$:window.cancelIdleCallback;var Py=_(zs(),1);import{assertNever as J$,ErrorCategory as gS,clientChecker as kl,Subject as vS}from"@vkontakte/videoplayer-shared/es2015";var Z$=18,SS=!1;try{SS=kl.isSafari&&!!kl.macVersion&&kl.macVersion<=Z$}catch(a){console.error(a)}var Rl=class{constructor(e){this.bufferFull$=new vS;this.error$=new vS;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!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:gS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return A(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 A(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 A(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};SS&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)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:gS.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:J$(t)}}},yS=Rl;var Ll=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 fr,assertNonNullable as je,clientChecker as fD,ErrorCategory as Ut,fromEvent as Wl,getExponentialDelay as Yl,isNonNullable as $a,isNullable as Le,now as Tn,once as bD,Subject as gD,Subscription as vD,ValueSubject as br}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 si=class extends G{};var oa=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 ua=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 la=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 ca=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 da=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pa=class extends G{constructor(e,t){super(e,t),this.data=this.content}};var hr=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 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){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 ba=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ga=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 va=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Sa=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 ya=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ta=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ia=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ea=class extends G{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var xa=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 Pa=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 wa=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 tM={ftyp:ua,moov:la,mvhd:ca,moof:da,mdat:pa,sidx:hr,trak:ha,mdia:va,mfhd:Ia,tkhd:Sa,traf:Ea,tfhd:xa,tfdt:Pa,trun:wa,minf:ya,sv3d:ma,st3d:fa,prhd:ba,proj:Ta,equi:ga,uuid:oa,unknown:si},vt=class a{constructor(e={}){this.options=E({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=tM[e];return r?new r(t,new a):new si(t,new a)}};var qt=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 iM=new TextDecoder("ascii"),aM=a=>iM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",sM=a=>{let e=new hr(a,new vt),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})},nM=(a,e)=>{let r=new vt().parse(a),i=new qt(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)},oM=a=>{let t=new vt().parse(a),r=new qt(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},uM=a=>{var i;let t=new vt().parse(a);return(i=new qt(t).find("sidx"))==null?void 0:i.timescale},lM=(a,e)=>{let r=new vt().parse(a),s=new qt(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},cM=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 vt().parse(a),i=new qt(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},TS={validateData:aM,parseInit:cM,getIndexRange:()=>{},parseSegments:sM,parseFeedableSegmentChunk:nM,getChunkEndTime:lM,getServerLatencyTimestamps:oM,getTimescaleFromIndex:uM};var ka=_(Xe(),1);import{assertNonNullable as Ml,isNonNullable as PS,isNullable as pM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as dM}from"@vkontakte/videoplayer-shared/es2015";var IS={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"}},ES=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=Aa(a,t),i=r in IS,s=i?IS[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=Aa(u),d=l*at(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Aa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*at(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*at(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*at(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},et=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Aa(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:dM(e)}},mr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=ES(r);if(!e(i))return;i.type==="master"&&mr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},xS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=ES(a);return mr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=et(o,n):s===17026?t=et(o,n):s===17029&&(r=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var wS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],hM=[231,22612,22743,167,171,163,160,175],mM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return mr(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=et(m,h);l=Aa(g)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=et(m,h):p===17545?i=et(m,h):p===21420&&l===475249515?u=et(m,h):p===374648427?mr(m,({tag:g,type:v,value:S})=>g===30321?(c=et(S,v)===1,!1):!0):s&&n&&(0,ka.default)(wS,p)&&(o=!0),!o}),Ml(e,"Failed to parse webm Segment start"),Ml(t,"Failed to parse webm Segment end"),Ml(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}}}},fM=a=>{if(pM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},bM=(a,e)=>{let t=!1,r=!1,i=o=>PS(o.time)&&PS(o.position),s=[],n;return mr(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=et(l,u));break;case 183:break;case 241:n&&(n.position=et(l,u));break;default:t&&(0,ka.default)(wS,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}}})},gM=a=>{let e=0,t=!1;try{mr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ka.default)(hM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ka.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},AS={validateData:xS,parseInit:mM,getIndexRange:fM,parseSegments:bM,parseFeedableSegmentChunk:gM};var Ra=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return AS;case"mp4":return TS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var jl=_(WS(),1),Sy=_(qr(),1),yy=_(ly(),1),Ty=_(ei(),1),Ql=_(Jr(),1);var cy=_(Xe(),1),_l=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,cy.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as mD,isNullable as gy}from"@vkontakte/videoplayer-shared/es2015";var dy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var py=a=>{var e;try{let t=pD(),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 pD(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
62
+ [selected audio track] ${f==null?void 0:f.id}
63
+ `}),f&&qg(i,u,f,o)};var ue=a=>new URL(a).hostname;import{assertNever as Jg,assertNonNullable as Zg,combine as G$,debounce as Q$,ErrorCategory as ev,filter as tv,filterChanged as W$,isNonNullable as hl,map as nn,merge as rv,observableFrom as Y$,once as z$,Subscription as K$,ValueSubject as fl,videoQualityToHeight as X$,videoSizeToQuality as J$}from"@vkontakte/videoplayer-shared/es2015";var jg=B(Xe(),1);var Hg=a=>{if(a instanceof DOMException&&(0,jg.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"))},Ae=(a,e)=>w(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!Hg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return Hg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as rn,isNullable as A$,assertNonNullable as Xi}from"@vkontakte/videoplayer-shared/es2015";var Qg=B(Zr(),1);import{isNonNullable as Gg,assertNonNullable as tn,now as P$}from"@vkontakte/videoplayer-shared/es2015";function le(){return P$()}function ll(a){return le()-a}function cl(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 Wg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ri(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;tn(c);let R=ll(c),q;if(R<b){q=b-R,setTimeout(g,q);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,L()},v=R=>(s=R,F),S=R=>(d=R,F),y=()=>(h="json",F),x=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},E=R=>(p=R,F),L=()=>{c=le(),n=new i,n.open("get",a);let R=0,q,_=0,Y=()=>(tn(c),Math.max(c,Math.max(q||0,_||0)));if(s&&n.addEventListener("progress",k=>{let T=le();s.updateChunk&&k.loaded>R&&(s.updateChunk(Y(),k.loaded-R),R=k.loaded,q=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>x())),n.addEventListener("load",()=>{if(u)return;tn(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let T=n.response.byteLength-R;T&&s.updateChunk&&s.updateChunk(Y(),T)}n.responseType==="json"&&!(0,Qg.default)(n.response).length?x():(d&&d(),e(n.response))}else x()}),n.addEventListener("error",()=>{x()}),p){let k=()=>{tn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(_=le(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),F},F={withBitrateReporting:v,withParallel:E,withJSONResponse:y,withRetryCount:R=>(l=R,F),withRetryInterval:(R,q)=>(Gg(R)&&(b=R),Gg(q)&&(f=q),F),withTimeout:R=>(o=R,F),withFinally:S,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return F}var zi=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 Yg=B(Zr(),1);var Ki=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=le(),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=le()-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=ri(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=le()}_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=le();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,Yg.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 k$}from"@vkontakte/videoplayer-shared/es2015";var an=1e4,dl=3;var R$=6e4,$$=10,L$=1,M$=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 k$,this.chunkRateEstimator=new zi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=cl(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=cl(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||rn(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=()=>{Wg(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 Ki(dl,an,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 x=s&&(!c||c===this.rep);return x||t("Not running!"),x},p=(x,E,L)=>{u&&u.abort(),u=ri(this.urlResolver.resolve(x,!1),E,L,()=>this._retryCallback()).withTimeout(an).withBitrateReporting(this.bitrateSwitcher).withRetryCount(dl).withFinally(()=>{u=null}).send()},h=(x,E,L)=>{Xi(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(x,!1),E,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=x=>{let E=r.playbackRate;r.playbackRate!==x&&(t(`Playback rate switch: ${E}=>${x}`),r.playbackRate=x)},b=x=>{this.lowLatency=x,t(`lowLatency changed to ${x}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let x=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let L=le()-1e4,O=0;for(let M=0;M<this.bufferStates.length;M++){let N=this.bufferStates[M];x=Math.min(x,N.buf),N.ts<L&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${x} drop=${O} jitter=${this.sourceJitter}`);let J=x-L$;this.sourceJitter>=0?J-=this.sourceJitter/2:this.sourceJitter-=1,J>3?f(1.15):J>1?f(1.1):J>.3?f(1.05):f(1)}},v=x=>{let E,L=()=>E&&E.start?E.start.length:0,O=k=>E.start[k]/1e3,J=k=>E.dur[k]/1e3,M=k=>E.fragIndex+k,N=(k,T)=>({chunkIdx:M(k),startTS:O(k),dur:J(k),discontinuity:T}),F=()=>{let k=0;if(E&&E.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,D=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Q=T;this.sourceJitter>1&&(Q+=this.sourceJitter-1);let H=E.dur.length-1;for(;H>=0&&(Q-=E.dur[H],!(Q<=0));--H);k=Math.min(H,E.dur.length-1-D),k=Math.max(k,0)}return N(k,!0)},R=k=>{let T=L();if(!(T<=0)){if(rn(k)){for(let D=0;D<T;D++)if(O(D)>k)return N(D)}return F()}},q=k=>{let T=L(),D=k?k.chunkIdx+1:0,Q=D-E.fragIndex;if(!(T<=0)){if(!k||Q<0||Q-T>$$)return t(`Resync: offset=${Q} bChunks=${T} chunk=`+JSON.stringify(k)),F();if(!(Q>=T))return N(D-E.fragIndex,!1)}},_=(k,T,D)=>{l&&l.abort(),l=ri(this.urlResolver.resolve(k,!0,this.lowLatency),T,D,()=>this._retryCallback()).withTimeout(an).withRetryCount(dl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,T)=>{_(x,D=>{if(!d())return;E=D;let Q=!!E.lowLatency;Q!==this.lowLatency&&b(Q);let H=0;for(let Be=0;Be<E.dur.length;++Be)H+=E.dur[Be];H>0&&(Xi(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(H/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,k(R(T))},()=>this._handleNetworkError())},nextChunk:q}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Xi(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:x=>{let{videoElement:E,logger:L}=this.params,O=v(e.jidxUrl),J,M,N,F,R=0,q,_,Y,k=()=>{q&&(clearTimeout(q),q=void 0);let j=Math.max(M$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ce=R+j,de=le(),_e=Math.min(1e4,ce-de);R=de;let Et=()=>{l||d()&&O.seek(()=>{d()&&(R=le(),T(),k())})};_e>0?q=window.setTimeout(()=>{this.paused?k():Et()},_e):Et()},T=()=>{let j;for(;j=O.nextChunk(F);)F=j,It(j);let ce=O.nextChunk(N);if(ce){if(N&&ce.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?k():(S(),this._initPlayerWith(e));return}Be(ce)}else k()},D=(j,ce)=>{if(!d()||!this.sourceBuffer)return;let de,_e,Et,Pr=xt=>{window.setTimeout(()=>{d()&&D(j,ce)},xt)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),Pr(100);else{let xt=le(),Kt=E.currentTime;!this.paused&&E.buffered.length>1&&_===Kt&&xt-Y>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),_!==Kt&&(_=Kt,Y=xt);let wr=this._getBufferSizeSec();if(wr>30)L(`Buffered ${wr} seconds; delaying appendBuffer`),Pr(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:xt,buf:wr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ce&&ce()}catch(fi){if(fi.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Et=this.sourceBuffer.buffered.length,Et!==0&&(de=this.sourceBuffer.buffered.start(0),_e=Kt,_e-de>4&&this.sourceBuffer.remove(de,_e-3)),Pr(1e3);else throw fi}}},Q=()=>{M&&J&&(L([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(N)]),D(M,function(){M=null,T()}))},H=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),Be=j=>{d()&&h(H(j),(ce,de)=>{if(d()){if(de/=1e3,M=ce,N=j,n=j.startTS,de){let _e=Math.min(10,j.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*_e:_e}Q()}},()=>this._handleNetworkError())},It=j=>{d()&&(Xi(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(H(j),!1)))},xr=j=>{d()&&(e.cachedHeader=j,D(j,()=>{J=!0,Q()}))};s=!0,O.seek(j=>{if(d()){if(R=le(),!j){k();return}F=j,!A$(x)||j.startTS>x?Be(j):(N=j,T())}},x),e.cachedHeader?xr(e.cachedHeader):p(e.headerUrl,xr,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),rn(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,Xi(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return rn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=le();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&ll(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=le();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ri(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(an).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;Ae(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))},R$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Xg=B(Ur(),1);import{debounce as D$,filter as zg,fromEvent as C$,interval as O$,isHigher as V$,isInvariantQuality as B$,isLower as _$,merge as N$,Subject as Kg,Subscription as F$}from"@vkontakte/videoplayer-shared/es2015";var pl=class{constructor(){this.onDroopedVideoFramesLimit$=new Kg;this.subscription=new F$;this.playing=!1;this.tracks=[];this.forceChecker$=new Kg;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&&!B$(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&&V$(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(C$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=O$(this.droppedFramesChecker.checkTime).pipe(zg(()=>this.playing),zg(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(D$(this.droppedFramesChecker.checkTime)),r=N$(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,Xg.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>_$(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}},sn=pl;import{map as q$,Observable as U$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as H$}from"@vkontakte/videoplayer-shared/es2015";var Zi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var j$=(a,e)=>new U$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Zi()))},I(I({},r),e));i.observe(a);let s=H$(document,"visibilitychange").pipe(q$(n=>!document.hidden||Zi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),He=j$;var Z$=["paused","playing","ready"],eL=["paused","playing","ready"],ea=class{constructor(e){this.subscription=new K$;this.videoState=new C("stopped");this.representations$=new fl([]);this.droppedFramesManager=new sn;this.maxSeekBackTime$=new fl(1/0);this.zeroTime$=new fl(void 0);this.liveOffset=new mt;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:ev.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=_t(u.name))!=null?r:J$(u.video),d=u.bitrate/1e3,p=I({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((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),hl(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,ml.default)(eL,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,ml.default)(Z$,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 Jg(e)}};this.textTracksManager=new qe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:ev.WTF,message:"DashLiveProvider internal logic error",thrown:i})};rv(this.videoState.stateChangeStarted$.pipe(nn(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(nn(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Ee(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(ue(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=we(this.video);this.subscription.add(this.representations$.pipe(nn(i=>i.map(({track:s})=>s)),tv(i=>!!i.length),z$()).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(W$(),nn(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(G$({zeroTime:this.zeroTime$.pipe(tv(hl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Pe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Fe(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(He(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&X$(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 Jg(i.to)}},t)).add(rv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Y$(["init"])).pipe(Q$(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),xe(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,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&hl(t)?t:Ft(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=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.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;Zg(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;Zg(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 iv=ea;var Fy=B(Xe(),1);var lt=(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 UD,assertNonNullable as HD,debounce as jD,ErrorCategory as tc,filter as By,filterChanged as qa,fromEvent as GD,isNonNullable as _y,map as rc,merge as Dn,observableFrom as ic,once as Ny,Subscription as QD}from"@vkontakte/videoplayer-shared/es2015";var on=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}},ii=class extends on{constructor(){super(),this.listeners||on.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)}},ta=class{constructor(){Object.defineProperty(this,"signal",{value:new ii,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&&(ta.prototype[Symbol.toStringTag]="AbortController",ii.prototype[Symbol.toStringTag]="AbortSignal");function un(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 bl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!un({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 p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ra=un({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),av=ra?bl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=ra?av.fetch:window.fetch,SF=ra?av.Request:window.Request,me=ra?ta:window.AbortController,yF=ra?ii:window.AbortSignal;var Xl=B(vl(),1);var gn=B(ti(),1);var gt=()=>window.ManagedMediaSource||window.MediaSource,ln=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},xv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Pv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as Sn,clientChecker as vn}from"@vkontakte/videoplayer-shared/es2015";var je=document.createElement("video"),PL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',wL='video/mp4; codecs="hev1.1.6.L93.B0"',Vv='video/webm; codecs="vp09.00.10.08"',Bv='video/webm; codecs="av01.0.00M.08"',AL='audio/mp4; codecs="mp4a.40.2"',kL='audio/webm; codecs="opus"',wv,Av,ia={mms:ln(),mse:xv(),hls:!!((wv=je.canPlayType)!=null&&wv.call(je,"application/x-mpegurl")||(Av=je.canPlayType)!=null&&Av.call(je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},kv,Rv,ke={mp4:!!((kv=je.canPlayType)!=null&&kv.call(je,"video/mp4")),webm:!!((Rv=je.canPlayType)!=null&&Rv.call(je,"video/webm")),cmaf:!0},dn,$v,pn,Lv,hn,Mv,fn,Dv,mn,Cv,bn,Ov,Re={h264:!!(($v=(dn=gt())==null?void 0:dn.isTypeSupported)!=null&&$v.call(dn,PL)),h265:!!((Lv=(pn=gt())==null?void 0:pn.isTypeSupported)!=null&&Lv.call(pn,wL)),vp9:!!((Mv=(hn=gt())==null?void 0:hn.isTypeSupported)!=null&&Mv.call(hn,Vv)),av1:!!((Dv=(fn=gt())==null?void 0:fn.isTypeSupported)!=null&&Dv.call(fn,Bv)),aac:!!((Cv=(mn=gt())==null?void 0:mn.isTypeSupported)!=null&&Cv.call(mn,AL)),opus:!!((Ov=(bn=gt())==null?void 0:bn.isTypeSupported)!=null&&Ov.call(bn,kL))},ai=(Re.h264||Re.h265)&&Re.aac,fr,RL=()=>w(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($(I({},a),{video:$(I({},a.video),{contentType:Bv})})),window.navigator.mediaCapabilities.decodingInfo($(I({},a),{video:$(I({},a.video),{contentType:Vv})}))]);fr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{RL()}catch(a){console.error(a)}var si=ia.hls&&ke.mp4,_v=()=>Object.keys(Re).filter(a=>Re[a]),Nv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ia.mse&&(!r||!!window.MediaStreamTrack)||ia.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&ke.mp4&&ai;case"DASH_WEBM":return i&&ke.webm&&Re.vp9&&Re.opus;case"DASH_WEBM_AV1":return i&&ke.webm&&Re.av1&&Re.opus;case"DASH_STREAMS":return i&&(ke.mp4&&ai||ke.webm&&(Re.vp9||Re.av1)&&(Re.opus||Re.aac));case"DASH_LIVE":return i&&ke.mp4&&ai;case"DASH_LIVE_CMAF":return i&&ke.mp4&&ai&&ke.cmaf;case"DASH_ONDEMAND":return i&&ke.mp4&&ai;case"HLS":case"HLS_ONDEMAND":return si||e&&i&&ke.mp4&&ai;case"HLS_LIVE":case"HLS_LIVE_CMAF":return si;case"MPEG":return ke.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ia.webrtc&&ia.ws&&Re.h264&&(ke.mp4||ke.webm);default:return Sn(s)}})},cn=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 fr?fr[t].smooth?[t,e]:fr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return fr?fr[t].powerEfficient?[t,e]:fr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:Sn(a)}return[e,t]},Fv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...cn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(vn.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",...cn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...cn(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...cn(a),...i,"HLS","HLS_ONDEMAND"];default:Sn(e)}return si?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},qv=({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=vn.isMac&&vn.isSafari;if(vn.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:Sn(a)}else si&&!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"]},Sl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Uv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,gn.default)(t.value.split("."),0)}for(let t of a){let r=(0,gn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,gn.default)(e.value.split("."),0)};var lS=B(uS(),1);import{ErrorCategory as sa}from"@vkontakte/videoplayer-shared/es2015";var cS=a=>{if(!a)return{id:"EmptyResponse",category:sa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:sa.NETWORK,message:`UV Error ${a}`};let e=(0,lS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:sa.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:sa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:sa.PARSER,message:"Response is valid XML, but parser failed"}};var qt=(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 zl,assertNonNullable as yr,clientChecker as ID,combine as di,ErrorCategory as Qt,filter as Ba,filterChanged as An,flattenObject as _a,fromEvent as Tr,getTraceSubscriptionMethod as ED,interval as Kl,isNonNullable as Ry,map as Na,merge as Ir,now as xD,Subject as $y,Subscription as Ly,tap as PD,throttle as wD,ValueSubject as ie}from"@vkontakte/videoplayer-shared/es2015";var Tn=B(Xe(),1),li=B(ti(),1),In=B(vl(),1);var QL=(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)},WL=a=>window.clearTimeout(a),dS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),pS=!dS(window.requestIdleCallback)||!dS(window.cancelIdleCallback),xl=pS?QL:window.requestIdleCallback,na=pS?WL:window.cancelIdleCallback;var Ty=B(zs(),1);import{assertNever as YL,ErrorCategory as hS,clientChecker as Pl,Subject as fS}from"@vkontakte/videoplayer-shared/es2015";var zL=18,mS=!1;try{mS=Pl.isSafari&&!!Pl.macVersion&&Pl.macVersion<=zL}catch(a){console.error(a)}var wl=class{constructor(e){this.bufferFull$=new fS;this.error$=new fS;this.queue=[];this.currentTask=null;this.destroyed=!1;this.abortRequested=!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:hS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return w(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 w(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 w(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};mS&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)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:hS.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:YL(t)}}},bS=wl;var Al=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 Ht,assertNonNullable as $e,clientChecker as dD,ErrorCategory as jt,fromEvent as jl,getExponentialDelay as Gl,isNonNullable as ui,isNullable as be,now as yn,once as pD,Subject as hD,Subscription as fD,ValueSubject as gr}from"@vkontakte/videoplayer-shared/es2015";var W=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 ni=class extends W{};var oa=class extends W{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 ua=class extends W{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 la=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Z=class extends W{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var ca=class extends Z{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 da=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var pa=class extends W{constructor(e,t){super(e,t),this.data=this.content}};var mr=class extends Z{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 ha=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ma=class extends Z{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 ba=class extends Z{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ga=class extends Z{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var va=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Sa=class extends Z{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 ya=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ta=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ia=class extends Z{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ea=class extends W{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var xa=class extends Z{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 Pa=class extends Z{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 wa=class extends Z{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 XL={ftyp:ua,moov:la,mvhd:ca,moof:da,mdat:pa,sidx:mr,trak:ha,mdia:va,mfhd:Ia,tkhd:Sa,traf:Ea,tfhd:xa,tfdt:Pa,trun:wa,minf:ya,sv3d:fa,st3d:ma,prhd:ba,proj:Ta,equi:ga,uuid:oa,unknown:ni},vt=class a{constructor(e={}){this.options=I({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=XL[e];return r?new r(t,new a):new ni(t,new a)}};var Ut=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"),eM=a=>ZL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",tM=a=>{let e=new mr(a,new vt),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})},rM=(a,e)=>{let r=new vt().parse(a),i=new Ut(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)},iM=a=>{let t=new vt().parse(a),r=new Ut(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},aM=a=>{var i;let t=new vt().parse(a);return(i=new Ut(t).find("sidx"))==null?void 0:i.timescale},sM=(a,e)=>{let r=new vt().parse(a),s=new Ut(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},nM=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 vt().parse(a),i=new Ut(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},gS={validateData:eM,parseInit:nM,getIndexRange:()=>{},parseSegments:tM,parseFeedableSegmentChunk:rM,getChunkEndTime:sM,getServerLatencyTimestamps:iM,getTimescaleFromIndex:aM};var ka=B(Xe(),1);import{assertNonNullable as Rl,isNonNullable as TS,isNullable as uM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as oM}from"@vkontakte/videoplayer-shared/es2015";var vS={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"}},SS=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=Aa(a,t),i=r in vS,s=i?vS[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=Aa(u),d=l*at(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},Aa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*at(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*at(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*at(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},et=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return Aa(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:oM(e)}},br=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=SS(r);if(!e(i))return;i.type==="master"&&br(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},yS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=SS(a);return br(i.value,({tag:s,type:n,value:o})=>(s===17143?e=et(o,n):s===17026?t=et(o,n):s===17029&&(r=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var IS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],lM=[231,22612,22743,167,171,163,160,175],cM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return br(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=et(f,h);l=Aa(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=et(f,h):p===17545?i=et(f,h):p===21420&&l===475249515?u=et(f,h):p===374648427?br(f,({tag:g,type:v,value:S})=>g===30321?(c=et(S,v)===1,!1):!0):s&&n&&(0,ka.default)(IS,p)&&(o=!0),!o}),Rl(e,"Failed to parse webm Segment start"),Rl(t,"Failed to parse webm Segment end"),Rl(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}}}},dM=a=>{if(uM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},pM=(a,e)=>{let t=!1,r=!1,i=o=>TS(o.time)&&TS(o.position),s=[],n;return br(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=et(l,u));break;case 183:break;case 241:n&&(n.position=et(l,u));break;default:t&&(0,ka.default)(IS,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}}})},hM=a=>{let e=0,t=!1;try{br(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,ka.default)(lM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,ka.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},ES={validateData:yS,parseInit:cM,getIndexRange:dM,parseSegments:pM,parseFeedableSegmentChunk:hM};var Ra=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return ES;case"mp4":return gS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var ql=B(HS(),1),my=B(Ur(),1),by=B(sy(),1),gy=B(ti(),1),Ul=B(Zr(),1);var ny=B(Xe(),1),Ol=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,ny.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as cD,isNullable as hy}from"@vkontakte/videoplayer-shared/es2015";var oy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var uy=a=>{var e;try{let t=uD(),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 uD(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
64
64
  (?<language>${`(?:[a-z]{2,3}(?:-${a})?|[a-z]{4}|[a-z]{5,8})`})
65
65
  (-(?<script>[a-z]{4}))?
66
66
  (-(?<region>(?:[a-z]{2}|[0-9]{3})))?
67
67
  (?<variants>(?:-(?:[a-z0-9]{5,8}|[0-9][a-z0-9]{3}))*)
68
68
  (?<extensions>(?:-[0-9a-wy-z](?:-[a-z0-9]{2,8})+)*)
69
69
  (?:-(?<privateuse>(?:${e})))?
70
- `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Fl=_(ei(),1);import{videoSizeToQuality as hD}from"@vkontakte/videoplayer-shared/es2015";var hy=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?Bt(s):void 0)!=null?u:hD({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},my=({id:a,bitrate:e})=>({id:a,bitrate:e}),fy=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),by=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),ql=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Fl.default)(r.split("."),0),isDefault:i}),Ul=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Fl.default)(i.split("."),0)}),Hl=a=>"url"in a,Se=a=>a.type==="template",La=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var vy=a=>{if(!(a!=null&&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},St=(a,e)=>{let t=a;t=(0,jl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,Sy.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,jl.default)(t,n,(o,u)=>gy(s)?o:gy(u)?s:(0,yy.default)(s,parseInt(u,10),"0"))}return t},Iy=(a,e)=>{var x,$,V,X,M,F,q,R,U,N,W,k,T,B,D,le,Me,pi,Er,j,ce,fe,be,It,xr,Et,Yt,Pr,hi,Ic,Ec,xc,Pc,wc,Ac,kc,Rc,Lc,$c,Mc,Dc,Cc,Vc,Oc,Bc,_c,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Qe=>{var K,zt;return(zt=(K=Qe.textContent)==null?void 0:K.trim())!=null?zt:""}),o=(x=(0,Ty.default)(n,0))!=null?x:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],m=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((Qe,K)=>L(E({},Qe),{[K.id]:K.children}),{}),v=b.reduce((Qe,K)=>L(E({},Qe),{[K.id]:K.getAttribute("duration")}),{});p?d=vy(p):(0,Ql.default)(v).filter(Qe=>Qe).length&&!u?d=(0,Ql.default)(v).reduce((Qe,K)=>{var zt;return Qe+((zt=vy(K))!=null?zt:0)},0):m&&(d=parseInt(m,10));let S=0,y=(V=($=s.getAttribute("profiles"))==null?void 0:$.split(","))!=null?V:[];for(let Qe of b.map(K=>K.id))for(let K of g[Qe]){let zt=(X=K.getAttribute("id"))!=null?X:"id"+(S++).toString(10),mi=(M=K.getAttribute("mimeType"))!=null?M:"",Kn=(F=K.getAttribute("codecs"))!=null?F:"",Xn=(q=K.getAttribute("contentType"))!=null?q:mi==null?void 0:mi.split("/")[0],FT=(U=(R=K.getAttribute("profiles"))==null?void 0:R.split(","))!=null?U:[],Zc=(W=py((N=K.getAttribute("lang"))!=null?N:""))!=null?W:{},qT=(B=(T=(k=K.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:T.trim())!=null?B:void 0,UT=K.querySelectorAll("Representation"),HT=K.querySelector("SegmentTemplate"),jT=(le=(D=K.querySelector("Role"))==null?void 0:D.getAttribute("value"))!=null?le:void 0,wr=Xn,ee={id:zt,language:Zc.language,isDefault:jT==="main",label:qT,codecs:Kn,hdr:wr==="video"&&_l(Kn),mime:mi,representations:[]};for(let Y of UT){let xt=(Me=Y.getAttribute("lang"))!=null?Me:void 0,fi=(pi=Y.getAttribute("label"))!=null?pi:void 0,rs=(ce=(j=(Er=Y.querySelector("BaseURL"))==null?void 0:Er.textContent)==null?void 0:j.trim())!=null?ce:"",Kt=new URL(rs||o,e).toString(),Pt=(fe=Y.getAttribute("mimeType"))!=null?fe:mi,is=(It=(be=Y.getAttribute("codecs"))!=null?be:Kn)!=null?It:"",as;if(Xn==="text"){let wt=Y.getAttribute("id")||"",ss=((xr=Zc.privateuse)==null?void 0:xr.includes("x-auto"))||wt.includes("_auto"),Xt=Y.querySelector("SegmentTemplate");if(Xt){let bi={representationId:(Et=Y.getAttribute("id"))!=null?Et:void 0,bandwidth:(Yt=Y.getAttribute("bandwidth"))!=null?Yt:void 0},ns=parseInt((Pr=Y.getAttribute("bandwidth"))!=null?Pr:"",10)/1e3,os=(Ic=parseInt((hi=Xt.getAttribute("startNumber"))!=null?hi:"",10))!=null?Ic:1,Ar=parseInt((Ec=Xt.getAttribute("timescale"))!=null?Ec:"",10),Jn=(xc=Xt.querySelectorAll("SegmentTimeline S"))!=null?xc:[],kr=Xt.getAttribute("media");if(!kr)continue;let us=[],ls=0,cs="",Rr=0,gi=os,ge=0;for(let Ge of Jn){let Jt=parseInt((Pc=Ge.getAttribute("d"))!=null?Pc:"",10),_e=parseInt((wc=Ge.getAttribute("r"))!=null?wc:"",10)||0,At=parseInt((Ac=Ge.getAttribute("t"))!=null?Ac:"",10);ge=Number.isFinite(At)?At:ge;let Zt=Jt/Ar*1e3,kt=ge/Ar*1e3;for(let rt=0;rt<_e+1;rt++){let Rt=St(kr,L(E({},bi),{segmentNumber:gi.toString(10),segmentTime:(ge+rt*Jt).toString(10)})),Lr=(kt!=null?kt:0)+rt*Zt,Si=Lr+Zt;gi++,us.push({time:{from:Lr,to:Si},url:Rt})}ge+=(_e+1)*Jt,ls+=(_e+1)*Zt}Rr=ge/Ar*1e3,cs=St(kr,L(E({},bi),{segmentNumber:gi.toString(10),segmentTime:ge.toString(10)}));let vi={time:{from:Rr,to:1/0},url:cs},dt={type:"template",baseUrl:Kt,segmentTemplateUrl:kr,initUrl:"",totalSegmentsDurationMs:ls,segments:us,nextSegmentBeyondManifest:vi,timescale:Ar};as={id:wt,kind:"text",segmentReference:dt,profiles:[],duration:d,bitrate:ns,mime:"",codecs:"",width:0,height:0,isAuto:ss}}else as={id:wt,isAuto:ss,kind:"text",url:Kt}}else{let wt=(Rc=(kc=Y.getAttribute("contentType"))!=null?kc:Pt==null?void 0:Pt.split("/")[0])!=null?Rc:Xn,ss=($c=(Lc=K.getAttribute("profiles"))==null?void 0:Lc.split(","))!=null?$c:[],Xt=parseInt((Mc=Y.getAttribute("width"))!=null?Mc:"",10),bi=parseInt((Dc=Y.getAttribute("height"))!=null?Dc:"",10),ns=parseInt((Cc=Y.getAttribute("bandwidth"))!=null?Cc:"",10)/1e3,os=(Vc=Y.getAttribute("frameRate"))!=null?Vc:"",Ar=(Oc=Y.getAttribute("quality"))!=null?Oc:void 0,Jn=os?dy(os):void 0,kr=(Bc=Y.getAttribute("id"))!=null?Bc:"id"+(S++).toString(10),us=wt==="video"?`${bi}p`:wt==="audio"?`${ns}Kbps`:is,ls=`${kr}@${us}`,cs=[...y,...FT,...ss],Rr,gi=Y.querySelector("SegmentBase"),ge=(_c=Y.querySelector("SegmentTemplate"))!=null?_c:HT;if(gi){let dt=(Fc=(Nc=Y.querySelector("SegmentBase Initialization"))==null?void 0:Nc.getAttribute("range"))!=null?Fc:"",[Ge,Jt]=dt.split("-").map(Rt=>parseInt(Rt,10)),_e={from:Ge,to:Jt},At=(qc=Y.querySelector("SegmentBase"))==null?void 0:qc.getAttribute("indexRange"),[Zt,kt]=At?At.split("-").map(Rt=>parseInt(Rt,10)):[],rt=At?{from:Zt,to:kt}:void 0;Rr={type:"byteRange",url:Kt,initRange:_e,indexRange:rt}}else if(ge){let dt={representationId:(Uc=Y.getAttribute("id"))!=null?Uc:void 0,bandwidth:(Hc=Y.getAttribute("bandwidth"))!=null?Hc:void 0},Ge=parseInt((jc=ge.getAttribute("timescale"))!=null?jc:"",10),Jt=(Qc=ge.getAttribute("initialization"))!=null?Qc:"",_e=ge.getAttribute("media"),At=(Wc=parseInt((Gc=ge.getAttribute("startNumber"))!=null?Gc:"",10))!=null?Wc:1,Zt=St(Jt,dt);if(!_e)throw new ReferenceError("No media attribute in SegmentTemplate");let kt=(Yc=ge.querySelectorAll("SegmentTimeline S"))!=null?Yc:[],rt=[],Rt=0,Lr="",Si=0;if(kt.length){let ds=At,We=0;for(let $r of kt){let it=parseInt((zc=$r.getAttribute("d"))!=null?zc:"",10),er=parseInt((Kc=$r.getAttribute("r"))!=null?Kc:"",10)||0,ps=parseInt((Xc=$r.getAttribute("t"))!=null?Xc:"",10);We=Number.isFinite(ps)?ps:We;let Zn=it/Ge*1e3,eo=We/Ge*1e3;for(let hs=0;hs<er+1;hs++){let GT=St(_e,L(E({},dt),{segmentNumber:ds.toString(10),segmentTime:(We+hs*it).toString(10)})),ed=(eo!=null?eo:0)+hs*Zn,WT=ed+Zn;ds++,rt.push({time:{from:ed,to:WT},url:GT})}We+=(er+1)*it,Rt+=(er+1)*Zn}Si=We/Ge*1e3,Lr=St(_e,L(E({},dt),{segmentNumber:ds.toString(10),segmentTime:We.toString(10)}))}else if(mD(d)){let We=parseInt((Jc=ge.getAttribute("duration"))!=null?Jc:"",10)/Ge*1e3,$r=Math.ceil(d/We),it=0;for(let er=1;er<$r;er++){let ps=St(_e,L(E({},dt),{segmentNumber:er.toString(10),segmentTime:it.toString(10)}));rt.push({time:{from:it,to:it+We},url:ps}),it+=We}Si=it,Lr=St(_e,L(E({},dt),{segmentNumber:$r.toString(10),segmentTime:it.toString(10)}))}let QT={time:{from:Si,to:1/0},url:Lr};Rr={type:"template",baseUrl:Kt,segmentTemplateUrl:_e,initUrl:Zt,totalSegmentsDurationMs:Rt,segments:rt,nextSegmentBeyondManifest:QT,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!wt||!Pt)continue;let vi={video:"video",audio:"audio",text:"text"}[wt];if(!vi)continue;wr||(wr=vi),as={id:ls,kind:vi,segmentReference:Rr,profiles:cs,duration:d,bitrate:ns,mime:Pt,codecs:is,width:Xt,height:bi,fps:Jn,quality:Ar}}ee.language||(ee.language=xt),ee.label||(ee.label=fi),ee.mime||(ee.mime=Pt),ee.codecs||(ee.codecs=is),ee.hdr||(ee.hdr=wr==="video"&&_l(is)),ee.representations.push(as)}if(wr){let Y=i[wr].find(xt=>xt.id===ee.id);if(Y&&ee.representations.every(xt=>Se(xt.segmentReference)))for(let xt of Y.representations){let fi=ee.representations.find(Pt=>Pt.id===xt.id),rs=fi==null?void 0:fi.segmentReference,Kt=xt.segmentReference;Kt.segments.push(...rs.segments),Kt.nextSegmentBeyondManifest=rs.nextSegmentBeyondManifest}else i[wr].push(ee)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var xy=_(Xe(),1);import{isNonNullable as Ey}from"@vkontakte/videoplayer-shared/es2015";var Re=(a,e)=>Ey(a)&&Ey(e)&&a.readyState==="open"&&(0,xy.default)([...a.activeSourceBuffers],e);var Ma=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new br(0);this.currentLowLatencySegmentLength$=new br(0);this.currentSegmentLength$=new br(0);this.onLastSegment$=new br(!1);this.fullyBuffered$=new br(!1);this.playingRepresentation$=new br(void 0);this.playingRepresentationInit$=new br(void 0);this.error$=new gD;this.gaps=[];this.subscription=new vD;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=fr(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new yS(this.sourceBuffer),this.subscription.add(Wl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ut.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ut.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Wl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ut.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Re(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ll(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=lt(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);je(r,"No init buffer for starting representation"),je(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=fr(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);je(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Le(s)||Le(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),je(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Re(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();$a(n)&&(this.isLive||(this.bufferLimit=1/0,yield new io(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=fr(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){var u,l;let t=(u=(0,En.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 p=this.representations.get(c);if(!p||!Se(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);je(i);let s=this.segments.get(r);je(s,"No segments for starting representation");let n=this.initData.get(r);if(je(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,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,fr(this.switchAbortController.signal,function(r,i=!1){return ae(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);je(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(Le(o)||Le(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),je(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Re(this.mediaSource,this.sourceBuffer))){if(yield 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();$a(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!Le(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return A(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new me,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Le(e)||Le(this.downloadingRepresentationId)||Le(this.playingRepresentationId)||Le(this.sourceBuffer)||!Re(this.mediaSource,this.sourceBuffer)||$a(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);$a(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=lt(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Ll(this.sourceBuffer.buffered)>=this.bufferLimit){let l=lt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,In.default)(o,i))l="high";else{let c=(0,oi.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&lt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,oi.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;$a(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,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,En.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,En.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Se(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>L(E({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,oi.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!Se(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=St(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}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&&na&&na(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&na&&na(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)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:p,to:h}},m)=>{let b=p<=r&&h>=r,g=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&Re(this.mediaSource,this.sourceBuffer)&&!(Ft(this.sourceBuffer.buffered,p)&&Ft(this.sourceBuffer.buffered,h)))&&g&&S});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 p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return A(this,null,function*(){Se(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return A(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 fr(o,function(){return ae(this,null,function*(){let c=Yl(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=Tn(),!c)return;let d=new DataView(c),p=Ra(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),La(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())Se(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return A(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 fr(n,function(){return ae(this,null,function*(){let u=Yl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Wl(window,"online").pipe(bD()).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=Tn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),La(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Se(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,oi.default)(e,0).byte.from,to:(0,oi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>A(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=Tn(),yield 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:Ut.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!Se(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=Tn();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:Ut.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,In.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return A(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=Ra(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 A(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){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,m=d<i,b=p<=i;if(!m)continue;let g=Ra(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(Le(this.sourceBuffer)||!Re(this.mediaSource,this.sourceBuffer))){!this.isLive&&fD.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ft(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ft(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ut.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Hl(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");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=Al(()=>(0,Py.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return A(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?fr(this.destroyAbortController.signal,function(){return ae(this,null,function*(){let o=Yl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ra(e.mime),i)).then(o=>A(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Se(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ut.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return A(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 A(this,null,function*(){if(!this.sourceBuffer||!Re(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Le(e))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:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(E({},u.time)),i=n(i);let l=Hl(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 p of this.segments.values())for(let h of p)(0,In.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(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(){return A(this,null,function*(){if(!this.sourceBuffer||!Re(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!Re(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!Re(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Le(e)?0:lt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Re(this.mediaSource,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||!this.sourceBuffer||!Re(this.mediaSource,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=Al(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ut.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Le(this.sourceBuffer)||!Re(this.mediaSource,this.sourceBuffer)||Le(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 Da=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var wy=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 Ca,assertNever as ky,fromEvent as Ry,merge as SD,now as Va,Subscription as yD,ValueSubject as zl,flattenObject as ui}from"@vkontakte/videoplayer-shared/es2015";var Ay=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var xn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new zl(void 0);this.lastConnectionReused$=new zl(void 0);this.lastRequestFirstBytes$=new zl(void 0);this.abortAllController=new me;this.subscription=new yD;this.fetchManifest=Ca(this.abortAllController.signal,function(e){return ae(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Da(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Ay(r));let i=yield Ze(r,{signal:this.abortAllController.signal}).catch(Oa);return i?(t.log("success",ui({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ui({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Ca(this.abortAllController.signal,function(l){return ae(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,U;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let N=new URL(c,location.href);N.searchParams.append("bytes",`${r.from}-${r.to}`),c=N.toString();break}default:ky(t)}this.requestQuic&&(c=Da(c));let h=this.abortAllController.signal,m;if(n){let N=new me;if(m=SD(Ry(this.abortAllController.signal,"abort"),Ry(n,"abort")).subscribe(()=>{try{N.abort()}catch(W){Oa(W)}}),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(W){Oa(W)}h=N.signal}let b=Va();p.log("startRequest",ui({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield Ze(c,{priority:s,headers:d,signal:h}).catch(Oa),v=Va();if(!g)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let N=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:N}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){m==null||m.unsubscribe();let N=Va(),W={requestStartedAt:b,requestEndedAt:N,duration:N-b};return p.log("endRequest",ui(W)),p.end(),g.arrayBuffer()}let[S,y]=g.body.tee(),I=S.getReader();o&&((U=this.throughputEstimator)==null||U.trackStream(y,u));let x=0,$=new Uint8Array(0),V=!1,X=N=>{m==null||m.unsubscribe(),V=!0,Oa(N)},M=Ca(h,function(k){return ae(this,arguments,function*({done:N,value:W}){if(x===0&&this.lastRequestFirstBytes$.next(Va()-b),h.aborted){m==null||m.unsubscribe();return}if(!N&&W){let T=new Uint8Array($.length+W.length);T.set($),T.set(W,$.length),$=T,x+=W.byteLength,i==null||i(new DataView($.buffer),x),yield I==null?void 0:I.read().then(M,X)}})}.bind(this));yield I==null?void 0:I.read().then(M,X),m==null||m.unsubscribe();let F=Va(),q={failed:V,requestStartedAt:b,requestEndedAt:F,duration:F-b};return V?(p.error("endRequest",ui(q)),p.end(),null):(p.log("endRequest",ui(q)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Ca(this.abortAllController.signal,function(e,t,r){return ae(this,null,function*(){var v;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 p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);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 S=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Ca(this.abortAllController.signal,function(e,t){return ae(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=>L(E({},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}=wy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return A(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:ky(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Oa=a=>{if(!La(a))throw a};var gr=(a,e,t)=>t*e+(1-t)*a,Kl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,Ly=(a,e,t,r)=>{let i=0,s=t,n=Kl(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 TD,ValueSubject as $y}from"@vkontakte/videoplayer-shared/es2015";var Ht=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 $y(e.initial),this.debounced$=new $y(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`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+=at(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)&&(TD(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 Pn=class extends Ht{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=gr(this.slow,e,this.params.emaAlphaSlow),this.fast=gr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var wn=class extends Ht{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Kl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=gr(this.emaSmoothed,e,this.params.emaAlpha);let r=Ly(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var An=class extends Ht{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?gr(this.smoothed,t,this.params.emaAlpha):t}};var vr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new Pn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new wn({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 An(E({initial:e,label:"liveEdgeDelay"},t))}};var Xl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as ID,ValueSubject as ED}from"@vkontakte/videoplayer-shared/es2015";var Ba=class a{constructor(e,t){this.currentRepresentation$=new ED(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(!ID(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(L(E({},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&&Se(t.segmentReference))}};var $D=["timeupdate","progress","play","seeked","stalled","waiting"],MD=["timeupdate","progress","loadeddata","playing","seeked"];var Rn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Vy;this.representationSubscription=new Vy;this.state$=new C("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new Cy;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.liveDuration$=new re(0);this.liveAvailabilityStartTime$=new re(void 0);this.bufferLength$=new re(0);this.liveLatency$=new re(void 0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.isLowLatency$=new re(!1);this.isActiveLowLatency$=new re(!1);this.currentStallDuration$=new re(0);this.videoLastDataObtainedTimestamp$=new re(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Cy;this.gapWatchdogActive=!1;this.destroyController=new me;this.initManifest=Jl(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=he(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:jt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Jl(this.destroyController.signal,function(){return ae(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:jt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Iy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=mS(e))!=null?n:{id:"ManifestParsing",category:jt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((m=(h=gt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),d=new Set(c.map(({codecs:h})=>h)),p=Gv(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);wD.isHDR&&h&&m?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=L(E({},t),{streams:i});return this.tracer.log("updateManifestEnd",Na(s)),s})}.bind(this));this.initRepresentations=Jl(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",Na({initialVideo:e,initialAudio:t,sourceHls:r})),Sr(this.manifest),Sr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(yr(p,"error").pipe(_a(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:jt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Rv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&cn())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,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new Ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Dy(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new Ma("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ba.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ba(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(Zl(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=Ks(this.manifestUrlString,2);this.manifestUrlString=he(this.manifestUrlString,m+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Tr(...MD.map(p=>yr(this.element,p))).pipe(Fa(p=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),kn(),RD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Tr(yr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(kn()).subscribe(h=>Xl(this.element,1))),this.representationSubscription.add(li({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(_a(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(li({isActiveLowLatency:this.isActiveLowLatency$.pipe(kn()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(_a(({isActiveLowLatency:h,currentLowLatencySegmentLength:m})=>h&&!!m)).subscribe(({currentLowLatencySegmentLength:h})=>{let m=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(li({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(_a(({isLive:h})=>h),Fa(h=>E({},h)),kn((h,m)=>m.bufferLength<h.bufferLength),Fa(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let g=Ks(this.manifestUrlString,2);return(h/2+m+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(li({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:m})=>{if(!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=h-b,y=1;Math.abs(S)>g&&(y=1+Math.sign(S)*v),Xl(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let m=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var I,x;return(x=(I=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?x:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(li({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(LD(1e3)).subscribe(b=>A(this,[b],function*({liveLoadBufferLength:h,bufferLength:m}){if(Sr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=Ks(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,x=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=isFinite(h)?h:m,V=this.isActiveLowLatency$.getValue(),X=S<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(V&&X);let M="none";if(V?M="active_low_latency":this.isLowLatency$.getValue()&&X?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),M="active_low_latency"):v!==0&&$<y?M="live_forward_buffering":$<y+x&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let F=p-(y+I),q=this.normolizeLiveOffset(Math.trunc(v+F/g)),R=Math.abs(q-v),U;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?U=v:q>0&&R>this.tuning.dashCmafLive.offsetCalculationError?U=q:U=0,this.manifestUrlString=he(this.manifestUrlString,U,2)}M!=="none"&&M!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=Tr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Fa(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Tr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Fa(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(Tr(this.forceEnded$,li({allBuffersFull:l,someBufferEnded:c}).pipe(_a(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:jt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Tr(...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 h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,ec.default)((0,ec.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),Se(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Dy(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=Zl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:jt.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 xn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=vr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return A(this,null,function*(){var r,i,s;Sr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=he(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(){Sr(this.element),this.state$.setState("running"),this.subscription.add(Tr(...$D.map(e=>yr(this.element,e)),yr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:jt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(yr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(yr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ft(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,b,g,v,S,y,I,x,$;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=kD(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,c=(I=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&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 V=this.element.currentTime*1e3;(x=this.videoBufferManager)==null||x.maintain(V),($=this.audioBufferManager)==null||$.maintain(V),i.position=V}this.tracer.log("stallIntervalCallback",Na(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Zl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:jt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return A(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){return A(this,null,function*(){var i,s,n,o,u;Sr(this.element),Sr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),Ft(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",Na({requestedPosition:e,forcePrecise:t,position:r}))})}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),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=AD(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return A(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=L(E({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Na(t)))}}};var Ln=class{constructor(e,t){this.fov=e,this.orientation=t}};var $n=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/at(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=E({},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*at(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 Oy=`attribute vec2 a_vertex;
70
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Bl=B(ti(),1);import{videoSizeToQuality as lD}from"@vkontakte/videoplayer-shared/es2015";var ly=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?_t(s):void 0)!=null?u:lD({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},cy=({id:a,bitrate:e})=>({id:a,bitrate:e}),dy=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),py=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),_l=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Bl.default)(r.split("."),0),isDefault:i}),Nl=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Bl.default)(i.split("."),0)}),Fl=a=>"url"in a,Se=a=>a.type==="template",$a=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var fy=a=>{if(!(a!=null&&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},St=(a,e)=>{let t=a;t=(0,ql.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,my.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,ql.default)(t,n,(o,u)=>hy(s)?o:hy(u)?s:(0,by.default)(s,parseInt(u,10),"0"))}return t},vy=(a,e)=>{var E,L,O,J,M,N,F,R,q,_,Y,k,T,D,Q,H,Be,It,xr,j,ce,de,_e,Et,Pr,xt,Kt,wr,fi,Sc,yc,Tc,Ic,Ec,xc,Pc,wc,Ac,kc,Rc,$c,Lc,Mc,Dc,Cc,Oc,Vc,Bc,_c,Nc,Fc,qc,Uc,Hc,jc,Gc,Qc,Wc,Yc,zc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Ge=>{var X,Xt;return(Xt=(X=Ge.textContent)==null?void 0:X.trim())!=null?Xt:""}),o=(E=(0,gy.default)(n,0))!=null?E:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],f=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((Ge,X)=>$(I({},Ge),{[X.id]:X.children}),{}),v=b.reduce((Ge,X)=>$(I({},Ge),{[X.id]:X.getAttribute("duration")}),{});p?d=fy(p):(0,Ul.default)(v).filter(Ge=>Ge).length&&!u?d=(0,Ul.default)(v).reduce((Ge,X)=>{var Xt;return Ge+((Xt=fy(X))!=null?Xt:0)},0):f&&(d=parseInt(f,10));let S=0,y=(O=(L=s.getAttribute("profiles"))==null?void 0:L.split(","))!=null?O:[];for(let Ge of b.map(X=>X.id))for(let X of g[Ge]){let Xt=(J=X.getAttribute("id"))!=null?J:"id"+(S++).toString(10),mi=(M=X.getAttribute("mimeType"))!=null?M:"",Yn=(N=X.getAttribute("codecs"))!=null?N:"",zn=(F=X.getAttribute("contentType"))!=null?F:mi==null?void 0:mi.split("/")[0],BT=(q=(R=X.getAttribute("profiles"))==null?void 0:R.split(","))!=null?q:[],Kc=(Y=uy((_=X.getAttribute("lang"))!=null?_:""))!=null?Y:{},_T=(D=(T=(k=X.querySelector("Label"))==null?void 0:k.textContent)==null?void 0:T.trim())!=null?D:void 0,NT=X.querySelectorAll("Representation"),FT=X.querySelector("SegmentTemplate"),qT=(H=(Q=X.querySelector("Role"))==null?void 0:Q.getAttribute("value"))!=null?H:void 0,Ar=zn,te={id:Xt,language:Kc.language,isDefault:qT==="main",label:_T,codecs:Yn,hdr:Ar==="video"&&Ol(Yn),mime:mi,representations:[]};for(let z of NT){let Pt=(Be=z.getAttribute("lang"))!=null?Be:void 0,bi=(It=z.getAttribute("label"))!=null?It:void 0,ts=(ce=(j=(xr=z.querySelector("BaseURL"))==null?void 0:xr.textContent)==null?void 0:j.trim())!=null?ce:"",Jt=new URL(ts||o,e).toString(),wt=(de=z.getAttribute("mimeType"))!=null?de:mi,rs=(Et=(_e=z.getAttribute("codecs"))!=null?_e:Yn)!=null?Et:"",is;if(zn==="text"){let At=z.getAttribute("id")||"",as=((Pr=Kc.privateuse)==null?void 0:Pr.includes("x-auto"))||At.includes("_auto"),Zt=z.querySelector("SegmentTemplate");if(Zt){let gi={representationId:(xt=z.getAttribute("id"))!=null?xt:void 0,bandwidth:(Kt=z.getAttribute("bandwidth"))!=null?Kt:void 0},ss=parseInt((wr=z.getAttribute("bandwidth"))!=null?wr:"",10)/1e3,ns=(Sc=parseInt((fi=Zt.getAttribute("startNumber"))!=null?fi:"",10))!=null?Sc:1,kr=parseInt((yc=Zt.getAttribute("timescale"))!=null?yc:"",10),Kn=(Tc=Zt.querySelectorAll("SegmentTimeline S"))!=null?Tc:[],Rr=Zt.getAttribute("media");if(!Rr)continue;let os=[],us=0,ls="",$r=0,vi=ns,ge=0;for(let Qe of Kn){let er=parseInt((Ic=Qe.getAttribute("d"))!=null?Ic:"",10),Ne=parseInt((Ec=Qe.getAttribute("r"))!=null?Ec:"",10)||0,kt=parseInt((xc=Qe.getAttribute("t"))!=null?xc:"",10);ge=Number.isFinite(kt)?kt:ge;let tr=er/kr*1e3,Rt=ge/kr*1e3;for(let rt=0;rt<Ne+1;rt++){let $t=St(Rr,$(I({},gi),{segmentNumber:vi.toString(10),segmentTime:(ge+rt*er).toString(10)})),Lr=(Rt!=null?Rt:0)+rt*tr,yi=Lr+tr;vi++,os.push({time:{from:Lr,to:yi},url:$t})}ge+=(Ne+1)*er,us+=(Ne+1)*tr}$r=ge/kr*1e3,ls=St(Rr,$(I({},gi),{segmentNumber:vi.toString(10),segmentTime:ge.toString(10)}));let Si={time:{from:$r,to:1/0},url:ls},dt={type:"template",baseUrl:Jt,segmentTemplateUrl:Rr,initUrl:"",totalSegmentsDurationMs:us,segments:os,nextSegmentBeyondManifest:Si,timescale:kr};is={id:At,kind:"text",segmentReference:dt,profiles:[],duration:d,bitrate:ss,mime:"",codecs:"",width:0,height:0,isAuto:as}}else is={id:At,isAuto:as,kind:"text",url:Jt}}else{let At=(wc=(Pc=z.getAttribute("contentType"))!=null?Pc:wt==null?void 0:wt.split("/")[0])!=null?wc:zn,as=(kc=(Ac=X.getAttribute("profiles"))==null?void 0:Ac.split(","))!=null?kc:[],Zt=parseInt((Rc=z.getAttribute("width"))!=null?Rc:"",10),gi=parseInt(($c=z.getAttribute("height"))!=null?$c:"",10),ss=parseInt((Lc=z.getAttribute("bandwidth"))!=null?Lc:"",10)/1e3,ns=(Mc=z.getAttribute("frameRate"))!=null?Mc:"",kr=(Dc=z.getAttribute("quality"))!=null?Dc:void 0,Kn=ns?oy(ns):void 0,Rr=(Cc=z.getAttribute("id"))!=null?Cc:"id"+(S++).toString(10),os=At==="video"?`${gi}p`:At==="audio"?`${ss}Kbps`:rs,us=`${Rr}@${os}`,ls=[...y,...BT,...as],$r,vi=z.querySelector("SegmentBase"),ge=(Oc=z.querySelector("SegmentTemplate"))!=null?Oc:FT;if(vi){let dt=(Bc=(Vc=z.querySelector("SegmentBase Initialization"))==null?void 0:Vc.getAttribute("range"))!=null?Bc:"",[Qe,er]=dt.split("-").map($t=>parseInt($t,10)),Ne={from:Qe,to:er},kt=(_c=z.querySelector("SegmentBase"))==null?void 0:_c.getAttribute("indexRange"),[tr,Rt]=kt?kt.split("-").map($t=>parseInt($t,10)):[],rt=kt?{from:tr,to:Rt}:void 0;$r={type:"byteRange",url:Jt,initRange:Ne,indexRange:rt}}else if(ge){let dt={representationId:(Nc=z.getAttribute("id"))!=null?Nc:void 0,bandwidth:(Fc=z.getAttribute("bandwidth"))!=null?Fc:void 0},Qe=parseInt((qc=ge.getAttribute("timescale"))!=null?qc:"",10),er=(Uc=ge.getAttribute("initialization"))!=null?Uc:"",Ne=ge.getAttribute("media"),kt=(jc=parseInt((Hc=ge.getAttribute("startNumber"))!=null?Hc:"",10))!=null?jc:1,tr=St(er,dt);if(!Ne)throw new ReferenceError("No media attribute in SegmentTemplate");let Rt=(Gc=ge.querySelectorAll("SegmentTimeline S"))!=null?Gc:[],rt=[],$t=0,Lr="",yi=0;if(Rt.length){let cs=kt,We=0;for(let Mr of Rt){let it=parseInt((Qc=Mr.getAttribute("d"))!=null?Qc:"",10),rr=parseInt((Wc=Mr.getAttribute("r"))!=null?Wc:"",10)||0,ds=parseInt((Yc=Mr.getAttribute("t"))!=null?Yc:"",10);We=Number.isFinite(ds)?ds:We;let Xn=it/Qe*1e3,Jn=We/Qe*1e3;for(let ps=0;ps<rr+1;ps++){let HT=St(Ne,$(I({},dt),{segmentNumber:cs.toString(10),segmentTime:(We+ps*it).toString(10)})),Xc=(Jn!=null?Jn:0)+ps*Xn,jT=Xc+Xn;cs++,rt.push({time:{from:Xc,to:jT},url:HT})}We+=(rr+1)*it,$t+=(rr+1)*Xn}yi=We/Qe*1e3,Lr=St(Ne,$(I({},dt),{segmentNumber:cs.toString(10),segmentTime:We.toString(10)}))}else if(cD(d)){let We=parseInt((zc=ge.getAttribute("duration"))!=null?zc:"",10)/Qe*1e3,Mr=Math.ceil(d/We),it=0;for(let rr=1;rr<Mr;rr++){let ds=St(Ne,$(I({},dt),{segmentNumber:rr.toString(10),segmentTime:it.toString(10)}));rt.push({time:{from:it,to:it+We},url:ds}),it+=We}yi=it,Lr=St(Ne,$(I({},dt),{segmentNumber:Mr.toString(10),segmentTime:it.toString(10)}))}let UT={time:{from:yi,to:1/0},url:Lr};$r={type:"template",baseUrl:Jt,segmentTemplateUrl:Ne,initUrl:tr,totalSegmentsDurationMs:$t,segments:rt,nextSegmentBeyondManifest:UT,timescale:Qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!At||!wt)continue;let Si={video:"video",audio:"audio",text:"text"}[At];if(!Si)continue;Ar||(Ar=Si),is={id:us,kind:Si,segmentReference:$r,profiles:ls,duration:d,bitrate:ss,mime:wt,codecs:rs,width:Zt,height:gi,fps:Kn,quality:kr}}te.language||(te.language=Pt),te.label||(te.label=bi),te.mime||(te.mime=wt),te.codecs||(te.codecs=rs),te.hdr||(te.hdr=Ar==="video"&&Ol(rs)),te.representations.push(is)}if(Ar){let z=i[Ar].find(Pt=>Pt.id===te.id);if(z&&te.representations.every(Pt=>Se(Pt.segmentReference)))for(let Pt of z.representations){let bi=te.representations.find(wt=>wt.id===Pt.id),ts=bi==null?void 0:bi.segmentReference,Jt=Pt.segmentReference;Jt.segments.push(...ts.segments),Jt.nextSegmentBeyondManifest=ts.nextSegmentBeyondManifest}else i[Ar].push(te)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var yy=B(Xe(),1);import{isNonNullable as Sy}from"@vkontakte/videoplayer-shared/es2015";var ye=(a,e)=>Sy(a)&&Sy(e)&&a.readyState==="open"&&(0,yy.default)([...a.activeSourceBuffers],e);var La=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new gr(0);this.currentLowLatencySegmentLength$=new gr(0);this.currentSegmentLength$=new gr(0);this.onLastSegment$=new gr(!1);this.fullyBuffered$=new gr(!1);this.playingRepresentation$=new gr(void 0);this.playingRepresentationInit$=new gr(void 0);this.error$=new hD;this.gaps=[];this.subscription=new fD;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=Ht(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){let t=this.representations.get(e);$e(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new bS(this.sourceBuffer),this.subscription.add(jl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:jt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:jt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(jl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:jt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ye(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Al(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=lt(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);$e(r,"No init buffer for starting representation"),$e(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.switchTo=Ht(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);$e(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(be(s)||be(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),$e(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer();else{let n=this.getCurrentPosition();ui(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new fs(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=Ht(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);$e(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(be(s)||be(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),$e(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();ui(n)&&(this.isLive||(this.bufferLimit=1/0,yield new fs(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=Ht(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){var u,l;let t=(u=(0,In.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 p=this.representations.get(c);if(!p||!Se(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);$e(i);let s=this.segments.get(r);$e(s,"No segments for starting representation");let n=this.initData.get(r);if($e(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,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}switchToWithPreviousAbort(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new me,Ht(this.switchAbortController.signal,function(r,i=!1){return ae(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);$e(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(be(o)||be(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),$e(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();ui(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!be(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return w(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new me,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(be(e)||be(this.downloadingRepresentationId)||be(this.playingRepresentationId)||be(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer)||ui(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if($e(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);ui(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=lt(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&Al(this.sourceBuffer.buffered)>=this.bufferLimit){let l=lt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,Tn.default)(o,i))l="high";else{let c=(0,li.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&lt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,li.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;ui(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,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,In.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,In.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!Se(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>$(I({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,li.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;$e(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!Se(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=St(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}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&&na&&na(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&na&&na(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)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:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&ye(this.mediaSource,this.sourceBuffer)&&!(qt(this.sourceBuffer.buffered,p)&&qt(this.sourceBuffer.buffered,h)))&&g&&S});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 p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return w(this,null,function*(){Se(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return w(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 Ht(o,function(){return ae(this,null,function*(){let c=Gl(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=yn(),!c)return;let d=new DataView(c),p=Ra(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),$a(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())Se(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return w(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 Ht(n,function(){return ae(this,null,function*(){let u=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),jl(window,"online").pipe(pD()).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=yn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),$a(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(Se(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,li.default)(e,0).byte.from,to:(0,li.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>w(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=yn(),yield 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:jt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!Se(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=yn();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:jt.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,Tn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return w(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=Ra(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 w(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){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(!f)continue;let g=Ra(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(be(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer))){!this.isLive&&dD.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qt(this.sourceBuffer.buffered,e.segment.time.from,100)&&qt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:jt.VIDEO_PIPELINE,message:"Browser stuck on empty result of adding segment to source buffer"})),this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status="fed",Fl(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");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=xl(()=>(0,Ty.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return w(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?Ht(this.destroyAbortController.signal,function(){return ae(this,null,function*(){let o=Gl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,Ra(e.mime),i)).then(o=>w(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&Se(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:jt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return w(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 w(this,null,function*(){if(!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||be(e))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:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(I({},u.time)),i=n(i);let l=Fl(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 p of this.segments.values())for(let h of p)(0,Tn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(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(){return w(this,null,function*(){if(!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))return!1;let e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;return this.sourceBufferTaskQueue.abort(t)})}getDebugBufferState(){if(!(!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||be(e)?0:lt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)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)));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||!this.sourceBuffer||!ye(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)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=xl(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:jt.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(be(this.sourceBuffer)||!ye(this.mediaSource,this.sourceBuffer)||be(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 Ma=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Iy=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 Da,assertNever as xy,fromEvent as Py,merge as mD,now as Ca,Subscription as bD,ValueSubject as Ql,flattenObject as ci}from"@vkontakte/videoplayer-shared/es2015";var Ey=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var En=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 bD;this.fetchManifest=Da(this.abortAllController.signal,function(e){return ae(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ma(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Ey(r));let i=yield Ze(r,{signal:this.abortAllController.signal}).catch(Oa);return i?(t.log("success",ci({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ci({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Da(this.abortAllController.signal,function(l){return ae(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,q;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let _=new URL(c,location.href);_.searchParams.append("bytes",`${r.from}-${r.to}`),c=_.toString();break}default:xy(t)}this.requestQuic&&(c=Ma(c));let h=this.abortAllController.signal,f;if(n){let _=new me;if(f=mD(Py(this.abortAllController.signal,"abort"),Py(n,"abort")).subscribe(()=>{try{_.abort()}catch(Y){Oa(Y)}}),this.abortAllController.signal.aborted||n.aborted)try{_.abort()}catch(Y){Oa(Y)}h=_.signal}let b=Ca();p.log("startRequest",ci({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield Ze(c,{priority:s,headers:d,signal:h}).catch(Oa),v=Ca();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(v-b),!g.ok||!g.body){f==null||f.unsubscribe();let _=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:_}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let _=Ca(),Y={requestStartedAt:b,requestEndedAt:_,duration:_-b};return p.log("endRequest",ci(Y)),p.end(),g.arrayBuffer()}let[S,y]=g.body.tee(),x=S.getReader();o&&((q=this.throughputEstimator)==null||q.trackStream(y,u));let E=0,L=new Uint8Array(0),O=!1,J=_=>{f==null||f.unsubscribe(),O=!0,Oa(_)},M=Da(h,function(k){return ae(this,arguments,function*({done:_,value:Y}){if(E===0&&this.lastRequestFirstBytes$.next(Ca()-b),h.aborted){f==null||f.unsubscribe();return}if(!_&&Y){let T=new Uint8Array(L.length+Y.length);T.set(L),T.set(Y,L.length),L=T,E+=Y.byteLength,i==null||i(new DataView(L.buffer),E),yield x==null?void 0:x.read().then(M,J)}})}.bind(this));yield x==null?void 0:x.read().then(M,J),f==null||f.unsubscribe();let N=Ca(),F={failed:O,requestStartedAt:b,requestEndedAt:N,duration:N-b};return O?(p.error("endRequest",ci(F)),p.end(),null):(p.log("endRequest",ci(F)),p.end(),L.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Da(this.abortAllController.signal,function(e,t,r){return ae(this,null,function*(){var v;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 p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let S=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Da(this.abortAllController.signal,function(e,t){return ae(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=>$(I({},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}=Iy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return w(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:xy(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Oa=a=>{if(!$a(a))throw a};var vr=(a,e,t)=>t*e+(1-t)*a,Wl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,wy=(a,e,t,r)=>{let i=0,s=t,n=Wl(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 gD,ValueSubject as Ay}from"@vkontakte/videoplayer-shared/es2015";var Gt=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 Ay(e.initial),this.debounced$=new Ay(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ve(`raw_${t}`),this.smoothedSeries$=new ve(`smoothed_${t}`),this.reportedSeries$=new ve(`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+=at(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)&&(gD(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 xn=class extends Gt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=vr(this.slow,e,this.params.emaAlphaSlow),this.fast=vr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var Pn=class extends Gt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Wl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=vr(this.emaSmoothed,e,this.params.emaAlpha);let r=wy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var wn=class extends Gt{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?vr(this.smoothed,t,this.params.emaAlpha):t}};var Sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new xn({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Pn({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 wn(I({initial:e,label:"liveEdgeDelay"},t))}};var Yl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as vD,ValueSubject as SD}from"@vkontakte/videoplayer-shared/es2015";var Va=class a{constructor(e,t){this.currentRepresentation$=new SD(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(!vD(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($(I({},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&&Se(t.segmentReference))}};var AD=["timeupdate","progress","play","seeked","stalled","waiting"],kD=["timeupdate","progress","loadeddata","playing","seeked"];var kn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Ly;this.representationSubscription=new Ly;this.state$=new C("none");this.currentVideoRepresentation$=new ie(void 0);this.currentVideoRepresentationInit$=new ie(void 0);this.currentAudioRepresentation$=new ie(void 0);this.currentVideoSegmentLength$=new ie(0);this.currentAudioSegmentLength$=new ie(0);this.error$=new $y;this.lastConnectionType$=new ie(void 0);this.lastConnectionReused$=new ie(void 0);this.lastRequestFirstBytes$=new ie(void 0);this.currentLiveTextRepresentation$=new ie(null);this.isLive$=new ie(!1);this.liveDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(void 0);this.bufferLength$=new ie(0);this.liveLatency$=new ie(void 0);this.liveLoadBufferLength$=new ie(0);this.livePositionFromPlayer$=new ie(0);this.isLowLatency$=new ie(!1);this.isActiveLowLatency$=new ie(!1);this.currentStallDuration$=new ie(0);this.videoLastDataObtainedTimestamp$=new ie(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new $y;this.gapWatchdogActive=!1;this.destroyController=new me;this.initManifest=zl(this.destroyController.signal,function(e,t,r){return ae(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:Qt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=zl(this.destroyController.signal,function(){return ae(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=vy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=cS(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,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((f=(h=gt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(c.map(({codecs:h})=>h)),p=Uv(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);ID.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=$(I({},t),{streams:i});return this.tracer.log("updateManifestEnd",_a(s)),s})}.bind(this));this.initRepresentations=zl(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",_a({initialVideo:e,initialAudio:t,sourceHls:r})),yr(this.manifest),yr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Tr(p,"error").pipe(Ba(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Qt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Pv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&ln())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,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new La("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Ry(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new La("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Va.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Va(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(Kl(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=Ks(this.manifestUrlString,2);this.manifestUrlString=fe(this.manifestUrlString,f+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ir(...kD.map(p=>Tr(this.element,p))).pipe(Na(p=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),An(),PD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ir(Tr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(An()).subscribe(h=>{this.isManualDecreasePlaybackInLive()||Yl(this.element,1)})),this.representationSubscription.add(di({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Ba(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(di({isActiveLowLatency:this.isActiveLowLatency$.pipe(An()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(Ba(({isActiveLowLatency:h,currentLowLatencySegmentLength:f})=>h&&!!f)).subscribe(({currentLowLatencySegmentLength:h})=>{let f=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(f,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(di({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ba(({isLive:h})=>h),Na(h=>I({},h)),An((h,f)=>f.bufferLength<h.bufferLength),Na(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=Ks(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(di({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=h-b;if(this.isManualDecreasePlaybackInLive())return;let y=1;Math.abs(S)>g&&(y=1+Math.sign(S)*v),Yl(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(y=>{var x,E;return(E=(x=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:x.to)!=null?E:v}))-v}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(di({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(wD(1e3)).subscribe(b=>w(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(yr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,v=Ks(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,L=isFinite(h)?h:f,O=this.isActiveLowLatency$.getValue(),J=S<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(O&&J);let M="none";if(O?M="active_low_latency":this.isLowLatency$.getValue()&&J?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(N=>N.proceedLowLatencyLive()),M="active_low_latency"):v!==0&&L<y?M="live_forward_buffering":L<y+E&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let N=p-(y+x),F=this.normolizeLiveOffset(Math.trunc(v+N/g)),R=Math.abs(F-v),q;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?q=v:F>0&&R>this.tuning.dashCmafLive.offsetCalculationError?q=F:q=0,this.manifestUrlString=fe(this.manifestUrlString,q,2)}M!=="none"&&M!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=Ir(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Na(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Ir(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Na(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(Ir(this.forceEnded$,di({allBuffersFull:l,someBufferEnded:c}).pipe(Ba(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:Qt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Ir(...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 h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,Xl.default)((0,Xl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),Se(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Ry(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=Kl(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 En({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=Sr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,I({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return w(this,null,function*(){var r,i,s;yr(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(){yr(this.element),this.state$.setState("running"),this.subscription.add(Ir(...AD.map(e=>Tr(this.element,e)),Tr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Qt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Tr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Tr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&qt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,g,v,S,y,x,E,L;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=xD(),n=100,o=(f=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,c=(x=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?x:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&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 O=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(O),(L=this.audioBufferManager)==null||L.maintain(O),i.position=O}this.tracer.log("stallIntervalCallback",_a(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Kl(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 w(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?i==null?void 0:i.switchToWithPreviousAbort(t,r):i==null?void 0:i.switchTo(t,r):i==null?void 0:i.switchToOld(t,r)})}seek(e,t){return w(this,null,function*(){var i,s,n,o,u;yr(this.element),yr(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),qt(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0: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=>{URL.revokeObjectURL(i.src),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=ED(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}isManualDecreasePlaybackInLive(){return!this.element||!this.isLive$.getValue()?!1:1-this.element.playbackRate>this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return w(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=$(I({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",_a(t)))}}};var Rn=class{constructor(e,t){this.fov=e,this.orientation=t}};var $n=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/at(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=I({},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*at(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 My=`attribute vec2 a_vertex;
71
71
  attribute vec2 a_texel;
72
72
 
73
73
  varying vec2 v_texel;
@@ -78,7 +78,7 @@ void main(void) {
78
78
  // save texel vector to pass to fragment shader
79
79
  v_texel = a_texel;
80
80
  }
81
- `;var By=`#ifdef GL_ES
81
+ `;var Dy=`#ifdef GL_ES
82
82
  precision highp float;
83
83
  precision highp int;
84
84
  #else
@@ -121,6 +121,6 @@ void main(void) {
121
121
  // sample using new coordinates
122
122
  gl_FragColor = texture2D(u_texture, tc);
123
123
  }
124
- `;var Mn=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 Ln(this.params.fov,this.params.orientation),this.cameraRotationManager=new $n(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(Oy,this.gl.VERTEX_SHADER),r=this.createShader(By,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,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as VD,now as _y,Subscription as OD,filter as BD,combine as Ny,ValueSubject as tc,isNonNullable as _D}from"@vkontakte/videoplayer-shared/es2015";var rc=class{constructor(){this.isSeeked$=new tc(!1);this.isBuffering$=new tc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new OD;this.severeStallOccurred$=new tc(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(Ny({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(BD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Ny({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(VD(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=_y(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,_D(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=_y(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Fy=rc;import{combine as ND,map as FD,observeElementSize as qD,Subscription as UD,ValueSubject as ic,noop as HD}from"@vkontakte/videoplayer-shared/es2015";var Dn=class{constructor(){this.subscription=new UD;this.pipSize$=new ic(void 0);this.videoSize$=new ic(void 0);this.elementSize$=new ic(void 0);this.pictureInPictureWindowRemoveEventListener=HD}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(qD(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(ND({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(FD(({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 Ir=class{constructor(e){this.subscription=new KD;this.videoState=new C("stopped");this.droppedFramesManager=new nn;this.stallsManager=new Fy;this.elementSizeManager=new Dn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Yi;this.audioTrackSwitchHistory=new Yi;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.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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&P(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"&&P(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"&&P(this.params.desiredState.playbackState,"paused");return;default:return GD(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Mn(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.textTracksManager=new Fe(e.source.url),this.params=e,this.video=Ie(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 Rn({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=Pe(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:ac.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(qy(c=>!!c.length),Hy()).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(sc(c=>c.to.state!=="none"),Ua());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Ua()),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(qy(Uy),Hy()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(sc(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(xe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ne(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ue(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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(WD(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of d.audio){h.push(ql(m));let b=[];for(let g of m.representations){let v=my(g);b.push(v),this.audioTracksMap.set(v,{stream:m,representation:g})}this.audioStreamsMap.set(m,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Ul(h));let m=[];for(let b of h.representations){let g=hy(L(E({},b),{streamId:h.id}));g&&(m.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let m of h.representations){let b=fy(h,m);this.textTracksMap.set(b,{stream:h,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:ac.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Cn(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$,zD(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,jy.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,b=[...this.videoTracksMap.keys()].find(v=>{var S;return((S=this.videoTracksMap.get(v))==null?void 0:S.representation.id)===h.id});Uy(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),m){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,v).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(Ua()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Ul(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Ua()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(ql(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.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(sc(({to:c})=>c==="ready"),Ua());this.subscription.add(Cn(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,nc(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Cn(u,this.player.state$.stateChangeEnded$,nc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Cn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,nc(["init"])).pipe(YD(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var $,V,X,M,F,q,R,U,N,W,k,T,B;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:D})=>D===i),o=t.currentVideoTrack$.getValue(),u=((M=(X=e.videoStream.getState())!=null?X:n&&((V=this.videoTracksMap.get(n))==null?void 0:V.stream))!=null?M:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:D})=>D===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=lt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(F=e.audioStream.getState())!=null?F:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(q=[...this.audioStreamsMap.keys()].find(({id:D})=>D===(m==null?void 0:m.id)))!=null?q:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let D=tn(n,c,(R=this.audioStreamsMap.get(b))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(U=D==null?void 0:D.bitrate)!=null?U:-1/0)}if(o){let D=tn(o,c,(N=this.audioStreamsMap.get(b))!=null?N:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(W=D==null?void 0:D.bitrate)!=null?W:-1/0)}}let v=Nt(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),S=r?v!=null?v:n:n!=null?n:v,y=b&&Qg(S,c,(k=this.audioStreamsMap.get(b))!=null?k:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=(T=this.videoTracksMap.get(S))==null?void 0:T.representation,x=y&&((B=this.audioTracksMap.get(y))==null?void 0:B.representation);if(I&&x)return[I,x];if(I&&!x&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ac.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),Ee(this.video),this.tracer.end()}};var Ha=class extends Ir{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 Qy,interval as XD,map as Gy}from"@vkontakte/videoplayer-shared/es2015";var ja=class extends Ir{constructor(e){super(e),this.liveOffset=new ft,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(Gy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Qy({interval:XD(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(Qy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Gy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=by(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 Yy=_(zs(),1);import{assertNever as Qa,assertNonNullable as Wy,debounce as JD,ErrorCategory as Vn,filter as ZD,isNonNullable as eC,isNullable as tC,map as On,merge as rC,Observable as iC,observableFrom as aC,Subscription as sC,videoSizeToQuality as nC}from"@vkontakte/videoplayer-shared/es2015";var tt={};var ci=(a,e)=>new iC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ga=class{constructor(e){this.subscription=new sC;this.videoState=new C("initializing");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:Qa(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Qa(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Qa(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Qa(e)}break;default:Qa(t)}};this.textTracksManager=new Fe(e.source.url),this.video=Ie(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),Ee(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Vn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Yy.default)(import("hls.js").then(i=>{e||(tt.Hls=i.default,tt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Wy(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Wy(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Vn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Pe(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(ot(this.video,e.isLooped,r)),this.subscription.add(xe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ne(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ue(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(On(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ci(this.hls,tt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Vn.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"),P(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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(ci(this.hls,tt.Events.MANIFEST_PARSED).pipe(On(({levels:l})=>l.reduce((c,d)=>{var S,y;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(y=Bt((S=d.attrs.QUALITY)!=null?S:""))!=null?y:nC({width:h,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(ci(this.hls,tt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ci(this.hls,tt.Events.LEVEL_LOADING).pipe(On(({url:l})=>oe(l))),t.hostname$),s(ci(this.hls,tt.Events.FRAG_CHANGED),l=>{var p,h,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Ct(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=ci(this.hls,tt.Events.LEVEL_SWITCHED).pipe(On(({level:l})=>n(this.hls.levels[l])));o.pipe(ZD(eC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ct(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(tC(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),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=rC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,aC(["init"])).pipe(JD(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 A(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vn.DOM,thrown:t})))||(this.videoState.setState("paused"),P(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"),P(this.params.desiredState.playbackState,"stopped",!0)}};var zy="X-Playback-Duration",oc=a=>A(void 0,null,function*(){var i;let e=yield Ze(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(zy)?parseInt(e.headers.get(zy),10):void 0});import{assertNever as gC,combine as vC,debounce as SC,ErrorCategory as Nn,filter as yC,filterChanged as TC,isNonNullable as Jy,isNullable as Fn,map as Zy,merge as IC,observableFrom as EC,Subscription as xC,ValueSubject as cc,VideoQuality as PC}from"@vkontakte/videoplayer-shared/es2015";var lc=_(pu(),1);import{videoSizeToQuality as oC,getExponentialDelay as uC}from"@vkontakte/videoplayer-shared/es2015";var lC=a=>{let e=null;if(a.QUALITY&&(e=Bt(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=oC({width:t,height:r})}return e!=null?e:null},cC=(a,e)=>{var s,n;let t=a.split(`
125
- `),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,lc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=lC(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[S,y]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,lc.default)(c[1].split(",").map(b=>{let g=b.indexOf("=");return[b.substring(0,g),b.substring(g+1)]}).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&i.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},dC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),uc=0,Ky=(i,...s)=>A(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield Ze(a,r)).text();uc+=1;try{let{qualityManifests:u,textTracks:l}=cC(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(uc<=t.manifestRetryMaxCount)return yield dC(uC(uc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ky(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Bn=Ky;import{isNonNullable as pC,Subscription as hC,throttle as mC,ValueSubject as Xy,Subject as fC,ErrorCategory as bC}from"@vkontakte/videoplayer-shared/es2015";var _n=class{constructor(e,t,r,i,s){this.subscription=new hC;this.abortControllers={destroy:new me,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Xy(null);this.getCurrentTime$=new Xy(null);this.error$=new fC;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(mC(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return A(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=yield this.fetchManifestData();yield this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return A(this,null,function*(){try{let r=yield this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}})}parseTextTracks(e,t){return A(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield Ze(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}})}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
126
- `),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(pC(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([L(E({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return A(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new me;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return A(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:bC.WTF,thrown:t,message:e})}};var Wa=class{constructor(e){this.subscription=new xC;this.videoState=new C("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new cc([]);this.liveOffset=new ft;this.manifestStartTime$=new cc(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"),P(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&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(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"&&P(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"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return gC(t)}};var r;this.params=e,this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:PC.INVARIANT,url:this.params.source.url};let t=(i,s)=>Bn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new _n(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Fe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Nn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Nn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new cc((r=e.source.maxSeekBackTime)!=null?r: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(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Nn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Pe(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(xe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ne(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ue(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(TC(),Zy(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&&Jy(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(oe(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(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(vC({startTime:this.manifestStartTime$.pipe(yC(Jy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Zy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=IC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,EC(["init"])).pipe(SC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Ee(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Fn(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:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=he(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),oc(n).then(c=>{var d;if(!Fn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Fn(p)||!isFinite(p))&&Ze(n).then(h=>h.text()).then(h=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();oc(g).then(v=>{Fn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Nn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=he(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as wC,debounce as AC,ErrorCategory as dc,fromEvent as pc,isNonNullable as kC,isNullable as RC,map as eT,merge as tT,observableFrom as rT,Subscription as LC,ValueSubject as $C,VideoQuality as MC,clientChecker as DC}from"@vkontakte/videoplayer-shared/es2015";var Ya=class{constructor(e){this.subscription=new LC;this.videoState=new C("stopped");this.manifests$=new $C([]);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"),P(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"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return wC(t)}};this.textTracksManager=new Fe(e.source.url),this.params=e,this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:MC.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),Bn(he(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:dc.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(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:dc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Pe(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(eT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(xe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ne(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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 h;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&&kC(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(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){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(eT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!DC.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(tT(pc(o,"addtrack"),pc(o,"removetrack"),pc(o,"change"),rT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=tT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,rT(["init"])).pipe(AC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ee(this.video)}prepare(){var s,n;let e=this.selectManifest();if(RC(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(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:dc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var nT=_(qr(),1),za=_(Jr(),1);import{assertNever as CC,assertNonNullable as iT,debounce as VC,ErrorCategory as aT,isHigher as OC,isHigherOrEqual as BC,isInvariantQuality as sT,isLowerOrEqual as _C,isNonNullable as NC,merge as FC,observableFrom as qC,Subscription as UC,map as HC}from"@vkontakte/videoplayer-shared/es2015";var Ka=class{constructor(e){this.subscription=new UC;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new Fe;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return CC(e)}};this.params=e,this.video=Ie(e.container,e.tuning),this.params.output.element$.next(this.video),(0,nT.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,za.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:aT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Pe(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(HC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(xe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ne(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ue(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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&&NC(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=FC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,qC(["init"])).pipe(VC(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),Ee(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;iT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];iT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Da(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(oe(t))}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:aT.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,za.default)(this.trackUrls).find(d=>!sT(d.track.quality)&&_C(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&&BC(c.quality,u.quality)&&(t=u),!t){let d=(0,za.default)(this.trackUrls).filter(h=>!sT(h.track.quality)&&OC(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,za.default)(this.trackUrls).map(l=>l.track);t=Nt(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 uT,debounce as WC,merge as lT,observableFrom as YC,Subscription as zC,map as cT,ValueSubject as KC,ErrorCategory as mc,VideoQuality as XC}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as jC}from"@vkontakte/videoplayer-shared/es2015";var oT=["stun:videostun.mycdn.me:80"],QC=1e3,GC=3,hc=()=>null,qn=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=hc;this.externalStopCallback=hc;this.externalErrorCallback=hc;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 A(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 A(this,null,function*(){try{let e={iceServers:[{urls:oT}]};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 A(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return A(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:jC.WTF,message:e.message})}onPeerConnectionStream(e){return A(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 A(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),QC)}normalizeOptions(e={}){let t={stunServerList:oT,maxRetryNumber:GC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Xa=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new KC(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"),P(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"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return uT(e)}};this.subscription=new zC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ie(e.container,e.tuning),this.liveStreamClient=new qn(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),Ee(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:mc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};lT(this.videoState.stateChangeStarted$.pipe(cT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(cT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Pe(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(Ue(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(xe(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 uT(n.to)}},r)).add(lT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,YC(["init"])).pipe(WC(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:XC.INVARIANT}),this.video.srcObject=e,P(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:mc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){we(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:mc.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 es,assertNonNullable as Qt,ErrorCategory as Un,filter as bT,isNonNullable as gT,isNullable as s0,map as n0,merge as o0,once as u0,Subject as $e,Subscription as vT,ValueSubject as O,flattenObject as ST}from"@vkontakte/videoplayer-shared/es2015";import{Observable as JC,map as dT,Subscription as ZC,Subject as e0}from"@vkontakte/videoplayer-shared/es2015";var pT=a=>new JC(e=>{let t=new ZC,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(dT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(dT(({type:l})=>l!==void 0)),n=new e0,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 t0,Subscription as r0,combine as i0,filter as mT,once as fT}from"@vkontakte/videoplayer-shared/es2015";function hT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as a0}from"@vkontakte/videoplayer-shared/es2015";var Za=class Za{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new me;this.subscriptions=new r0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(mT(s=>!!s.type),fT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){a0.isSafari&&e!=="MPEG"||this.subscriptions.add(i0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(mT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),fT()).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 A(this,null,function*(){let{volumeMultiplier:t}=this,r=hT();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:Za.errorId,category:t0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Za.errorId} exception`,thrown:e})}};Za.errorId="VolumeMultiplierManager";var di=Za;var l0={chunkDuration:5e3,maxParallelRequests:5},ts=class{constructor(e){this.current$=new O({type:void 0});this.providerError$=new $e;this.noAvailableProvidersError$=new $e;this.volumeMultiplierError$=new $e;this.providerOutput={position$:new O(0),duration$:new O(1/0),volume$:new O({muted:!1,volume:1}),availableVideoStreams$:new O([]),currentVideoStream$:new O(void 0),availableVideoTracks$:new O([]),currentVideoTrack$:new O(void 0),availableAudioStreams$:new O([]),currentAudioStream$:new O(void 0),availableAudioTracks$:new O([]),currentVideoSegmentLength$:new O(0),currentAudioSegmentLength$:new O(0),isAudioAvailable$:new O(!0),autoVideoTrackLimitingAvailable$:new O(!1),autoVideoTrackLimits$:new O(void 0),currentBuffer$:new O(void 0),isBuffering$:new O(!0),error$:new $e,warning$:new $e,willSeekEvent$:new $e,soundProhibitedEvent$:new $e,seekedEvent$:new $e,loopedEvent$:new $e,endedEvent$:new $e,firstBytesEvent$:new $e,loadedMetadataEvent$:new $e,firstFrameEvent$:new $e,canplay$:new $e,isLive$:new O(void 0),isLowLatency$:new O(!1),canChangePlaybackSpeed$:new O(!0),liveTime$:new O(void 0),liveBufferTime$:new O(void 0),liveLatency$:new O(void 0),availableTextTracks$:new O([]),currentTextTrack$:new O(void 0),hostname$:new O(void 0),httpConnectionType$:new O(void 0),httpConnectionReused$:new O(void 0),inPiP$:new O(!1),inFullscreen$:new O(!1),element$:new O(void 0),elementVisible$:new O(!0),availableSources$:new O(void 0),is3DVideo$:new O(!1),playbackState$:new O(""),getCurrentTime$:new O(null)};this.subscription=new vT;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=Hv([...Qv(this.params.tuning),...jv(this.params.tuning)],this.params.tuning).filter(l=>gT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,fc.default)(i,l)),...t.filter(l=>(0,fc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",ST(s)),this.screenFormatsIterator=new Ja(s);let n=[...Il(!0),...Il(!1)];this.chromecastFormatsIterator=new Ja(n.filter(l=>gT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&di.isSupported()&&(this.volumeMultiplierManager=new di(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(s0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Un.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 es(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 Qt(o),new Ha(L(E({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new ja(L(E({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Qt(o),ai||!this.params.tuning.useHlsJs?new Ya(L(E({},n),{source:o})):new Ga(L(E({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Wa(L(E({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ka(L(E({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new ov(L(E({},n),{source:o,config:L(E({},l0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Xa({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 es(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 Qt(o),new ji({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 es(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return es(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 es(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 L(E({},e),{url:r(e.url)})}return(0,TT.default)((0,yT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new vT,t=!1,r=0;return e.add(o0(this.providerOutput.error$.pipe(bT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),pT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(n0(i=>({id:`ProviderHangup:${i}`,category:Un.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(bT(({to:s})=>s==="playing"),u0()).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===Un.NETWORK,u=i.category===Un.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=L(E({},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 Hn,once as c0,combine as d0,Subscription as IT,ValueSubject as bc,map as p0,filter as h0,isNonNullable as jn,now as Be,safeStorage as gc}from"@vkontakte/videoplayer-shared/es2015";var m0=5e3,ET="one_video_throughput",xT="one_video_rtt",yt=window.navigator.connection,PT=()=>{let a=yt==null?void 0:yt.downlink;if(jn(a)&&a!==10)return a*1e3},wT=()=>{let a=yt==null?void 0:yt.rtt;if(jn(a)&&a!==3e3)return a},AT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},vc=class a{constructor(e){this.subscription=new IT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(ET)||(e.useBrowserEstimation?PT():void 0)||m0,r=(s=(i=a.load(xT))!=null?i:e.useBrowserEstimation?wT():void 0)!=null?s:0;if(this.throughput$=new bc(t),this.rtt$=new bc(r),this.rttAdjustedThroughput$=new bc(AT(t,r,e.rttPenaltyRequestSize)),this.throughput=vr.getSmoothedValue(t,-1,e),this.rtt=vr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=PT();u&&this.throughput.next(u);let l=wT();jn(l)&&this.rtt.next(l)};yt&&"onchange"in yt&&this.subscription.add(Hn(yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{gc.set(ET,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{gc.set(xT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(d0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(p0(({throughput:n,rtt:o})=>AT(n,o,e.rttPenaltyRequestSize)),h0(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=Be(),i=new IT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Hn(e,"progress").pipe(c0()).subscribe(s=>{t=s.loaded,r=Be()}));break;case 1:case 0:i.add(Hn(e,"loadstart").subscribe(()=>{t=0,r=Be()}));break}i.add(Hn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Be(),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=Be(),n=0,o=Be(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>A(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Be()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Be();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Be()}else n+=d.byteLength;o=Be()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Be()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Be()-o,this.concurrentDownloads.size),n=0,o=Be());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=gc.get(e);if(jn(t))return(r=parseInt(t,10))!=null?r:void 0}},kT=vc;import{fillWithDefault as f0,VideoQuality as Qn}from"@vkontakte/videoplayer-shared/es2015";var RT={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:Qn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Qn.Q_720P,trafficSavingLimit:Qn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Qn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},LT=a=>{var e;return L(E({},f0(a,RT)),{configName:[...(e=a.configName)!=null?e:[],...RT.configName]})};import{assertNonNullable as Gn,combine as Tt,ErrorCategory as Wn,filter as ye,filterChanged as Q,fromEvent as yc,isNonNullable as I0,isNullable as E0,Logger as x0,map as H,mapTo as CT,merge as Gt,now as Yn,once as ct,Subject as z,Subscription as VT,tap as OT,ValueSubject as w,isHigher as P0,isInvariantQuality as BT,flattenObject as Wt,throttle as Tc,getTraceSubscriptionMethod as _T,Tracer as w0,InternalsExposure as A0}from"@vkontakte/videoplayer-shared/es2015";import{merge as b0,map as g0,filter as $T,isNonNullable as v0}from"@vkontakte/videoplayer-shared/es2015";var Sc=({seekState:a,position$:e})=>b0(a.stateChangeEnded$.pipe(g0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),$T(v0)),e.pipe($T(()=>a.getState().state==="none")));import{assertNonNullable as S0}from"@vkontakte/videoplayer-shared/es2015";var MT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return S0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as y0,once as T0}from"@vkontakte/videoplayer-shared/es2015";var DT=(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(y0(i=>i.length>0),T0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var zn=class{constructor(e={configName:[]},t=w0.createRootTracer(!1)){this.subscription=new VT;this.logger=new x0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new w(!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 w("stopped"),position$:new w(0),duration$:new w(1/0),muted$:new w(!1),volume$:new w(1),availableVideoStreams$:new w([]),currentVideoStream$:new w(void 0),availableQualities$:new w([]),availableQualitiesFps$:new w({}),currentQuality$:new w(void 0),isAutoQualityEnabled$:new w(!0),autoQualityLimitingAvailable$:new w(!1),autoQualityLimits$:new w({}),predefinedQualityLimitType$:new w("unknown"),availableAudioStreams$:new w([]),currentAudioStream$:new w(void 0),availableAudioTracks$:new w([]),isAudioAvailable$:new w(!0),currentPlaybackRate$:new w(1),currentBuffer$:new w({start:0,end:0}),isBuffering$:new w(!0),isStalled$:new w(!1),isEnded$:new w(!1),isLooped$:new w(!1),isLive$:new w(void 0),canChangePlaybackSpeed$:new w(void 0),atLiveEdge$:new w(void 0),atLiveDurationEdge$:new w(void 0),liveTime$:new w(void 0),liveBufferTime$:new w(void 0),liveLatency$:new w(void 0),currentFormat$:new w(void 0),availableTextTracks$:new w([]),currentTextTrack$:new w(void 0),throughputEstimation$:new w(void 0),rttEstimation$:new w(void 0),videoBitrate$:new w(void 0),hostname$:new w(void 0),httpConnectionType$:new w(void 0),httpConnectionReused$:new w(void 0),surface$:new w("none"),chromecastState$:new w("NOT_AVAILABLE"),chromecastDeviceName$:new w(void 0),intrinsicVideoSize$:new w(void 0),availableSources$:new w(void 0),is3DVideo$:new w(!1),currentVideoSegmentLength$:new w(0),currentAudioSegmentLength$:new w(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 w(void 0),tuningConfigName$:new w([]),enableDebugTelemetry$:new w(!1),dumpTelemetry:Vg,getCurrentTime$:new w(null)};if(this.initLogs(),this.tuning=LT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ts({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new kT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new A0("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(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return(0,NT.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:Wn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=id(i,["container"]);return this.tracer.log("initVideo",Wt(r)),this.domContainer=MT(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new ts({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&&!Zi()?(this.tracer.log("request play from hidden tab"),yc(document,"visibilitychange").pipe(ct()).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){Gn(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(ye(r=>r.length>0),ct()).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",Wt(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;Gn(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",Wt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>E({type:"external"},t))),this}selectTextTrack(e){var t;return DT(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",E({},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(E0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return I0(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(Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(H(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:r}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(Zs({limits:e,highQualityLimit:t,trafficSavingLimit:r}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ye(({from:e})=>e==="stopped"),ct()).subscribe(()=>{this.initedAt=Yn(),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",Wt(n)),n.state==="requested"?this.desiredState.seekState.setState(L(E({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Wn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ct()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Wt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(H(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(H(n=>n.destination),Q()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Tt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(H(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>BT(u)?1:BT(l)?-1:P0(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(H(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(Tt({hasLiveOffsetByPaused:Gt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(H(n=>n.to),Q(),H(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(Tt({atLiveEdge:Tt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(H(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Q(),OT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(H(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Tt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(H(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Q(),OT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(H(n=>n.muted),Q()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(H(n=>n.volume),Q()).subscribe(this.info.volume$)).add(Sc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Gt(e.providerOutput.endedEvent$.pipe(CT(!0)),e.providerOutput.seekedEvent$.pipe(CT(!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(H(n=>({id:n?`No${n}`:"NoProviders",category:Wn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(ct(),H(n=>n!=null?n:Yn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ct(),H(()=>Yn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ct(),H(()=>Yn()-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 w(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new w(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ye(({to:n})=>n==="playing"),ct()).subscribe(()=>r.next(!1)));let i=0,s=Gt(e.providerOutput.isBuffering$,t,r).pipe(H(()=>{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(Gt(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(Gt(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(H(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 VT;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(ye(r=>r.length>0),ct()).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=Nt(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(Gt(this.desiredState.videoTrack.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(H(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;Gn(this.providerContainer),Gn(e),Cg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Dg(r)),this.providerContainer.current$.subscribe(({type:r})=>Wi("provider",r)),e.duration$.subscribe(r=>Wi("duration",r)),e.availableVideoTracks$.pipe(ye(r=>!!r.length),ct()).subscribe(r=>Wi("tracks",r)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(H(r=>r==null?void 0:r.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(r=>this.subscription.add(r)),Wi("codecs",Uv())}initTracerSubscription(){let e=_T(this.tracer.log.bind(this.tracer)),t=_T(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(Tt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ye(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),Q((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ye(r=>r>0),Q()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ye(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(Tt({currentBuffer:this.info.currentBuffer$.pipe(ye(r=>r.end>0),Q((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(Q())}).pipe(Tc(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(Tt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ye(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Tc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Q(),ye(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Q(),ye(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(),ye(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Tt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ye(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Tc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Q(),ye(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=()=>A(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:Wn.DOM,message:String(i)})})});this.subscription.add(Gt(yc(document,"visibilitychange"),yc(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",Wt({quality:t,availableTracks:Wt(e),track:Wt(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 q4,Observable as U4,Subject as H4,ValueSubject as j4,VideoQuality as Q4}from"@vkontakte/videoplayer-shared/es2015";var G4=`@vkontakte/videoplayer-core@${ad}`;export{fs as ChromecastState,ao as HttpConnectionType,U4 as Observable,Te as PlaybackState,zn as Player,yi as PredefinedQualityLimits,G4 as SDK_VERSION,H4 as Subject,q4 as Subscription,so as Surface,ad as VERSION,j4 as ValueSubject,Lt as VideoFormat,Q4 as VideoQuality};
124
+ `;var Ln=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 Rn(this.params.fov,this.params.orientation),this.cameraRotationManager=new $n(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(My,this.gl.VERTEX_SHADER),r=this.createShader(Dy,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,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as LD,now as Cy,Subscription as MD,filter as DD,combine as Oy,ValueSubject as Jl,isNonNullable as CD}from"@vkontakte/videoplayer-shared/es2015";var Zl=class{constructor(){this.isSeeked$=new Jl(!1);this.isBuffering$=new Jl(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new MD;this.severeStallOccurred$=new Jl(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(Oy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(DD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Oy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(LD(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=Cy(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,CD(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=Cy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Vy=Zl;import{combine as OD,map as VD,observeElementSize as BD,Subscription as _D,ValueSubject as ec,noop as ND}from"@vkontakte/videoplayer-shared/es2015";var Mn=class{constructor(){this.subscription=new _D;this.pipSize$=new ec(void 0);this.videoSize$=new ec(void 0);this.elementSize$=new ec(void 0);this.pictureInPictureWindowRemoveEventListener=ND}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(BD(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(OD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(VD(({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 Er=class{constructor(e){this.subscription=new QD;this.videoState=new C("stopped");this.droppedFramesManager=new sn;this.stallsManager=new Vy;this.elementSizeManager=new Mn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Yi;this.audioTrackSwitchHistory=new Yi;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.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"),P(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"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&P(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"&&P(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"&&P(this.params.desiredState.playbackState,"paused");return;default:return UD(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Ln(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.textTracksManager=new qe(e.source.url),this.params=e,this.video=Ee(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(ue(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 kn({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=we(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:tc.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(By(c=>!!c.length),Ny()).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(rc(c=>c.to.state!=="none"),qa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(qa()),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(By(_y),Ny()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(rc(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Pe(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Fe(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(He(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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(HD(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(_l(f));let b=[];for(let g of f.representations){let v=cy(g);b.push(v),this.audioTracksMap.set(v,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(Nl(h));let f=[];for(let b of h.representations){let g=ly($(I({},b),{streamId:h.id}));g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let f of h.representations){let b=dy(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:tc.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Dn(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$,GD(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Fy.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=[...this.videoTracksMap.keys()].find(v=>{var S;return((S=this.videoTracksMap.get(v))==null?void 0:S.representation.id)===h.id});_y(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),f){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,v).catch(o)}},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(qa()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(Nl(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(qa()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(_l(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.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(rc(({to:c})=>c==="ready"),qa());this.subscription.add(Dn(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,ic(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Dn(u,this.player.state$.stateChangeEnded$,ic(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Dn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ic(["init"])).pipe(jD(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var O,J,M,N,F,R,q,_,Y,k,T,D,Q;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(O=e.videoTrack.getState())==null?void 0:O.id,n=[...this.videoTracksMap.keys()].find(({id:H})=>H===i),o=t.currentVideoTrack$.getValue(),u=((N=(M=e.videoStream.getState())!=null?M:n&&((J=this.videoTracksMap.get(n))==null?void 0:J.stream))!=null?N:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:H})=>H===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=lt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,f=Math.min(d/Math.min(p,h||1/0),1),b=(F=e.audioStream.getState())!=null?F:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(R=[...this.audioStreamsMap.keys()].find(({id:H})=>H===(b==null?void 0:b.id)))!=null?R:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!r){let H=en(n,c,(q=this.audioStreamsMap.get(g))!=null?q:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(_=H==null?void 0:H.bitrate)!=null?_:-1/0)}if(o){let H=en(o,c,(Y=this.audioStreamsMap.get(g))!=null?Y:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(k=H==null?void 0:H.bitrate)!=null?k:-1/0)}}let S=Ft(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:f,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),y=r?S!=null?S:n:n!=null?n:S,x=g&&Ug(y,c,(T=this.audioStreamsMap.get(g))!=null?T:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:f,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),E=(D=this.videoTracksMap.get(y))==null?void 0:D.representation,L=x&&((Q=this.audioTracksMap.get(x))==null?void 0:Q.representation);if(E&&L)return[E,L];if(E&&!L&&this.audioTracksMap.size===0)return[E,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:tc.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),xe(this.video),this.tracer.end()}};var Ua=class extends Er{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 qy,interval as WD,map as Uy}from"@vkontakte/videoplayer-shared/es2015";var Ha=class extends Er{constructor(e){super(e),this.liveOffset=new mt,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(Uy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(qy({interval:WD(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(qy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Uy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=py(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 jy=B(zs(),1);import{assertNever as ja,assertNonNullable as Hy,debounce as YD,ErrorCategory as Cn,filter as zD,isNonNullable as KD,isNullable as XD,map as On,merge as JD,Observable as ZD,observableFrom as eC,Subscription as tC,videoSizeToQuality as rC}from"@vkontakte/videoplayer-shared/es2015";var tt={};var pi=(a,e)=>new ZD(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ga=class{constructor(e){this.subscription=new tC;this.videoState=new C("initializing");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:ja(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ja(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ja(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ja(e)}break;default:ja(t)}};this.textTracksManager=new qe(e.source.url),this.video=Ee(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(ue(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),xe(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Cn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,jy.default)(import("hls.js").then(i=>{e||(tt.Hls=i.default,tt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Hy(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Hy(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Cn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=we(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(ot(this.video,e.isLooped,r)),this.subscription.add(Pe(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Fe(this.video,e.playbackRate,i.playbackRateState$,r)),s(He(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(On(l=>l.to)),this.params.output.playbackState$),this.subscription.add(pi(this.hls,tt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Cn.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"),P(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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(pi(this.hls,tt.Events.MANIFEST_PARSED).pipe(On(({levels:l})=>l.reduce((c,d)=>{var S,y;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(y=_t((S=d.attrs.QUALITY)!=null?S:""))!=null?y:rC({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(pi(this.hls,tt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(pi(this.hls,tt.Events.LEVEL_LOADING).pipe(On(({url:l})=>ue(l))),t.hostname$),s(pi(this.hls,tt.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Ot(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=pi(this.hls,tt.Events.LEVEL_SWITCHED).pipe(On(({level:l})=>n(this.hls.levels[l])));o.pipe(zD(KD)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ot(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(XD(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=JD(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,eC(["init"])).pipe(YD(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 w(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cn.DOM,thrown:t})))||(this.videoState.setState("paused"),P(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"),P(this.params.desiredState.playbackState,"stopped",!0)}};var Gy="X-Playback-Duration",ac=a=>w(void 0,null,function*(){var i;let e=yield Ze(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(Gy)?parseInt(e.headers.get(Gy),10):void 0});import{assertNever as hC,combine as fC,debounce as mC,ErrorCategory as _n,filter as bC,filterChanged as gC,isNonNullable as Yy,isNullable as Nn,map as zy,merge as vC,observableFrom as SC,Subscription as yC,ValueSubject as oc,VideoQuality as TC}from"@vkontakte/videoplayer-shared/es2015";var nc=B(lu(),1);import{videoSizeToQuality as iC,getExponentialDelay as aC}from"@vkontakte/videoplayer-shared/es2015";var sC=a=>{let e=null;if(a.QUALITY&&(e=_t(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=iC({width:t,height:r})}return e!=null?e:null},nC=(a,e)=>{var s,n;let t=a.split(`
125
+ `),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,nc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=sC(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[S,y]=d.RESOLUTION.split("x").map(x=>parseInt(x,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:f,size:g,fps:b})}if(c){let d=(0,nc.default)(c[1].split(",").map(b=>{let g=b.indexOf("=");return[b.substring(0,g),b.substring(g+1)]}).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},oC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),sc=0,Qy=(i,...s)=>w(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield Ze(a,r)).text();sc+=1;try{let{qualityManifests:u,textTracks:l}=nC(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(sc<=t.manifestRetryMaxCount)return yield oC(aC(sc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Qy(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Vn=Qy;import{isNonNullable as uC,Subscription as lC,throttle as cC,ValueSubject as Wy,Subject as dC,ErrorCategory as pC}from"@vkontakte/videoplayer-shared/es2015";var Bn=class{constructor(e,t,r,i,s){this.subscription=new lC;this.abortControllers={destroy:new me,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Wy(null);this.getCurrentTime$=new Wy(null);this.error$=new dC;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(cC(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return w(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=yield this.fetchManifestData();yield this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return w(this,null,function*(){try{let r=yield this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}})}parseTextTracks(e,t){return w(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield Ze(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}})}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
126
+ `),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(uC(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([$(I({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return w(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new me;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return w(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:pC.WTF,thrown:t,message:e})}};var Qa=class{constructor(e){this.subscription=new yC;this.videoState=new C("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new oc([]);this.liveOffset=new mt;this.manifestStartTime$=new oc(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"),P(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&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(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"&&P(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"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return hC(t)}};var r;this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:TC.INVARIANT,url:this.params.source.url};let t=(i,s)=>Vn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new Bn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new qe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:_n.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:_n.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new oc((r=e.source.maxSeekBackTime)!=null?r: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(p=>p.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=we(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(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(gC(),zy(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&&Yy(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ue(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(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(fC({startTime:this.manifestStartTime$.pipe(bC(Yy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(zy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=vC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,SC(["init"])).pipe(mC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Nn(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:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let f=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,f)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=fe(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),ac(n).then(c=>{var d;if(!Nn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Nn(p)||!isFinite(p))&&Ze(n).then(h=>h.text()).then(h=>{var b;let f=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(f){let g=new URL(f,n).toString();ac(g).then(v=>{Nn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(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()}generateLiveUrl(){let e=fe(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as IC,debounce as EC,ErrorCategory as uc,fromEvent as lc,isNonNullable as xC,isNullable as PC,map as Ky,merge as Xy,observableFrom as Jy,Subscription as wC,ValueSubject as AC,VideoQuality as kC,clientChecker as RC}from"@vkontakte/videoplayer-shared/es2015";var Wa=class{constructor(e){this.subscription=new wC;this.videoState=new C("stopped");this.manifests$=new AC([]);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"),P(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"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return IC(t)}};this.textTracksManager=new qe(e.source.url),this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:kC.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(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Vn(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:uc.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(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:uc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=we(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(Ky(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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 h;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&&xC(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(ue(b.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){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(Ky(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!RC.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(Xy(lc(o,"addtrack"),lc(o,"removetrack"),lc(o,"change"),Jy(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=Xy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Jy(["init"])).pipe(EC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),xe(this.video)}prepare(){var s,n;let e=this.selectManifest();if(PC(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(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:uc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var rT=B(Ur(),1),Ya=B(Zr(),1);import{assertNever as $C,assertNonNullable as Zy,debounce as LC,ErrorCategory as eT,isHigher as MC,isHigherOrEqual as DC,isInvariantQuality as tT,isLowerOrEqual as CC,isNonNullable as OC,merge as VC,observableFrom as BC,Subscription as _C,map as NC}from"@vkontakte/videoplayer-shared/es2015";var za=class{constructor(e){this.subscription=new _C;this.videoState=new C("stopped");this.trackUrls={};this.textTracksManager=new qe;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"),P(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"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return $C(e)}};this.params=e,this.video=Ee(e.container,e.tuning),this.params.output.element$.next(this.video),(0,rT.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,Ya.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:eT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=we(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(NC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Pe(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Fe(this.video,t.playbackRate,i.playbackRateState$,r)),s(He(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(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&&OC(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=VC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,BC(["init"])).pipe(LC(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),xe(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Zy(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Zy(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ma(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:eT.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,Ya.default)(this.trackUrls).find(d=>!tT(d.track.quality)&&CC(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&&DC(c.quality,u.quality)&&(t=u),!t){let d=(0,Ya.default)(this.trackUrls).filter(h=>!tT(h.track.quality)&&MC(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Ya.default)(this.trackUrls).map(l=>l.track);t=Ft(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 aT,debounce as HC,merge as sT,observableFrom as jC,Subscription as GC,map as nT,ValueSubject as QC,ErrorCategory as dc,VideoQuality as WC}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as FC}from"@vkontakte/videoplayer-shared/es2015";var iT=["stun:videostun.mycdn.me:80"],qC=1e3,UC=3,cc=()=>null,Fn=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=cc;this.externalStopCallback=cc;this.externalErrorCallback=cc;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 w(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 w(this,null,function*(){try{let e={iceServers:[{urls:iT}]};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 w(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return w(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:FC.WTF,message:e.message})}onPeerConnectionStream(e){return w(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 w(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),qC)}normalizeOptions(e={}){let t={stunServerList:iT,maxRetryNumber:UC,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ka=class{constructor(e){this.videoState=new C("stopped");this.maxSeekBackTime$=new QC(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"),P(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"),P(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"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return aT(e)}};this.subscription=new GC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ee(e.container,e.tuning),this.liveStreamClient=new Fn(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),xe(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:dc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};sT(this.videoState.stateChangeStarted$.pipe(nT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(nT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=we(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(He(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(Pe(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 aT(n.to)}},r)).add(sT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,jC(["init"])).pipe(HC(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(ue(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:WC.INVARIANT}),this.video.srcObject=e,P(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:dc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ae(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:dc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Xa=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 Za,assertNonNullable as Wt,ErrorCategory as qn,filter as pT,isNonNullable as hT,isNullable as t0,map as r0,merge as i0,once as a0,Subject as Le,Subscription as fT,ValueSubject as V,flattenObject as mT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as YC,map as oT,Subscription as zC,Subject as KC}from"@vkontakte/videoplayer-shared/es2015";var uT=a=>new YC(e=>{let t=new zC,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(oT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(oT(({type:l})=>l!==void 0)),n=new KC,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 XC,Subscription as JC,combine as ZC,filter as cT,once as dT}from"@vkontakte/videoplayer-shared/es2015";function lT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as e0}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 JC;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(cT(s=>!!s.type),dT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){e0.isSafari&&e!=="MPEG"||this.subscriptions.add(ZC({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(cT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),dT()).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 w(this,null,function*(){let{volumeMultiplier:t}=this,r=lT();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:XC.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Ja.errorId} exception`,thrown:e})}};Ja.errorId="VolumeMultiplierManager";var hi=Ja;var s0={chunkDuration:5e3,maxParallelRequests:5},es=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new Le;this.noAvailableProvidersError$=new Le;this.volumeMultiplierError$=new Le;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableVideoTracks$:new V([]),currentVideoTrack$:new V(void 0),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new Le,warning$:new Le,willSeekEvent$:new Le,soundProhibitedEvent$:new Le,seekedEvent$:new Le,loopedEvent$:new Le,endedEvent$:new Le,firstBytesEvent$:new Le,loadedMetadataEvent$:new Le,firstFrameEvent$:new Le,canplay$:new Le,isLive$:new V(void 0),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V(""),getCurrentTime$:new V(null)};this.subscription=new fT;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=Nv([...qv(this.params.tuning),...Fv(this.params.tuning)],this.params.tuning).filter(l=>hT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,pc.default)(i,l)),...t.filter(l=>(0,pc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",mT(s)),this.screenFormatsIterator=new Xa(s);let n=[...Sl(!0),...Sl(!1)];this.chromecastFormatsIterator=new Xa(n.filter(l=>hT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&hi.isSupported()&&(this.volumeMultiplierManager=new hi(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(t0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:qn.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 Za(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 Wt(o),new Ua($(I({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Ha($(I({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Wt(o),si||!this.params.tuning.useHlsJs?new Wa($(I({},n),{source:o})):new Ga($(I({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Qa($(I({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Wt(o),new za($(I({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new iv($(I({},n),{source:o,config:$(I({},s0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Wt(o),new Ka({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 Za(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 Wt(o),new ji({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 Za(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Za(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 Za(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 $(I({},e),{url:r(e.url)})}return(0,gT.default)((0,bT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new fT,t=!1,r=0;return e.add(i0(this.providerOutput.error$.pipe(pT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),uT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r0(i=>({id:`ProviderHangup:${i}`,category:qn.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(pT(({to:s})=>s==="playing"),a0()).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===qn.NETWORK,u=i.category===qn.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=$(I({},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",mT(n))})),e}};import{fromEvent as Un,once as n0,combine as o0,Subscription as vT,ValueSubject as hc,map as u0,filter as l0,isNonNullable as Hn,now as Ve,safeStorage as fc}from"@vkontakte/videoplayer-shared/es2015";var c0=5e3,ST="one_video_throughput",yT="one_video_rtt",yt=window.navigator.connection,TT=()=>{let a=yt==null?void 0:yt.downlink;if(Hn(a)&&a!==10)return a*1e3},IT=()=>{let a=yt==null?void 0:yt.rtt;if(Hn(a)&&a!==3e3)return a},ET=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},mc=class a{constructor(e){this.subscription=new vT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(ST)||(e.useBrowserEstimation?TT():void 0)||c0,r=(s=(i=a.load(yT))!=null?i:e.useBrowserEstimation?IT():void 0)!=null?s:0;if(this.throughput$=new hc(t),this.rtt$=new hc(r),this.rttAdjustedThroughput$=new hc(ET(t,r,e.rttPenaltyRequestSize)),this.throughput=Sr.getSmoothedValue(t,-1,e),this.rtt=Sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=TT();u&&this.throughput.next(u);let l=IT();Hn(l)&&this.rtt.next(l)};yt&&"onchange"in yt&&this.subscription.add(Un(yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{fc.set(ST,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{fc.set(yT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(o0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(u0(({throughput:n,rtt:o})=>ET(n,o,e.rttPenaltyRequestSize)),l0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Ve(),i=new vT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Un(e,"progress").pipe(n0()).subscribe(s=>{t=s.loaded,r=Ve()}));break;case 1:case 0:i.add(Un(e,"loadstart").subscribe(()=>{t=0,r=Ve()}));break}i.add(Un(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ve(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Ve(),n=0,o=Ve(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>w(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Ve()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Ve();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Ve()}else n+=d.byteLength;o=Ve()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ve()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ve()-o,this.concurrentDownloads.size),n=0,o=Ve());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,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=fc.get(e);if(Hn(t))return(r=parseInt(t,10))!=null?r:void 0}},xT=mc;import{fillWithDefault as d0,VideoQuality as PT}from"@vkontakte/videoplayer-shared/es2015";var wT={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:50,maxLastEvaluationTimeout:300}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:2.8,bitrateAudioFactorAtEmptyBuffer:10,bitrateFactorAtFullBuffer:2,bitrateAudioFactorAtFullBuffer:7,minVideoAudioRatio:5,minAvailableThroughputAudioRatio:5,usePixelRatio:!0,pixelRatioMultiplier:void 0,pixelRatioLogBase:3,pixelRatioLogCoefficients:[1,0,1],limitByContainer:!0,containerSizeFactor:1.3,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldownIncreaseQuality:15e3,trackCooldownDecreaseQuality:3e3,backgroundVideoQualityLimit:PT.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:PT.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,useRefactoredSearchGap:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},AT=a=>{var e;return $(I({},d0(a,wT)),{configName:[...(e=a.configName)!=null?e:[],...wT.configName]})};import{assertNonNullable as jn,combine as Tt,ErrorCategory as Gn,filter as Te,filterChanged as G,fromEvent as gc,isNonNullable as v0,isNullable as S0,Logger as y0,map as U,mapTo as LT,merge as Yt,now as Qn,once as ct,Subject as K,Subscription as MT,tap as DT,ValueSubject as A,isHigher as T0,isInvariantQuality as CT,flattenObject as zt,throttle as vc,getTraceSubscriptionMethod as OT,Tracer as I0,InternalsExposure as E0}from"@vkontakte/videoplayer-shared/es2015";import{merge as p0,map as h0,filter as kT,isNonNullable as f0}from"@vkontakte/videoplayer-shared/es2015";var bc=({seekState:a,position$:e})=>p0(a.stateChangeEnded$.pipe(h0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),kT(f0)),e.pipe(kT(()=>a.getState().state==="none")));import{assertNonNullable as m0}from"@vkontakte/videoplayer-shared/es2015";var RT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return m0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as b0,once as g0}from"@vkontakte/videoplayer-shared/es2015";var $T=(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(b0(i=>i.length>0),g0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Wn=class{constructor(e={configName:[]},t=I0.createRootTracer(!1)){this.subscription=new MT;this.logger=new y0;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 K,ready$:new K,started$:new K,playing$:new K,paused$:new K,stopped$:new K,willStart$:new K,willResume$:new K,willPause$:new K,willStop$:new K,willDestruct$:new K,watchCoverageRecord$:new K,watchCoverageLive$:new K,managedError$:new K,fatalError$:new K,ended$:new K,looped$:new K,seeked$:new K,willSeek$:new K,autoplaySoundProhibited$:new K,firstBytes$:new K,loadedMetadata$:new K,firstFrame$:new K,canplay$:new K,log$:new K};this.experimental={element$:new A(void 0),tuningConfigName$:new A([]),enableDebugTelemetry$:new A(!1),dumpTelemetry:Mg,getCurrentTime$:new A(null)};if(this.initLogs(),this.tuning=AT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ts({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new xT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new E0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,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(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,VT.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:Gn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=ed(i,["container"]);return this.tracer.log("initVideo",zt(r)),this.domContainer=RT(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new es({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&&!Zi()?(this.tracer.log("request play from hidden tab"),gc(document,"visibilitychange").pipe(ct()).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-.2),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){jn(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(Te(r=>r.length>0),ct()).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",zt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;jn(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",zt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>I({type:"external"},t))),this}selectTextTrack(e){var t;return $T(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",I({},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(S0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return v0(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(Yt(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(Te(({from:e})=>e==="stopped"),ct()).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",zt(n)),n.state==="requested"?this.desiredState.seekState.setState($(I({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Gn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ct()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",zt(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(Tt({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)=>CT(u)?1:CT(l)?-1:T0(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(Tt({hasLiveOffsetByPaused:Yt(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(Tt({atLiveEdge:Tt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:bc({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(),DT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(U(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Tt({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(),DT(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(bc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Yt(e.providerOutput.endedEvent$.pipe(LT(!0)),e.providerOutput.seekedEvent$.pipe(LT(!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:Gn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(ct(),U(n=>n!=null?n:Qn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ct(),U(()=>Qn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ct(),U(()=>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(Te(({to:n})=>n==="playing"),ct()).subscribe(()=>r.next(!1)));let i=0,s=Yt(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(Yt(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(Yt(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 MT;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(Te(r=>r.length>0),ct()).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=Ft(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(Yt(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;jn(this.providerContainer),jn(e),Lg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>$g(r)),this.providerContainer.current$.subscribe(({type:r})=>Wi("provider",r)),e.duration$.subscribe(r=>Wi("duration",r)),e.availableVideoTracks$.pipe(Te(r=>!!r.length),ct()).subscribe(r=>Wi("tracks",r)),this.events.fatalError$.subscribe(new ve("fatalError")),this.events.managedError$.subscribe(new ve("managedError")),e.position$.subscribe(new ve("position")),e.currentVideoTrack$.pipe(U(r=>r==null?void 0:r.quality)).subscribe(new ve("quality")),this.info.currentBuffer$.subscribe(new ve("buffer")),e.isBuffering$.subscribe(new ve("isBuffering"))].forEach(r=>this.subscription.add(r)),Wi("codecs",_v())}initTracerSubscription(){let e=OT(this.tracer.log.bind(this.tracer)),t=OT(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(Tt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Te(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),G((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(Te(r=>r>0),G()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(Te(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(Tt({currentBuffer:this.info.currentBuffer$.pipe(Te(r=>r.end>0),G((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(G())}).pipe(vc(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(Tt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Te(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),vc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(G(),Te(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(G(),Te(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(),Te(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Tt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Te(({throughputEstimation:r,rtt:i})=>!!r&&!!i),vc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(G(),Te(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=()=>w(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:Gn.DOM,message:String(i)})})});this.subscription.add(Yt(gc(document,"visibilitychange"),gc(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",zt({quality:t,availableTracks:zt(e),track:zt(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 R4,Observable as $4,Subject as L4,ValueSubject as M4,VideoQuality as D4}from"@vkontakte/videoplayer-shared/es2015";var C4=`@vkontakte/videoplayer-core@${td}`;export{ms as ChromecastState,to as HttpConnectionType,$4 as Observable,Ie as PlaybackState,Wn as Player,C4 as SDK_VERSION,L4 as Subject,R4 as Subscription,ro as Surface,td as VERSION,M4 as ValueSubject,Lt as VideoFormat,D4 as VideoQuality};