@vkontakte/videoplayer-core 2.0.130-dev.afe0f37e.0 → 2.0.130-dev.ca914dc0.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,12 +1,12 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.130-dev.afe0f37e.0
3
- * Mon, 07 Apr 2025 10:04:46 GMT
2
+ * @vkontakte/videoplayer-core v2.0.130-dev.ca914dc0.0
3
+ * Tue, 08 Apr 2025 14:25:05 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-130/doc/
5
5
  */
6
- var tI=Object.create;var ro=Object.defineProperty,iI=Object.defineProperties,rI=Object.getOwnPropertyDescriptor,aI=Object.getOwnPropertyDescriptors,sI=Object.getOwnPropertyNames,hs=Object.getOwnPropertySymbols,nI=Object.getPrototypeOf,ao=Object.prototype.hasOwnProperty,bd=Object.prototype.propertyIsEnumerable;var oI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,fd=(a,e,t)=>e in a?ro(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,A=(a,e)=>{for(var t in e||(e={}))ao.call(e,t)&&fd(a,t,e[t]);if(hs)for(var t of hs(e))bd.call(e,t)&&fd(a,t,e[t]);return a},C=(a,e)=>iI(a,aI(e));var gd=(a,e)=>{var t={};for(var i in a)ao.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&hs)for(var i of hs(a))e.indexOf(i)<0&&bd.call(a,i)&&(t[i]=a[i]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var uI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of sI(e))!ao.call(a,r)&&r!==t&&ro(a,r,{get:()=>e[r],enumerable:!(i=rI(e,r))||i.enumerable});return a};var B=(a,e,t)=>(t=a!=null?tI(nI(a)):{},uI(e||!a||!a.__esModule?ro(t,"default",{value:a,enumerable:!0}):t,a));var P=(a,e,t)=>new Promise((i,r)=>{var s=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),ms=function(a,e){this[0]=a,this[1]=e},oe=(a,e,t)=>{var i=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof ms,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>s[n]=o=>new Promise((u,l)=>i(n,o,u,l)),s={};return t=t.apply(a,e),s[oI("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var se=f((oo,Sd)=>{"use strict";var gr=function(a){return a&&a.Math===Math&&a};Sd.exports=gr(typeof globalThis=="object"&&globalThis)||gr(typeof window=="object"&&window)||gr(typeof self=="object"&&self)||gr(typeof global=="object"&&global)||gr(typeof oo=="object"&&oo)||function(){return this}()||Function("return this")()});var fe=f((_0,yd)=>{"use strict";yd.exports=function(a){try{return!!a()}catch(e){return!0}}});var vr=f((N0,Td)=>{"use strict";var lI=fe();Td.exports=!lI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var uo=f((F0,Pd)=>{"use strict";var cI=vr(),xd=Function.prototype,Id=xd.apply,Ed=xd.call;Pd.exports=typeof Reflect=="object"&&Reflect.apply||(cI?Ed.bind(Id):function(){return Ed.apply(Id,arguments)})});var ce=f((q0,kd)=>{"use strict";var wd=vr(),Ad=Function.prototype,lo=Ad.call,dI=wd&&Ad.bind.bind(lo,lo);kd.exports=wd?dI:function(a){return function(){return lo.apply(a,arguments)}}});var ii=f((U0,Ld)=>{"use strict";var Rd=ce(),pI=Rd({}.toString),hI=Rd("".slice);Ld.exports=function(a){return hI(pI(a),8,-1)}});var co=f((H0,$d)=>{"use strict";var mI=ii(),fI=ce();$d.exports=function(a){if(mI(a)==="Function")return fI(a)}});var re=f((j0,Md)=>{"use strict";var po=typeof document=="object"&&document.all;Md.exports=typeof po=="undefined"&&po!==void 0?function(a){return typeof a=="function"||a===po}:function(a){return typeof a=="function"}});var Ve=f((Q0,Dd)=>{"use strict";var bI=fe();Dd.exports=!bI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Oe=f((G0,Cd)=>{"use strict";var gI=vr(),gs=Function.prototype.call;Cd.exports=gI?gs.bind(gs):function(){return gs.apply(gs,arguments)}});var ho=f(Bd=>{"use strict";var Vd={}.propertyIsEnumerable,Od=Object.getOwnPropertyDescriptor,vI=Od&&!Vd.call({1:2},1);Bd.f=vI?function(e){var t=Od(this,e);return!!t&&t.enumerable}:Vd});var Sr=f((Y0,_d)=>{"use strict";_d.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Fd=f((z0,Nd)=>{"use strict";var SI=ce(),yI=fe(),TI=ii(),mo=Object,II=SI("".split);Nd.exports=yI(function(){return!mo("z").propertyIsEnumerable(0)})?function(a){return TI(a)==="String"?II(a,""):mo(a)}:mo});var Ri=f((K0,qd)=>{"use strict";qd.exports=function(a){return a==null}});var Mt=f((X0,Ud)=>{"use strict";var EI=Ri(),xI=TypeError;Ud.exports=function(a){if(EI(a))throw new xI("Can't call method on "+a);return a}});var ri=f((J0,Hd)=>{"use strict";var PI=Fd(),wI=Mt();Hd.exports=function(a){return PI(wI(a))}});var Be=f((Z0,jd)=>{"use strict";var AI=re();jd.exports=function(a){return typeof a=="object"?a!==null:AI(a)}});var Li=f((eV,Qd)=>{"use strict";Qd.exports={}});var ft=f((tV,Wd)=>{"use strict";var fo=Li(),bo=se(),kI=re(),Gd=function(a){return kI(a)?a:void 0};Wd.exports=function(a,e){return arguments.length<2?Gd(fo[a])||Gd(bo[a]):fo[a]&&fo[a][e]||bo[a]&&bo[a][e]}});var yr=f((iV,Yd)=>{"use strict";var RI=ce();Yd.exports=RI({}.isPrototypeOf)});var ai=f((rV,Xd)=>{"use strict";var LI=se(),zd=LI.navigator,Kd=zd&&zd.userAgent;Xd.exports=Kd?String(Kd):""});var vo=f((aV,rp)=>{"use strict";var ip=se(),go=ai(),Jd=ip.process,Zd=ip.Deno,ep=Jd&&Jd.versions||Zd&&Zd.version,tp=ep&&ep.v8,Ye,vs;tp&&(Ye=tp.split("."),vs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!vs&&go&&(Ye=go.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=go.match(/Chrome\/(\d+)/),Ye&&(vs=+Ye[1])));rp.exports=vs});var So=f((sV,sp)=>{"use strict";var ap=vo(),$I=fe(),MI=se(),DI=MI.String;sp.exports=!!Object.getOwnPropertySymbols&&!$I(function(){var a=Symbol("symbol detection");return!DI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&ap&&ap<41})});var yo=f((nV,np)=>{"use strict";var CI=So();np.exports=CI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var To=f((oV,op)=>{"use strict";var VI=ft(),OI=re(),BI=yr(),_I=yo(),NI=Object;op.exports=_I?function(a){return typeof a=="symbol"}:function(a){var e=VI("Symbol");return OI(e)&&BI(e.prototype,NI(a))}});var Tr=f((uV,up)=>{"use strict";var FI=String;up.exports=function(a){try{return FI(a)}catch(e){return"Object"}}});var st=f((lV,lp)=>{"use strict";var qI=re(),UI=Tr(),HI=TypeError;lp.exports=function(a){if(qI(a))return a;throw new HI(UI(a)+" is not a function")}});var Ir=f((cV,cp)=>{"use strict";var jI=st(),QI=Ri();cp.exports=function(a,e){var t=a[e];return QI(t)?void 0:jI(t)}});var pp=f((dV,dp)=>{"use strict";var Io=Oe(),Eo=re(),xo=Be(),GI=TypeError;dp.exports=function(a,e){var t,i;if(e==="string"&&Eo(t=a.toString)&&!xo(i=Io(t,a))||Eo(t=a.valueOf)&&!xo(i=Io(t,a))||e!=="string"&&Eo(t=a.toString)&&!xo(i=Io(t,a)))return i;throw new GI("Can't convert object to primitive value")}});var ze=f((pV,hp)=>{"use strict";hp.exports=!0});var bp=f((hV,fp)=>{"use strict";var mp=se(),WI=Object.defineProperty;fp.exports=function(a,e){try{WI(mp,a,{value:e,configurable:!0,writable:!0})}catch(t){mp[a]=e}return e}});var Er=f((mV,Sp)=>{"use strict";var YI=ze(),zI=se(),KI=bp(),gp="__core-js_shared__",vp=Sp.exports=zI[gp]||KI(gp,{});(vp.versions||(vp.versions=[])).push({version:"3.38.0",mode:YI?"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 Po=f((fV,Tp)=>{"use strict";var yp=Er();Tp.exports=function(a,e){return yp[a]||(yp[a]=e||{})}});var $i=f((bV,Ip)=>{"use strict";var XI=Mt(),JI=Object;Ip.exports=function(a){return JI(XI(a))}});var Ke=f((gV,Ep)=>{"use strict";var ZI=ce(),eE=$i(),tE=ZI({}.hasOwnProperty);Ep.exports=Object.hasOwn||function(e,t){return tE(eE(e),t)}});var wo=f((vV,xp)=>{"use strict";var iE=ce(),rE=0,aE=Math.random(),sE=iE(1 .toString);xp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+sE(++rE+aE,36)}});var be=f((SV,wp)=>{"use strict";var nE=se(),oE=Po(),Pp=Ke(),uE=wo(),lE=So(),cE=yo(),Mi=nE.Symbol,Ao=oE("wks"),dE=cE?Mi.for||Mi:Mi&&Mi.withoutSetter||uE;wp.exports=function(a){return Pp(Ao,a)||(Ao[a]=lE&&Pp(Mi,a)?Mi[a]:dE("Symbol."+a)),Ao[a]}});var Lp=f((yV,Rp)=>{"use strict";var pE=Oe(),Ap=Be(),kp=To(),hE=Ir(),mE=pp(),fE=be(),bE=TypeError,gE=fE("toPrimitive");Rp.exports=function(a,e){if(!Ap(a)||kp(a))return a;var t=hE(a,gE),i;if(t){if(e===void 0&&(e="default"),i=pE(t,a,e),!Ap(i)||kp(i))return i;throw new bE("Can't convert object to primitive value")}return e===void 0&&(e="number"),mE(a,e)}});var ko=f((TV,$p)=>{"use strict";var vE=Lp(),SE=To();$p.exports=function(a){var e=vE(a,"string");return SE(e)?e:e+""}});var Ss=f((IV,Dp)=>{"use strict";var yE=se(),Mp=Be(),Ro=yE.document,TE=Mp(Ro)&&Mp(Ro.createElement);Dp.exports=function(a){return TE?Ro.createElement(a):{}}});var Lo=f((EV,Cp)=>{"use strict";var IE=Ve(),EE=fe(),xE=Ss();Cp.exports=!IE&&!EE(function(){return Object.defineProperty(xE("div"),"a",{get:function(){return 7}}).a!==7})});var Bp=f(Op=>{"use strict";var PE=Ve(),wE=Oe(),AE=ho(),kE=Sr(),RE=ri(),LE=ko(),$E=Ke(),ME=Lo(),Vp=Object.getOwnPropertyDescriptor;Op.f=PE?Vp:function(e,t){if(e=RE(e),t=LE(t),ME)try{return Vp(e,t)}catch(i){}if($E(e,t))return kE(!wE(AE.f,e,t),e[t])}});var $o=f((PV,_p)=>{"use strict";var DE=fe(),CE=re(),VE=/#|\.prototype\./,xr=function(a,e){var t=BE[OE(a)];return t===NE?!0:t===_E?!1:CE(e)?DE(e):!!e},OE=xr.normalize=function(a){return String(a).replace(VE,".").toLowerCase()},BE=xr.data={},_E=xr.NATIVE="N",NE=xr.POLYFILL="P";_p.exports=xr});var Di=f((wV,Fp)=>{"use strict";var Np=co(),FE=st(),qE=vr(),UE=Np(Np.bind);Fp.exports=function(a,e){return FE(a),e===void 0?a:qE?UE(a,e):function(){return a.apply(e,arguments)}}});var Mo=f((AV,qp)=>{"use strict";var HE=Ve(),jE=fe();qp.exports=HE&&jE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=f((kV,Up)=>{"use strict";var QE=Be(),GE=String,WE=TypeError;Up.exports=function(a){if(QE(a))return a;throw new WE(GE(a)+" is not an object")}});var si=f(jp=>{"use strict";var YE=Ve(),zE=Lo(),KE=Mo(),ys=nt(),Hp=ko(),XE=TypeError,Do=Object.defineProperty,JE=Object.getOwnPropertyDescriptor,Co="enumerable",Vo="configurable",Oo="writable";jp.f=YE?KE?function(e,t,i){if(ys(e),t=Hp(t),ys(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Oo in i&&!i[Oo]){var r=JE(e,t);r&&r[Oo]&&(e[t]=i.value,i={configurable:Vo in i?i[Vo]:r[Vo],enumerable:Co in i?i[Co]:r[Co],writable:!1})}return Do(e,t,i)}:Do:function(e,t,i){if(ys(e),t=Hp(t),ys(i),zE)try{return Do(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new XE("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ci=f((LV,Qp)=>{"use strict";var ZE=Ve(),ex=si(),tx=Sr();Qp.exports=ZE?function(a,e,t){return ex.f(a,e,tx(1,t))}:function(a,e,t){return a[e]=t,a}});var ue=f(($V,Wp)=>{"use strict";var Pr=se(),ix=uo(),rx=co(),ax=re(),sx=Bp().f,nx=$o(),Vi=Li(),ox=Di(),Oi=Ci(),Gp=Ke();Er();var ux=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return ix(a,this,arguments)};return e.prototype=a.prototype,e};Wp.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Pr:r?Pr[t]:Pr[t]&&Pr[t].prototype,o=i?Vi:Vi[t]||Oi(Vi,t,{})[t],u=o.prototype,l,c,d,h,p,m,b,g,v;for(h in e)l=nx(i?h:t+(r?".":"#")+h,a.forced),c=!l&&n&&Gp(n,h),m=o[h],c&&(a.dontCallGetSet?(v=sx(n,h),b=v&&v.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?g=ox(p,Pr):a.wrap&&c?g=ux(p):s&&ax(p)?g=rx(p):g=p,(a.sham||p&&p.sham||m&&m.sham)&&Oi(g,"sham",!0),Oi(o,h,g),s&&(d=t+"Prototype",Gp(Vi,d)||Oi(Vi,d,{}),Oi(Vi[d],h,p),a.real&&u&&(l||!u[h])&&Oi(u,h,p)))}});var zp=f((MV,Yp)=>{"use strict";var lx=Math.ceil,cx=Math.floor;Yp.exports=Math.trunc||function(e){var t=+e;return(t>0?cx:lx)(t)}});var wr=f((DV,Kp)=>{"use strict";var dx=zp();Kp.exports=function(a){var e=+a;return e!==e||e===0?0:dx(e)}});var Jp=f((CV,Xp)=>{"use strict";var px=wr(),hx=Math.max,mx=Math.min;Xp.exports=function(a,e){var t=px(a);return t<0?hx(t+e,0):mx(t,e)}});var Bo=f((VV,Zp)=>{"use strict";var fx=wr(),bx=Math.min;Zp.exports=function(a){var e=fx(a);return e>0?bx(e,9007199254740991):0}});var Bi=f((OV,eh)=>{"use strict";var gx=Bo();eh.exports=function(a){return gx(a.length)}});var _o=f((BV,ih)=>{"use strict";var vx=ri(),Sx=Jp(),yx=Bi(),th=function(a){return function(e,t,i){var r=vx(e),s=yx(r);if(s===0)return!a&&-1;var n=Sx(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};ih.exports={includes:th(!0),indexOf:th(!1)}});var Ar=f((_V,rh)=>{"use strict";rh.exports=function(){}});var ah=f(()=>{"use strict";var Tx=ue(),Ix=_o().includes,Ex=fe(),xx=Ar(),Px=Ex(function(){return!Array(1).includes()});Tx({target:"Array",proto:!0,forced:Px},{includes:function(e){return Ix(this,e,arguments.length>1?arguments[1]:void 0)}});xx("includes")});var Dt=f((qV,sh)=>{"use strict";var wx=ft();sh.exports=wx});var oh=f((UV,nh)=>{"use strict";ah();var Ax=Dt();nh.exports=Ax("Array","includes")});var lh=f((HV,uh)=>{"use strict";var kx=oh();uh.exports=kx});var qe=f((jV,ch)=>{"use strict";var Rx=lh();ch.exports=Rx});var Es=f((iO,vh)=>{"use strict";var Bx=Po(),_x=wo(),gh=Bx("keys");vh.exports=function(a){return gh[a]||(gh[a]=_x(a))}});var yh=f((rO,Sh)=>{"use strict";var Nx=fe();Sh.exports=!Nx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var xs=f((aO,Ih)=>{"use strict";var Fx=Ke(),qx=re(),Ux=$i(),Hx=Es(),jx=yh(),Th=Hx("IE_PROTO"),qo=Object,Qx=qo.prototype;Ih.exports=jx?qo.getPrototypeOf:function(a){var e=Ux(a);if(Fx(e,Th))return e[Th];var t=e.constructor;return qx(t)&&e instanceof t?t.prototype:e instanceof qo?Qx:null}});var Ps=f((sO,Eh)=>{"use strict";Eh.exports={}});var wh=f((nO,Ph)=>{"use strict";var Gx=ce(),Uo=Ke(),Wx=ri(),Yx=_o().indexOf,zx=Ps(),xh=Gx([].push);Ph.exports=function(a,e){var t=Wx(a),i=0,r=[],s;for(s in t)!Uo(zx,s)&&Uo(t,s)&&xh(r,s);for(;e.length>i;)Uo(t,s=e[i++])&&(~Yx(r,s)||xh(r,s));return r}});var Ho=f((oO,Ah)=>{"use strict";Ah.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var jo=f((uO,kh)=>{"use strict";var Kx=wh(),Xx=Ho();kh.exports=Object.keys||function(e){return Kx(e,Xx)}});var Qo=f((lO,Dh)=>{"use strict";var Lh=Ve(),Jx=fe(),$h=ce(),Zx=xs(),eP=jo(),tP=ri(),iP=ho().f,Mh=$h(iP),rP=$h([].push),aP=Lh&&Jx(function(){var a=Object.create(null);return a[2]=2,!Mh(a,2)}),Rh=function(a){return function(e){for(var t=tP(e),i=eP(t),r=aP&&Zx(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!Lh||(r?u in t:Mh(t,u)))&&rP(o,a?[u,t[u]]:t[u]);return o}};Dh.exports={entries:Rh(!0),values:Rh(!1)}});var Ch=f(()=>{"use strict";var sP=ue(),nP=Qo().entries;sP({target:"Object",stat:!0},{entries:function(e){return nP(e)}})});var Oh=f((pO,Vh)=>{"use strict";Ch();var oP=Li();Vh.exports=oP.Object.entries});var _h=f((hO,Bh)=>{"use strict";var uP=Oh();Bh.exports=uP});var _i=f((mO,Nh)=>{"use strict";var lP=_h();Nh.exports=lP});var ni=f((fO,Fh)=>{"use strict";Fh.exports={}});var Hh=f((bO,Uh)=>{"use strict";var cP=se(),dP=re(),qh=cP.WeakMap;Uh.exports=dP(qh)&&/native code/.test(String(qh))});var zo=f((gO,Gh)=>{"use strict";var pP=Hh(),Qh=se(),hP=Be(),mP=Ci(),Go=Ke(),Wo=Er(),fP=Es(),bP=Ps(),jh="Object already initialized",Yo=Qh.TypeError,gP=Qh.WeakMap,ws,kr,As,vP=function(a){return As(a)?kr(a):ws(a,{})},SP=function(a){return function(e){var t;if(!hP(e)||(t=kr(e)).type!==a)throw new Yo("Incompatible receiver, "+a+" required");return t}};pP||Wo.state?(Xe=Wo.state||(Wo.state=new gP),Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,ws=function(a,e){if(Xe.has(a))throw new Yo(jh);return e.facade=a,Xe.set(a,e),e},kr=function(a){return Xe.get(a)||{}},As=function(a){return Xe.has(a)}):(oi=fP("state"),bP[oi]=!0,ws=function(a,e){if(Go(a,oi))throw new Yo(jh);return e.facade=a,mP(a,oi,e),e},kr=function(a){return Go(a,oi)?a[oi]:{}},As=function(a){return Go(a,oi)});var Xe,oi;Gh.exports={set:ws,get:kr,has:As,enforce:vP,getterFor:SP}});var Jo=f((vO,Yh)=>{"use strict";var Ko=Ve(),yP=Ke(),Wh=Function.prototype,TP=Ko&&Object.getOwnPropertyDescriptor,Xo=yP(Wh,"name"),IP=Xo&&function(){}.name==="something",EP=Xo&&(!Ko||Ko&&TP(Wh,"name").configurable);Yh.exports={EXISTS:Xo,PROPER:IP,CONFIGURABLE:EP}});var Kh=f(zh=>{"use strict";var xP=Ve(),PP=Mo(),wP=si(),AP=nt(),kP=ri(),RP=jo();zh.f=xP&&!PP?Object.defineProperties:function(e,t){AP(e);for(var i=kP(t),r=RP(t),s=r.length,n=0,o;s>n;)wP.f(e,o=r[n++],i[o]);return e}});var Zo=f((yO,Xh)=>{"use strict";var LP=ft();Xh.exports=LP("document","documentElement")});var ru=f((TO,am)=>{"use strict";var $P=nt(),MP=Kh(),Jh=Ho(),DP=Ps(),CP=Zo(),VP=Ss(),OP=Es(),Zh=">",em="<",tu="prototype",iu="script",im=OP("IE_PROTO"),eu=function(){},rm=function(a){return em+iu+Zh+a+em+"/"+iu+Zh},tm=function(a){a.write(rm("")),a.close();var e=a.parentWindow.Object;return a=null,e},BP=function(){var a=VP("iframe"),e="java"+iu+":",t;return a.style.display="none",CP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(rm("document.F=Object")),t.close(),t.F},ks,Rs=function(){try{ks=new ActiveXObject("htmlfile")}catch(e){}Rs=typeof document!="undefined"?document.domain&&ks?tm(ks):BP():tm(ks);for(var a=Jh.length;a--;)delete Rs[tu][Jh[a]];return Rs()};DP[im]=!0;am.exports=Object.create||function(e,t){var i;return e!==null?(eu[tu]=$P(e),i=new eu,eu[tu]=null,i[im]=e):i=Rs(),t===void 0?i:MP.f(i,t)}});var Ni=f((IO,sm)=>{"use strict";var _P=Ci();sm.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:_P(a,e,t),a}});var ou=f((EO,um)=>{"use strict";var NP=fe(),FP=re(),qP=Be(),UP=ru(),nm=xs(),HP=Ni(),jP=be(),QP=ze(),nu=jP("iterator"),om=!1,bt,au,su;[].keys&&(su=[].keys(),"next"in su?(au=nm(nm(su)),au!==Object.prototype&&(bt=au)):om=!0);var GP=!qP(bt)||NP(function(){var a={};return bt[nu].call(a)!==a});GP?bt={}:QP&&(bt=UP(bt));FP(bt[nu])||HP(bt,nu,function(){return this});um.exports={IteratorPrototype:bt,BUGGY_SAFARI_ITERATORS:om}});var Ls=f((xO,cm)=>{"use strict";var WP=be(),YP=WP("toStringTag"),lm={};lm[YP]="z";cm.exports=String(lm)==="[object z]"});var Rr=f((PO,dm)=>{"use strict";var zP=Ls(),KP=re(),$s=ii(),XP=be(),JP=XP("toStringTag"),ZP=Object,ew=$s(function(){return arguments}())==="Arguments",tw=function(a,e){try{return a[e]}catch(t){}};dm.exports=zP?$s:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=tw(e=ZP(a),JP))=="string"?t:ew?$s(e):(i=$s(e))==="Object"&&KP(e.callee)?"Arguments":i}});var hm=f((wO,pm)=>{"use strict";var iw=Ls(),rw=Rr();pm.exports=iw?{}.toString:function(){return"[object "+rw(this)+"]"}});var Lr=f((AO,fm)=>{"use strict";var aw=Ls(),sw=si().f,nw=Ci(),ow=Ke(),uw=hm(),lw=be(),mm=lw("toStringTag");fm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(ow(r,mm)||sw(r,mm,{configurable:!0,value:e}),i&&!aw&&nw(r,"toString",uw))}});var gm=f((kO,bm)=>{"use strict";var cw=ou().IteratorPrototype,dw=ru(),pw=Sr(),hw=Lr(),mw=ni(),fw=function(){return this};bm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=dw(cw,{next:pw(+!i,t)}),hw(a,r,!1,!0),mw[r]=fw,a}});var Sm=f((RO,vm)=>{"use strict";var bw=ce(),gw=st();vm.exports=function(a,e,t){try{return bw(gw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Tm=f((LO,ym)=>{"use strict";var vw=Be();ym.exports=function(a){return vw(a)||a===null}});var Em=f(($O,Im)=>{"use strict";var Sw=Tm(),yw=String,Tw=TypeError;Im.exports=function(a){if(Sw(a))return a;throw new Tw("Can't set "+yw(a)+" as a prototype")}});var uu=f((MO,xm)=>{"use strict";var Iw=Sm(),Ew=Be(),xw=Mt(),Pw=Em();xm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Iw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return xw(r),Pw(s),Ew(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Vm=f((DO,Cm)=>{"use strict";var ww=ue(),Aw=Oe(),Ms=ze(),Mm=Jo(),kw=re(),Rw=gm(),Pm=xs(),wm=uu(),Lw=Lr(),$w=Ci(),lu=Ni(),Mw=be(),Am=ni(),Dm=ou(),Dw=Mm.PROPER,Cw=Mm.CONFIGURABLE,km=Dm.IteratorPrototype,Ds=Dm.BUGGY_SAFARI_ITERATORS,$r=Mw("iterator"),Rm="keys",Mr="values",Lm="entries",$m=function(){return this};Cm.exports=function(a,e,t,i,r,s,n){Rw(t,e,i);var o=function(v){if(v===r&&h)return h;if(!Ds&&v&&v in c)return c[v];switch(v){case Rm:return function(){return new t(this,v)};case Mr:return function(){return new t(this,v)};case Lm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[$r]||c["@@iterator"]||r&&c[r],h=!Ds&&d||o(r),p=e==="Array"&&c.entries||d,m,b,g;if(p&&(m=Pm(p.call(new a)),m!==Object.prototype&&m.next&&(!Ms&&Pm(m)!==km&&(wm?wm(m,km):kw(m[$r])||lu(m,$r,$m)),Lw(m,u,!0,!0),Ms&&(Am[u]=$m))),Dw&&r===Mr&&d&&d.name!==Mr&&(!Ms&&Cw?$w(c,"name",Mr):(l=!0,h=function(){return Aw(d,this)})),r)if(b={values:o(Mr),keys:s?h:o(Rm),entries:o(Lm)},n)for(g in b)(Ds||l||!(g in c))&&lu(c,g,b[g]);else ww({target:e,proto:!0,forced:Ds||l},b);return(!Ms||n)&&c[$r]!==h&&lu(c,$r,h,{name:r}),Am[e]=h,b}});var Bm=f((CO,Om)=>{"use strict";Om.exports=function(a,e){return{value:a,done:e}}});var du=f((VO,Um)=>{"use strict";var Vw=ri(),cu=Ar(),_m=ni(),Fm=zo(),Ow=si().f,Bw=Vm(),Cs=Bm(),_w=ze(),Nw=Ve(),qm="Array Iterator",Fw=Fm.set,qw=Fm.getterFor(qm);Um.exports=Bw(Array,"Array",function(a,e){Fw(this,{type:qm,target:Vw(a),index:0,kind:e})},function(){var a=qw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Cs(void 0,!0);switch(a.kind){case"keys":return Cs(t,!1);case"values":return Cs(e[t],!1)}return Cs([t,e[t]],!1)},"values");var Nm=_m.Arguments=_m.Array;cu("keys");cu("values");cu("entries");if(!_w&&Nw&&Nm.name!=="values")try{Ow(Nm,"name",{value:"values"})}catch(a){}});var jm=f((OO,Hm)=>{"use strict";var Uw=be(),Hw=ni(),jw=Uw("iterator"),Qw=Array.prototype;Hm.exports=function(a){return a!==void 0&&(Hw.Array===a||Qw[jw]===a)}});var pu=f((BO,Gm)=>{"use strict";var Gw=Rr(),Qm=Ir(),Ww=Ri(),Yw=ni(),zw=be(),Kw=zw("iterator");Gm.exports=function(a){if(!Ww(a))return Qm(a,Kw)||Qm(a,"@@iterator")||Yw[Gw(a)]}});var Ym=f((_O,Wm)=>{"use strict";var Xw=Oe(),Jw=st(),Zw=nt(),eA=Tr(),tA=pu(),iA=TypeError;Wm.exports=function(a,e){var t=arguments.length<2?tA(a):e;if(Jw(t))return Zw(Xw(t,a));throw new iA(eA(a)+" is not iterable")}});var Xm=f((NO,Km)=>{"use strict";var rA=Oe(),zm=nt(),aA=Ir();Km.exports=function(a,e,t){var i,r;zm(a);try{if(i=aA(a,"return"),!i){if(e==="throw")throw t;return t}i=rA(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return zm(i),t}});var Os=f((FO,tf)=>{"use strict";var sA=Di(),nA=Oe(),oA=nt(),uA=Tr(),lA=jm(),cA=Bi(),Jm=yr(),dA=Ym(),pA=pu(),Zm=Xm(),hA=TypeError,Vs=function(a,e){this.stopped=a,this.result=e},ef=Vs.prototype;tf.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=sA(e,i),l,c,d,h,p,m,b,g=function(S){return l&&Zm(l,"normal",S),new Vs(!0,S)},v=function(S){return r?(oA(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=pA(a),!c)throw new hA(uA(a)+" is not iterable");if(lA(c)){for(d=0,h=cA(a);h>d;d++)if(p=v(a[d]),p&&Jm(ef,p))return p;return new Vs(!1)}l=dA(a,c)}for(m=s?a.next:l.next;!(b=nA(m,l)).done;){try{p=v(b.value)}catch(S){Zm(l,"throw",S)}if(typeof p=="object"&&p&&Jm(ef,p))return p}return new Vs(!1)}});var af=f((qO,rf)=>{"use strict";var mA=Ve(),fA=si(),bA=Sr();rf.exports=function(a,e,t){mA?fA.f(a,e,bA(0,t)):a[e]=t}});var sf=f(()=>{"use strict";var gA=ue(),vA=Os(),SA=af();gA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return vA(e,function(i,r){SA(t,i,r)},{AS_ENTRIES:!0}),t}})});var of=f((jO,nf)=>{"use strict";du();sf();var yA=Li();nf.exports=yA.Object.fromEntries});var lf=f((QO,uf)=>{"use strict";uf.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 df=f(()=>{"use strict";du();var TA=lf(),IA=se(),EA=Lr(),cf=ni();for(Bs in TA)EA(IA[Bs],Bs),cf[Bs]=cf.Array;var Bs});var hf=f((YO,pf)=>{"use strict";var xA=of();df();pf.exports=xA});var hu=f((zO,mf)=>{"use strict";var PA=hf();mf.exports=PA});var ff=f(()=>{"use strict"});var mu=f((JO,bf)=>{"use strict";var Dr=se(),wA=ai(),AA=ii(),_s=function(a){return wA.slice(0,a.length)===a};bf.exports=function(){return _s("Bun/")?"BUN":_s("Cloudflare-Workers")?"CLOUDFLARE":_s("Deno/")?"DENO":_s("Node.js/")?"NODE":Dr.Bun&&typeof Bun.version=="string"?"BUN":Dr.Deno&&typeof Deno.version=="object"?"DENO":AA(Dr.process)==="process"?"NODE":Dr.window&&Dr.document?"BROWSER":"REST"}()});var Ns=f((ZO,gf)=>{"use strict";var kA=mu();gf.exports=kA==="NODE"});var Sf=f((eB,vf)=>{"use strict";var RA=si();vf.exports=function(a,e,t){return RA.f(a,e,t)}});var If=f((tB,Tf)=>{"use strict";var LA=ft(),$A=Sf(),MA=be(),DA=Ve(),yf=MA("species");Tf.exports=function(a){var e=LA(a);DA&&e&&!e[yf]&&$A(e,yf,{configurable:!0,get:function(){return this}})}});var xf=f((iB,Ef)=>{"use strict";var CA=yr(),VA=TypeError;Ef.exports=function(a,e){if(CA(e,a))return a;throw new VA("Incorrect invocation")}});var bu=f((rB,Pf)=>{"use strict";var OA=ce(),BA=re(),fu=Er(),_A=OA(Function.toString);BA(fu.inspectSource)||(fu.inspectSource=function(a){return _A(a)});Pf.exports=fu.inspectSource});var vu=f((aB,Lf)=>{"use strict";var NA=ce(),FA=fe(),wf=re(),qA=Rr(),UA=ft(),HA=bu(),Af=function(){},kf=UA("Reflect","construct"),gu=/^\s*(?:class|function)\b/,jA=NA(gu.exec),QA=!gu.test(Af),Cr=function(e){if(!wf(e))return!1;try{return kf(Af,[],e),!0}catch(t){return!1}},Rf=function(e){if(!wf(e))return!1;switch(qA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return QA||!!jA(gu,HA(e))}catch(t){return!0}};Rf.sham=!0;Lf.exports=!kf||FA(function(){var a;return Cr(Cr.call)||!Cr(Object)||!Cr(function(){a=!0})||a})?Rf:Cr});var Mf=f((sB,$f)=>{"use strict";var GA=vu(),WA=Tr(),YA=TypeError;$f.exports=function(a){if(GA(a))return a;throw new YA(WA(a)+" is not a constructor")}});var Su=f((nB,Cf)=>{"use strict";var Df=nt(),zA=Mf(),KA=Ri(),XA=be(),JA=XA("species");Cf.exports=function(a,e){var t=Df(a).constructor,i;return t===void 0||KA(i=Df(t)[JA])?e:zA(i)}});var Of=f((oB,Vf)=>{"use strict";var ZA=ce();Vf.exports=ZA([].slice)});var _f=f((uB,Bf)=>{"use strict";var ek=TypeError;Bf.exports=function(a,e){if(a<e)throw new ek("Not enough arguments");return a}});var yu=f((lB,Nf)=>{"use strict";var tk=ai();Nf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(tk)});var Ru=f((cB,Yf)=>{"use strict";var _e=se(),ik=uo(),rk=Di(),Ff=re(),ak=Ke(),Wf=fe(),qf=Zo(),sk=Of(),Uf=Ss(),nk=_f(),ok=yu(),uk=Ns(),wu=_e.setImmediate,Au=_e.clearImmediate,lk=_e.process,Tu=_e.Dispatch,ck=_e.Function,Hf=_e.MessageChannel,dk=_e.String,Iu=0,Vr={},jf="onreadystatechange",Or,ui,Eu,xu;Wf(function(){Or=_e.location});var ku=function(a){if(ak(Vr,a)){var e=Vr[a];delete Vr[a],e()}},Pu=function(a){return function(){ku(a)}},Qf=function(a){ku(a.data)},Gf=function(a){_e.postMessage(dk(a),Or.protocol+"//"+Or.host)};(!wu||!Au)&&(wu=function(e){nk(arguments.length,1);var t=Ff(e)?e:ck(e),i=sk(arguments,1);return Vr[++Iu]=function(){ik(t,void 0,i)},ui(Iu),Iu},Au=function(e){delete Vr[e]},uk?ui=function(a){lk.nextTick(Pu(a))}:Tu&&Tu.now?ui=function(a){Tu.now(Pu(a))}:Hf&&!ok?(Eu=new Hf,xu=Eu.port2,Eu.port1.onmessage=Qf,ui=rk(xu.postMessage,xu)):_e.addEventListener&&Ff(_e.postMessage)&&!_e.importScripts&&Or&&Or.protocol!=="file:"&&!Wf(Gf)?(ui=Gf,_e.addEventListener("message",Qf,!1)):jf in Uf("script")?ui=function(a){qf.appendChild(Uf("script"))[jf]=function(){qf.removeChild(this),ku(a)}}:ui=function(a){setTimeout(Pu(a),0)});Yf.exports={set:wu,clear:Au}});var Xf=f((dB,Kf)=>{"use strict";var zf=se(),pk=Ve(),hk=Object.getOwnPropertyDescriptor;Kf.exports=function(a){if(!pk)return zf[a];var e=hk(zf,a);return e&&e.value}});var Lu=f((pB,Zf)=>{"use strict";var Jf=function(){this.head=null,this.tail=null};Jf.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}}};Zf.exports=Jf});var tb=f((hB,eb)=>{"use strict";var mk=ai();eb.exports=/ipad|iphone|ipod/i.test(mk)&&typeof Pebble!="undefined"});var rb=f((mB,ib)=>{"use strict";var fk=ai();ib.exports=/web0s(?!.*chrome)/i.test(fk)});var cb=f((fB,lb)=>{"use strict";var qi=se(),bk=Xf(),ab=Di(),$u=Ru().set,gk=Lu(),vk=yu(),Sk=tb(),yk=rb(),Mu=Ns(),sb=qi.MutationObserver||qi.WebKitMutationObserver,nb=qi.document,ob=qi.process,Fs=qi.Promise,Vu=bk("queueMicrotask"),Fi,Du,Cu,qs,ub;Vu||(Br=new gk,_r=function(){var a,e;for(Mu&&(a=ob.domain)&&a.exit();e=Br.get();)try{e()}catch(t){throw Br.head&&Fi(),t}a&&a.enter()},!vk&&!Mu&&!yk&&sb&&nb?(Du=!0,Cu=nb.createTextNode(""),new sb(_r).observe(Cu,{characterData:!0}),Fi=function(){Cu.data=Du=!Du}):!Sk&&Fs&&Fs.resolve?(qs=Fs.resolve(void 0),qs.constructor=Fs,ub=ab(qs.then,qs),Fi=function(){ub(_r)}):Mu?Fi=function(){ob.nextTick(_r)}:($u=ab($u,qi),Fi=function(){$u(_r)}),Vu=function(a){Br.head||Fi(),Br.add(a)});var Br,_r;lb.exports=Vu});var pb=f((bB,db)=>{"use strict";db.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Us=f((gB,hb)=>{"use strict";hb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var li=f((vB,mb)=>{"use strict";var Tk=se();mb.exports=Tk.Promise});var Ui=f((SB,vb)=>{"use strict";var Ik=se(),Nr=li(),Ek=re(),xk=$o(),Pk=bu(),wk=be(),fb=mu(),Ak=ze(),Ou=vo(),bb=Nr&&Nr.prototype,kk=wk("species"),Bu=!1,gb=Ek(Ik.PromiseRejectionEvent),Rk=xk("Promise",function(){var a=Pk(Nr),e=a!==String(Nr);if(!e&&Ou===66||Ak&&!(bb.catch&&bb.finally))return!0;if(!Ou||Ou<51||!/native code/.test(a)){var t=new Nr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[kk]=i,Bu=t.then(function(){})instanceof i,!Bu)return!0}return!e&&(fb==="BROWSER"||fb==="DENO")&&!gb});vb.exports={CONSTRUCTOR:Rk,REJECTION_EVENT:gb,SUBCLASSING:Bu}});var Hi=f((yB,yb)=>{"use strict";var Sb=st(),Lk=TypeError,$k=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new Lk("Bad Promise constructor");e=i,t=r}),this.resolve=Sb(e),this.reject=Sb(t)};yb.exports.f=function(a){return new $k(a)}});var Nb=f(()=>{"use strict";var Mk=ue(),Dk=ze(),Gs=Ns(),Ct=se(),Wi=Oe(),Tb=Ni(),Ib=uu(),Ck=Lr(),Vk=If(),Ok=st(),Qs=re(),Bk=Be(),_k=xf(),Nk=Su(),Ab=Ru().set,Uu=cb(),Fk=pb(),qk=Us(),Uk=Lu(),kb=zo(),Ws=li(),Hu=Ui(),Rb=Hi(),Ys="Promise",Lb=Hu.CONSTRUCTOR,Hk=Hu.REJECTION_EVENT,jk=Hu.SUBCLASSING,_u=kb.getterFor(Ys),Qk=kb.set,ji=Ws&&Ws.prototype,ci=Ws,Hs=ji,$b=Ct.TypeError,Nu=Ct.document,ju=Ct.process,Fu=Rb.f,Gk=Fu,Wk=!!(Nu&&Nu.createEvent&&Ct.dispatchEvent),Mb="unhandledrejection",Yk="rejectionhandled",Eb=0,Db=1,zk=2,Qu=1,Cb=2,js,xb,Kk,Pb,Vb=function(a){var e;return Bk(a)&&Qs(e=a.then)?e:!1},Ob=function(a,e){var t=e.value,i=e.state===Db,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===Cb&&Jk(e),e.rejection=Qu),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new $b("Promise-chain cycle")):(l=Vb(u))?Wi(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},Bb=function(a,e){a.notified||(a.notified=!0,Uu(function(){for(var t=a.reactions,i;i=t.get();)Ob(i,a);a.notified=!1,e&&!a.rejection&&Xk(a)}))},_b=function(a,e,t){var i,r;Wk?(i=Nu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Ct.dispatchEvent(i)):i={promise:e,reason:t},!Hk&&(r=Ct["on"+a])?r(i):a===Mb&&Fk("Unhandled promise rejection",t)},Xk=function(a){Wi(Ab,Ct,function(){var e=a.facade,t=a.value,i=wb(a),r;if(i&&(r=qk(function(){Gs?ju.emit("unhandledRejection",t,e):_b(Mb,e,t)}),a.rejection=Gs||wb(a)?Cb:Qu,r.error))throw r.value})},wb=function(a){return a.rejection!==Qu&&!a.parent},Jk=function(a){Wi(Ab,Ct,function(){var e=a.facade;Gs?ju.emit("rejectionHandled",e):_b(Yk,e,a.value)})},Qi=function(a,e,t){return function(i){a(e,i,t)}},Gi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=zk,Bb(a,!0))},qu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new $b("Promise can't be resolved itself");var i=Vb(e);i?Uu(function(){var r={done:!1};try{Wi(i,e,Qi(qu,r,a),Qi(Gi,r,a))}catch(s){Gi(r,s,a)}}):(a.value=e,a.state=Db,Bb(a,!1))}catch(r){Gi({done:!1},r,a)}}};if(Lb&&(ci=function(e){_k(this,Hs),Ok(e),Wi(js,this);var t=_u(this);try{e(Qi(qu,t),Qi(Gi,t))}catch(i){Gi(t,i)}},Hs=ci.prototype,js=function(e){Qk(this,{type:Ys,done:!1,notified:!1,parent:!1,reactions:new Uk,rejection:!1,state:Eb,value:void 0})},js.prototype=Tb(Hs,"then",function(e,t){var i=_u(this),r=Fu(Nk(this,ci));return i.parent=!0,r.ok=Qs(e)?e:!0,r.fail=Qs(t)&&t,r.domain=Gs?ju.domain:void 0,i.state===Eb?i.reactions.add(r):Uu(function(){Ob(r,i)}),r.promise}),xb=function(){var a=new js,e=_u(a);this.promise=a,this.resolve=Qi(qu,e),this.reject=Qi(Gi,e)},Rb.f=Fu=function(a){return a===ci||a===Kk?new xb(a):Gk(a)},!Dk&&Qs(Ws)&&ji!==Object.prototype)){Pb=ji.then,jk||Tb(ji,"then",function(e,t){var i=this;return new ci(function(r,s){Wi(Pb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete ji.constructor}catch(a){}Ib&&Ib(ji,Hs)}Mk({global:!0,constructor:!0,wrap:!0,forced:Lb},{Promise:ci});Ck(ci,Ys,!1,!0);Vk(Ys)});var jb=f((EB,Hb)=>{"use strict";var Zk=be(),qb=Zk("iterator"),Ub=!1;try{Fb=0,Gu={next:function(){return{done:!!Fb++}},return:function(){Ub=!0}},Gu[qb]=function(){return this},Array.from(Gu,function(){throw 2})}catch(a){}var Fb,Gu;Hb.exports=function(a,e){try{if(!e&&!Ub)return!1}catch(r){return!1}var t=!1;try{var i={};i[qb]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Wu=f((xB,Qb)=>{"use strict";var eR=li(),tR=jb(),iR=Ui().CONSTRUCTOR;Qb.exports=iR||!tR(function(a){eR.all(a).then(void 0,function(){})})});var Gb=f(()=>{"use strict";var rR=ue(),aR=Oe(),sR=st(),nR=Hi(),oR=Us(),uR=Os(),lR=Wu();rR({target:"Promise",stat:!0,forced:lR},{all:function(e){var t=this,i=nR.f(t),r=i.resolve,s=i.reject,n=oR(function(){var o=sR(t.resolve),u=[],l=0,c=1;uR(e,function(d){var h=l++,p=!1;c++,aR(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var Yb=f(()=>{"use strict";var cR=ue(),dR=ze(),pR=Ui().CONSTRUCTOR,zu=li(),hR=ft(),mR=re(),fR=Ni(),Wb=zu&&zu.prototype;cR({target:"Promise",proto:!0,forced:pR,real:!0},{catch:function(a){return this.then(void 0,a)}});!dR&&mR(zu)&&(Yu=hR("Promise").prototype.catch,Wb.catch!==Yu&&fR(Wb,"catch",Yu,{unsafe:!0}));var Yu});var zb=f(()=>{"use strict";var bR=ue(),gR=Oe(),vR=st(),SR=Hi(),yR=Us(),TR=Os(),IR=Wu();bR({target:"Promise",stat:!0,forced:IR},{race:function(e){var t=this,i=SR.f(t),r=i.reject,s=yR(function(){var n=vR(t.resolve);TR(e,function(o){gR(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Kb=f(()=>{"use strict";var ER=ue(),xR=Hi(),PR=Ui().CONSTRUCTOR;ER({target:"Promise",stat:!0,forced:PR},{reject:function(e){var t=xR.f(this),i=t.reject;return i(e),t.promise}})});var Ku=f((DB,Xb)=>{"use strict";var wR=nt(),AR=Be(),kR=Hi();Xb.exports=function(a,e){if(wR(a),AR(e)&&e.constructor===a)return e;var t=kR.f(a),i=t.resolve;return i(e),t.promise}});var eg=f(()=>{"use strict";var RR=ue(),LR=ft(),Jb=ze(),$R=li(),Zb=Ui().CONSTRUCTOR,MR=Ku(),DR=LR("Promise"),CR=Jb&&!Zb;RR({target:"Promise",stat:!0,forced:Jb||Zb},{resolve:function(e){return MR(CR&&this===DR?$R:this,e)}})});var tg=f(()=>{"use strict";Nb();Gb();Yb();zb();Kb();eg()});var sg=f(()=>{"use strict";var VR=ue(),OR=ze(),zs=li(),BR=fe(),rg=ft(),ag=re(),_R=Su(),ig=Ku(),NR=Ni(),Ju=zs&&zs.prototype,FR=!!zs&&BR(function(){Ju.finally.call({then:function(){}},function(){})});VR({target:"Promise",proto:!0,real:!0,forced:FR},{finally:function(a){var e=_R(this,rg("Promise")),t=ag(a);return this.then(t?function(i){return ig(e,a()).then(function(){return i})}:a,t?function(i){return ig(e,a()).then(function(){throw i})}:a)}});!OR&&ag(zs)&&(Xu=rg("Promise").prototype.finally,Ju.finally!==Xu&&NR(Ju,"finally",Xu,{unsafe:!0}));var Xu});var og=f((FB,ng)=>{"use strict";ff();tg();sg();var qR=Dt();ng.exports=qR("Promise","finally")});var lg=f((qB,ug)=>{"use strict";var UR=og();ug.exports=UR});var Ks=f((UB,cg)=>{"use strict";var HR=lg();cg.exports=HR});var Eg=f(()=>{"use strict";var rL=ue(),aL=Qo().values;rL({target:"Object",stat:!0},{values:function(e){return aL(e)}})});var Pg=f((w_,xg)=>{"use strict";Eg();var sL=Li();xg.exports=sL.Object.values});var Ag=f((A_,wg)=>{"use strict";var nL=Pg();wg.exports=nL});var zi=f((k_,kg)=>{"use strict";var oL=Ag();kg.exports=oL});var Qg=f(()=>{"use strict";var $L=ue(),ML=$i(),DL=Bi(),CL=wr(),VL=Ar();$L({target:"Array",proto:!0},{at:function(e){var t=ML(this),i=DL(t),r=CL(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});VL("at")});var Wg=f((FN,Gg)=>{"use strict";Qg();var OL=Dt();Gg.exports=OL("Array","at")});var zg=f((qN,Yg)=>{"use strict";var BL=Wg();Yg.exports=BL});var Nt=f((UN,Kg)=>{"use strict";var _L=zg();Kg.exports=_L});var xl=f((Lq,$v)=>{"use strict";var T$=ii();$v.exports=Array.isArray||function(e){return T$(e)==="Array"}});var Dv=f(($q,Mv)=>{"use strict";var I$=TypeError,E$=9007199254740991;Mv.exports=function(a){if(a>E$)throw I$("Maximum allowed index exceeded");return a}});var Ov=f((Mq,Vv)=>{"use strict";var x$=xl(),P$=Bi(),w$=Dv(),A$=Di(),Cv=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?A$(n,o):!1,d,h;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&x$(d)?(h=P$(d),u=Cv(a,e,d,h,u,s-1)-1):(w$(u+1),a[u]=d),u++),l++;return u};Vv.exports=Cv});var Fv=f((Dq,Nv)=>{"use strict";var Bv=xl(),k$=vu(),R$=Be(),L$=be(),$$=L$("species"),_v=Array;Nv.exports=function(a){var e;return Bv(a)&&(e=a.constructor,k$(e)&&(e===_v||Bv(e.prototype))?e=void 0:R$(e)&&(e=e[$$],e===null&&(e=void 0))),e===void 0?_v:e}});var Uv=f((Cq,qv)=>{"use strict";var M$=Fv();qv.exports=function(a,e){return new(M$(a))(e===0?0:e)}});var Hv=f(()=>{"use strict";var D$=ue(),C$=Ov(),V$=st(),O$=$i(),B$=Bi(),_$=Uv();D$({target:"Array",proto:!0},{flatMap:function(e){var t=O$(this),i=B$(t),r;return V$(e),r=_$(t,0),r.length=C$(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var jv=f(()=>{"use strict";var N$=Ar();N$("flatMap")});var Gv=f((Nq,Qv)=>{"use strict";Hv();jv();var F$=Dt();Qv.exports=F$("Array","flatMap")});var Yv=f((Fq,Wv)=>{"use strict";var q$=Gv();Wv.exports=q$});var Pl=f((qq,zv)=>{"use strict";var U$=Yv();zv.exports=U$});var ia=f((Uq,Kv)=>{"use strict";var H$=Rr(),j$=String;Kv.exports=function(a){if(H$(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return j$(a)}});var wl=f((Hq,Xv)=>{"use strict";Xv.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 eS=f((jq,Zv)=>{"use strict";var Q$=ce(),G$=Mt(),W$=ia(),kl=wl(),Jv=Q$("".replace),Y$=RegExp("^["+kl+"]+"),z$=RegExp("(^|[^"+kl+"])["+kl+"]+$"),Al=function(a){return function(e){var t=W$(G$(e));return a&1&&(t=Jv(t,Y$,"")),a&2&&(t=Jv(t,z$,"$1")),t}};Zv.exports={start:Al(1),end:Al(2),trim:Al(3)}});var aS=f((Qq,rS)=>{"use strict";var K$=Jo().PROPER,X$=fe(),tS=wl(),iS="\u200B\x85\u180E";rS.exports=function(a){return X$(function(){return!!tS[a]()||iS[a]()!==iS||K$&&tS[a].name!==a})}});var Rl=f((Gq,sS)=>{"use strict";var J$=eS().start,Z$=aS();sS.exports=Z$("trimStart")?function(){return J$(this)}:"".trimStart});var oS=f(()=>{"use strict";var eM=ue(),nS=Rl();eM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==nS},{trimLeft:nS})});var lS=f(()=>{"use strict";oS();var tM=ue(),uS=Rl();tM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==uS},{trimStart:uS})});var dS=f((Xq,cS)=>{"use strict";lS();var iM=Dt();cS.exports=iM("String","trimLeft")});var hS=f((Jq,pS)=>{"use strict";var rM=dS();pS.exports=rM});var fS=f((Zq,mS)=>{"use strict";var aM=hS();mS.exports=aM});var $S=f(()=>{"use strict"});var MS=f(()=>{"use strict"});var CS=f((OH,DS)=>{"use strict";var AM=Be(),kM=ii(),RM=be(),LM=RM("match");DS.exports=function(a){var e;return AM(a)&&((e=a[LM])!==void 0?!!e:kM(a)==="RegExp")}});var OS=f((BH,VS)=>{"use strict";var $M=nt();VS.exports=function(){var a=$M(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 NS=f((_H,_S)=>{"use strict";var MM=Oe(),DM=Ke(),CM=yr(),VM=OS(),BS=RegExp.prototype;_S.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in BS)&&!DM(a,"flags")&&CM(BS,a)?MM(VM,a):e}});var qS=f((NH,FS)=>{"use strict";var Bl=ce(),OM=$i(),BM=Math.floor,Vl=Bl("".charAt),_M=Bl("".replace),Ol=Bl("".slice),NM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,FM=/\$([$&'`]|\d{1,2})/g;FS.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=FM;return r!==void 0&&(r=OM(r),u=NM),_M(s,u,function(l,c){var d;switch(Vl(c,0)){case"$":return"$";case"&":return a;case"`":return Ol(e,0,t);case"'":return Ol(e,n);case"<":d=r[Ol(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=BM(h/10);return p===0?l:p<=o?i[p-1]===void 0?Vl(c,1):i[p-1]+Vl(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var jS=f(()=>{"use strict";var qM=ue(),UM=Oe(),Nl=ce(),US=Mt(),HM=re(),jM=Ri(),QM=CS(),tr=ia(),GM=Ir(),WM=NS(),YM=qS(),zM=be(),KM=ze(),XM=zM("replace"),JM=TypeError,_l=Nl("".indexOf),ZM=Nl("".replace),HS=Nl("".slice),eD=Math.max;qM({target:"String",proto:!0},{replaceAll:function(e,t){var i=US(this),r,s,n,o,u,l,c,d,h,p,m=0,b="";if(!jM(e)){if(r=QM(e),r&&(s=tr(US(WM(e))),!~_l(s,"g")))throw new JM("`.replaceAll` does not allow non-global regexes");if(n=GM(e,XM),n)return UM(n,e,i,t);if(KM&&r)return ZM(tr(i),e,t)}for(o=tr(i),u=tr(e),l=HM(t),l||(t=tr(t)),c=u.length,d=eD(1,c),h=_l(o,u);h!==-1;)p=l?tr(t(u,h,o)):YM(u,o,h,[],void 0,t),b+=HS(o,m,h)+p,m=h+c,h=h+d>o.length?-1:_l(o,u,h+d);return m<o.length&&(b+=HS(o,m)),b}})});var GS=f((UH,QS)=>{"use strict";$S();MS();jS();var tD=Dt();QS.exports=tD("String","replaceAll")});var YS=f((HH,WS)=>{"use strict";var iD=GS();WS.exports=iD});var KS=f((jH,zS)=>{"use strict";var rD=YS();zS.exports=rD});var JS=f((QH,XS)=>{"use strict";var aD=wr(),sD=ia(),nD=Mt(),oD=RangeError;XS.exports=function(e){var t=sD(nD(this)),i="",r=aD(e);if(r<0||r===1/0)throw new oD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var ry=f((GH,iy)=>{"use strict";var ty=ce(),uD=Bo(),ZS=ia(),lD=JS(),cD=Mt(),dD=ty(lD),pD=ty("".slice),hD=Math.ceil,ey=function(a){return function(e,t,i){var r=ZS(cD(e)),s=uD(t),n=r.length,o=i===void 0?" ":ZS(i),u,l;return s<=n||o===""?r:(u=s-n,l=dD(o,hD(u/o.length)),l.length>u&&(l=pD(l,0,u)),a?r+l:l+r)}};iy.exports={start:ey(!1),end:ey(!0)}});var sy=f((WH,ay)=>{"use strict";var mD=ai();ay.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(mD)});var ny=f(()=>{"use strict";var fD=ue(),bD=ry().start,gD=sy();fD({target:"String",proto:!0,forced:gD},{padStart:function(e){return bD(this,e,arguments.length>1?arguments[1]:void 0)}})});var uy=f((KH,oy)=>{"use strict";ny();var vD=Dt();oy.exports=vD("String","padStart")});var cy=f((XH,ly)=>{"use strict";var SD=uy();ly.exports=SD});var py=f((JH,dy)=>{"use strict";var yD=cy();dy.exports=yD});var vd="2.0.130-dev.afe0f37e.0";var Ce=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ce||{}),mt=(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))(mt||{});var fs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(fs||{}),so=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(so||{});var no=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(no||{}),bs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(bs||{});var WT=B(qe(),1);import{assertNever as bh,assertNonNullable as Lx,isNonNullable as Ts,ValueSubject as No,Subject as $x,Subscription as Mx,merge as Dx,observableFrom as Cx,fromEvent as ph,map as hh,tap as mh,filterChanged as Vx,isNullable as Fo,ErrorCategory as fh}from"@vkontakte/videoplayer-shared/es2015";var dh=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Is=class{constructor(e){this.connection$=new No(void 0);this.castState$=new No("NOT_AVAILABLE");this.errorEvent$=new $x;this.realCastState$=new No("NOT_AVAILABLE");this.subscription=new Mx;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let i=Ts((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||dh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:fh.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ts(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Fo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Fo(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),i=cast.framework.CastContext.getInstance();this.subscription.add(ph(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.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 bh(r.sessionState)}})).add(Dx(ph(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(mh(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),hh(r=>r.castState)),Cx([i.getCastState()])).pipe(Vx(),hh(Ox),mh(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=Ts(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();Lx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Fo(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(r==="CONNECTED"?Ts(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:fh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Ox=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 bh(a)}};var Ec=B(qe(),1),RT=B(_i(),1),LT=B(hu(),1);var yg=B(Ks(),1);import{assertNever as dg}from"@vkontakte/videoplayer-shared/es2015";var ge=(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 i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:dg(t)}return a},Xs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:dg(e)}};var R=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as jR,Subject as Js,merge as pg}from"@vkontakte/videoplayer-shared/es2015";var _=class{constructor(e){this.transitionStarted$=new Js;this.transitionEnded$=new Js;this.transitionUpdated$=new Js;this.forceChanged$=new Js;this.stateChangeStarted$=pg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=pg(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||jR(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as QR}from"@vkontakte/videoplayer-shared/es2015";var hg=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 QR(a)}};import{assertNever as Yi,assertNonNullable as di,debounce as mg,ErrorCategory as fg,fromEvent as pi,isNonNullable as bg,map as gg,merge as vg,observableFrom as GR,Subject as WR,Subscription as Zu,timeout as YR,getHighestQuality as zR}from"@vkontakte/videoplayer-shared/es2015";var KR=5,XR=5,JR=500,Sg=7e3,Fr=class{constructor(e){this.subscription=new Zu;this.loadMediaTimeoutSubscription=new Zu;this.videoState=new _("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yi(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:Yi(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:Yi(e)}break}default:Yi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(hg(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(vg(this.videoState.stateChangeStarted$.pipe(gg(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(gg(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new WR;e.add(r.pipe(mg(JR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(pi(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)>KR)&&r.next(o),s=o})),e.add(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.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<XR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(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:Yi(n)}}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=vg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,GR(["init"])).pipe(mg(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),R(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"),R(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"&&R(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];di(c);let d=zR(Object.keys(c));di(d);let h=c[d];di(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];di(c),i=c.url,r="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];di(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];di(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];di(c),i=ge(c.url),r="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:fg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yi(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return bg(o)&&(n.metadata.title=o),bg(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(YR(Sg).subscribe(()=>s(`timeout(${Sg})`)))});(0,yg.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:fg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Il=B(qe(),1);import{clearVideoElement as Ig}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as ZR}from"@vkontakte/videoplayer-shared/es2015";var Tg=a=>{try{a.pause(),a.playbackRate=0,ZR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as eL,Subscription as tL}from"@vkontakte/videoplayer-shared/es2015";var el=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)}},tl=window.WeakMap?new WeakMap:new el,il=window.WeakMap?new WeakMap:new Map,iL=(a,e=20)=>{let t=0;return eL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ae=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?Ig(i):(i=document.createElement("video"),a.appendChild(i)),tl.set(i,r);let s=new tL;return s.add(iL(i,e)),il.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},ke=a=>{let e=il.get(a);e==null||e.unsubscribe(),il.delete(a);let t=tl.get(a);tl.delete(a),t?Ig(a):Tg(a)};var al=B(zi(),1);import{assertNonNullable as qr,isNonNullable as ut,isNullable as cL,fromEvent as Ki,merge as Rg,observableFrom as Lg,filterChanged as $g,map as Ur,Subject as Mg,Subscription as dL,ValueSubject as pL,ErrorCategory as hL}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as rl,isNullable as uL,Subscription as lL}from"@vkontakte/videoplayer-shared/es2015";var Zs=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=uL(r),l=new lL;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(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)=>Zs(e,()=>a.loop,i=>{rl(i)&&(a.loop=i)},{onError:t}),Re=(a,e,t,i)=>Zs(e,()=>({muted:a.muted,volume:a.volume}),r=>{rl(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ue=(a,e,t,i)=>Zs(e,()=>a.playbackRate,r=>{rl(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Vt=Zs;var mL=a=>["__",a.language,a.label].join("|"),fL=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},sl=class a{constructor(e){this.available$=new Mg;this.current$=new pL(void 0);this.error$=new Mg;this.subscription=new dL;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:hL.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Vt(t.internalTextTracks,()=>(0,al.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(Ur(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Vt(t.externalTextTracks,()=>(0,al.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(Ur(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Vt(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:r})),this.subscription.add(Vt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){qr(this.video);let{textTracks:e}=this.video;this.subscription.add(Ki(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Rg(Ki(e,"addtrack"),Ki(e,"removetrack"),Lg(["init"])).pipe(Ur(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),$g((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(Rg(Ki(e,"change"),Lg(["init"])).pipe(Ur(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ur(i=>i&&this.htmlTextTrackToITextTrack(i).id),$g()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(Ki(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Ki(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;ut(t.align)&&(r.align=t.align),ut(t.position)&&(r.position=t.position),ut(t.size)&&(r.size=t.size),ut(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){qr(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:i}=e,r=e.id?e.id:mL(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){qr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(cL(e)||!fL(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){qr(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){qr(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},He=sl;var hi=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 Dg=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},nl=a=>{let e=Dg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Cg=a=>{let e=Dg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Le,map as Ot,merge as ul,filterChanged as xL,isNonNullable as Hg,Subject as PL,filter as jr,mapTo as ll,combine as wL,once as AL,throttle as kL,ErrorCategory as RL,ValueSubject as jg,Subscription as LL}from"@vkontakte/videoplayer-shared/es2015";var bL=3,Vg=(a,e,t=bL)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var en=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var Og=B(qe(),1);var Hr=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var tn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Og.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Hr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return P(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var rn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var Je=()=>window.ManagedMediaSource||window.MediaSource,an=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Bg=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},_g=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var gL=document.createElement("video"),vL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',SL='video/mp4; codecs="hev1.1.6.L93.B0"',Ng='video/webm; codecs="vp09.00.10.08"',Fg='video/webm; codecs="av01.0.00M.08"',yL='audio/mp4; codecs="mp4a.40.2"',TL='audio/webm; codecs="opus"',qg,IL=()=>P(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(C(A({},a),{video:C(A({},a.video),{contentType:Fg})})),window.navigator.mediaCapabilities.decodingInfo(C(A({},a),{video:C(A({},a.video),{contentType:Ng})}))]);qg={DASH_WEBM_AV1:e,DASH_WEBM:t}});IL().catch(a=>{console.log(gL),console.error(a)});var sn=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return qg}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,h,p,m,b,g,v,S,y,E;this._video=document.createElement("video");try{this._protocols={mms:an(),mse:Bg(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let I=!!((c=(l=Je())==null?void 0:l.isTypeSupported)!=null&&c.call(l,vL)),$=!!((h=(d=Je())==null?void 0:d.isTypeSupported)!=null&&h.call(d,SL)),V=!!((m=(p=Je())==null?void 0:p.isTypeSupported)!=null&&m.call(p,yL));this._codecs={h264:I,h265:$,vp9:!!((g=(b=Je())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Ng)),av1:!!((S=(v=Je())==null?void 0:v.isTypeSupported)!=null&&S.call(v,Fg)),aac:V,opus:!!((E=(y=Je())==null?void 0:y.isTypeSupported)!=null&&E.call(y,TL)),mpeg:(I||$)&&V},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(I){console.error(I)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Ug="audio/mpeg",nn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Ug))},this._codecs={mp3:!!((r=(i=Je())==null?void 0:i.isTypeSupported)!=null&&r.call(i,Ug))}}catch(s){console.error(s)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as EL}from"@vkontakte/videoplayer-shared/es2015";var ol=class{constructor(){this.isInited$=new EL(!1);this._displayChecker=new rn,this._deviceChecker=new tn(this._displayChecker),this._browserChecker=new en,this._videoChecker=new sn(this._deviceChecker,this._browserChecker),this._audioChecker=new nn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return P(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},q=new ol;var $e=a=>{let e=w=>Le(a,w).pipe(ll(void 0)),t=new LL,i=()=>t.unsubscribe(),s=ul(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>Le(a,w))).pipe(Ot(w=>w.type==="ended"?a.readyState<2:a.readyState<3),xL()),n=ul(Le(a,"progress"),Le(a,"timeupdate")).pipe(Ot(()=>Vg(a.buffered,a.currentTime))),o=q.browser.isSafari?wL({play:e("play").pipe(AL()),playing:e("playing")}).pipe(ll(void 0)):e("playing"),u=Le(a,"volumechange").pipe(Ot(()=>({muted:a.muted,volume:a.volume}))),l=Le(a,"ratechange").pipe(Ot(()=>a.playbackRate)),c=Le(a,"error").pipe(jr(()=>!!(a.error||a.played.length)),Ot(()=>{var H;let w=a.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:RL.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(H=a.error)!=null?H:void 0}})),d=Le(a,"timeupdate").pipe(Ot(()=>a.currentTime)),h=new PL,p=.3,m;t.add(d.subscribe(w=>{a.loop&&Hg(m)&&Hg(w)&&m>=a.duration-p&&w<=p&&h.next(m),m=w}));let b=e("pause").pipe(jr(()=>!a.error&&m!==a.duration)),g=Le(a,"enterpictureinpicture"),v=Le(a,"leavepictureinpicture"),S=new jg(Cg(a));t.add(g.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let y=new jg(nl(a)),E=Le(a,"fullscreenchange");t.add(E.pipe(Ot(()=>nl(a))).subscribe(y));let I=.1,$=1e3,V=Le(a,"timeupdate").pipe(jr(w=>a.duration-a.currentTime<I)),F=ul(V.pipe(jr(w=>!a.loop)),Le(a,"ended")).pipe(kL($),ll(void 0)),z=V.pipe(jr(w=>a.loop));return{playing$:o,pause$:b,canplay$:e("canplay"),ended$:F,looped$:h,loopExpected$:z,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:Le(a,"durationchange").pipe(Ot(()=>a.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:S,inFullscreen$:y,enterPip$:g,leavePip$:v,destroy:i}};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 Ft=B(Nt(),1),nv=B(qe(),1),ln=B(_i(),1);import{isNonNullable as Ee,isNullable as iv,now as ov,isHigher as rv,isHigherOrEqual as hl,isInvariantQuality as av,isLowerOrEqual as ml,videoSizeToQuality as qL,assertNotEmptyArray as uv,assertNonNullable as UL}from"@vkontakte/videoplayer-shared/es2015";var cl=!1,vt={},Xg=a=>{cl=a},Jg=()=>{vt={}},Zg=a=>{a(vt)},Qr=(a,e)=>{var t;cl&&(vt.meta=(t=vt.meta)!=null?t:{},vt.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var i,r;if(!cl)return;vt.series=(i=vt.series)!=null?i:{};let t=(r=vt.series[this.name])!=null?r:[];t.push([Date.now(),e]),vt.series[this.name]=t}};import{isHigher as NL,isHigherOrEqual as YN,isLower as ev,isLowerOrEqual as zN,isNonNullable as on,isNullable as FL,videoHeightToQuality as un}from"@vkontakte/videoplayer-shared/es2015";function dl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function pl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&dl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Gr({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return FL(a)||on(a.min)&&on(a.max)&&ev(a.max,a.min)||on(a.min)&&e&&NL(a.min,e)||on(a.max)&&t&&ev(a.max,t)}function tv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Gr({limits:{max:a!=null&&a.max?un(a.max):void 0,min:a!=null&&a.min?un(a.min):void 0},highestAvailableQuality:e?un(e):void 0,lowestAvailableQuality:t?un(t):void 0})}var HL=new Ie("best_bitrate"),lv=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var fl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Wr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ov()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},cv='Assertion "ABR Tracks is empty array" failed',cn=(a,e,t,i)=>{var u;let r=[...e].sort(fl(1)),s=[...t].sort(fl(1)),n=s.filter(l=>Ee(l.bitrate)&&Ee(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Ft.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Ft.default)(s,-1);return o&&(0,nv.default)(n,o)?o:n.length?(0,Ft.default)(n,-1):(0,Ft.default)(s,0)},sv=a=>"quality"in a,dv=(a,e,t,i)=>{var n;let r=Ee((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&Ee(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&ov()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=sv(o)?"video":"audio",l=sv(o)?o.quality:o.bitrate;return e({message:`
6
+ var iI=Object.create;var ro=Object.defineProperty,rI=Object.defineProperties,aI=Object.getOwnPropertyDescriptor,sI=Object.getOwnPropertyDescriptors,nI=Object.getOwnPropertyNames,hs=Object.getOwnPropertySymbols,oI=Object.getPrototypeOf,ao=Object.prototype.hasOwnProperty,gd=Object.prototype.propertyIsEnumerable;var uI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,bd=(a,e,t)=>e in a?ro(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,A=(a,e)=>{for(var t in e||(e={}))ao.call(e,t)&&bd(a,t,e[t]);if(hs)for(var t of hs(e))gd.call(e,t)&&bd(a,t,e[t]);return a},C=(a,e)=>rI(a,sI(e));var vd=(a,e)=>{var t={};for(var i in a)ao.call(a,i)&&e.indexOf(i)<0&&(t[i]=a[i]);if(a!=null&&hs)for(var i of hs(a))e.indexOf(i)<0&&gd.call(a,i)&&(t[i]=a[i]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var lI=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of nI(e))!ao.call(a,r)&&r!==t&&ro(a,r,{get:()=>e[r],enumerable:!(i=aI(e,r))||i.enumerable});return a};var B=(a,e,t)=>(t=a!=null?iI(oI(a)):{},lI(e||!a||!a.__esModule?ro(t,"default",{value:a,enumerable:!0}):t,a));var P=(a,e,t)=>new Promise((i,r)=>{var s=u=>{try{o(t.next(u))}catch(l){r(l)}},n=u=>{try{o(t.throw(u))}catch(l){r(l)}},o=u=>u.done?i(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),ms=function(a,e){this[0]=a,this[1]=e},oe=(a,e,t)=>{var i=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof ms,h=c.done;Promise.resolve(d?o[0]:o).then(p=>d?i(n==="return"?n:"next",o[1]?{done:p.done,value:p.value}:p,u,l):u({value:p,done:h})).catch(p=>i("throw",p,u,l))}catch(p){l(p)}},r=n=>s[n]=o=>new Promise((u,l)=>i(n,o,u,l)),s={};return t=t.apply(a,e),s[uI("asyncIterator")]=()=>s,r("next"),r("throw"),r("return"),s};var se=f((oo,yd)=>{"use strict";var gr=function(a){return a&&a.Math===Math&&a};yd.exports=gr(typeof globalThis=="object"&&globalThis)||gr(typeof window=="object"&&window)||gr(typeof self=="object"&&self)||gr(typeof global=="object"&&global)||gr(typeof oo=="object"&&oo)||function(){return this}()||Function("return this")()});var fe=f((_0,Td)=>{"use strict";Td.exports=function(a){try{return!!a()}catch(e){return!0}}});var vr=f((N0,Id)=>{"use strict";var cI=fe();Id.exports=!cI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var uo=f((F0,wd)=>{"use strict";var dI=vr(),Pd=Function.prototype,Ed=Pd.apply,xd=Pd.call;wd.exports=typeof Reflect=="object"&&Reflect.apply||(dI?xd.bind(Ed):function(){return xd.apply(Ed,arguments)})});var ce=f((q0,Rd)=>{"use strict";var Ad=vr(),kd=Function.prototype,lo=kd.call,pI=Ad&&kd.bind.bind(lo,lo);Rd.exports=Ad?pI:function(a){return function(){return lo.apply(a,arguments)}}});var ii=f((U0,$d)=>{"use strict";var Ld=ce(),hI=Ld({}.toString),mI=Ld("".slice);$d.exports=function(a){return mI(hI(a),8,-1)}});var co=f((H0,Md)=>{"use strict";var fI=ii(),bI=ce();Md.exports=function(a){if(fI(a)==="Function")return bI(a)}});var re=f((j0,Dd)=>{"use strict";var po=typeof document=="object"&&document.all;Dd.exports=typeof po=="undefined"&&po!==void 0?function(a){return typeof a=="function"||a===po}:function(a){return typeof a=="function"}});var Ve=f((Q0,Cd)=>{"use strict";var gI=fe();Cd.exports=!gI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Oe=f((G0,Vd)=>{"use strict";var vI=vr(),gs=Function.prototype.call;Vd.exports=vI?gs.bind(gs):function(){return gs.apply(gs,arguments)}});var ho=f(_d=>{"use strict";var Od={}.propertyIsEnumerable,Bd=Object.getOwnPropertyDescriptor,SI=Bd&&!Od.call({1:2},1);_d.f=SI?function(e){var t=Bd(this,e);return!!t&&t.enumerable}:Od});var Sr=f((Y0,Nd)=>{"use strict";Nd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var qd=f((z0,Fd)=>{"use strict";var yI=ce(),TI=fe(),II=ii(),mo=Object,EI=yI("".split);Fd.exports=TI(function(){return!mo("z").propertyIsEnumerable(0)})?function(a){return II(a)==="String"?EI(a,""):mo(a)}:mo});var Ri=f((K0,Ud)=>{"use strict";Ud.exports=function(a){return a==null}});var Mt=f((X0,Hd)=>{"use strict";var xI=Ri(),PI=TypeError;Hd.exports=function(a){if(xI(a))throw new PI("Can't call method on "+a);return a}});var ri=f((J0,jd)=>{"use strict";var wI=qd(),AI=Mt();jd.exports=function(a){return wI(AI(a))}});var Be=f((Z0,Qd)=>{"use strict";var kI=re();Qd.exports=function(a){return typeof a=="object"?a!==null:kI(a)}});var Li=f((eV,Gd)=>{"use strict";Gd.exports={}});var ft=f((tV,Yd)=>{"use strict";var fo=Li(),bo=se(),RI=re(),Wd=function(a){return RI(a)?a:void 0};Yd.exports=function(a,e){return arguments.length<2?Wd(fo[a])||Wd(bo[a]):fo[a]&&fo[a][e]||bo[a]&&bo[a][e]}});var yr=f((iV,zd)=>{"use strict";var LI=ce();zd.exports=LI({}.isPrototypeOf)});var ai=f((rV,Jd)=>{"use strict";var $I=se(),Kd=$I.navigator,Xd=Kd&&Kd.userAgent;Jd.exports=Xd?String(Xd):""});var vo=f((aV,ap)=>{"use strict";var rp=se(),go=ai(),Zd=rp.process,ep=rp.Deno,tp=Zd&&Zd.versions||ep&&ep.version,ip=tp&&tp.v8,Ye,vs;ip&&(Ye=ip.split("."),vs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!vs&&go&&(Ye=go.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=go.match(/Chrome\/(\d+)/),Ye&&(vs=+Ye[1])));ap.exports=vs});var So=f((sV,np)=>{"use strict";var sp=vo(),MI=fe(),DI=se(),CI=DI.String;np.exports=!!Object.getOwnPropertySymbols&&!MI(function(){var a=Symbol("symbol detection");return!CI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&sp&&sp<41})});var yo=f((nV,op)=>{"use strict";var VI=So();op.exports=VI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var To=f((oV,up)=>{"use strict";var OI=ft(),BI=re(),_I=yr(),NI=yo(),FI=Object;up.exports=NI?function(a){return typeof a=="symbol"}:function(a){var e=OI("Symbol");return BI(e)&&_I(e.prototype,FI(a))}});var Tr=f((uV,lp)=>{"use strict";var qI=String;lp.exports=function(a){try{return qI(a)}catch(e){return"Object"}}});var st=f((lV,cp)=>{"use strict";var UI=re(),HI=Tr(),jI=TypeError;cp.exports=function(a){if(UI(a))return a;throw new jI(HI(a)+" is not a function")}});var Ir=f((cV,dp)=>{"use strict";var QI=st(),GI=Ri();dp.exports=function(a,e){var t=a[e];return GI(t)?void 0:QI(t)}});var hp=f((dV,pp)=>{"use strict";var Io=Oe(),Eo=re(),xo=Be(),WI=TypeError;pp.exports=function(a,e){var t,i;if(e==="string"&&Eo(t=a.toString)&&!xo(i=Io(t,a))||Eo(t=a.valueOf)&&!xo(i=Io(t,a))||e!=="string"&&Eo(t=a.toString)&&!xo(i=Io(t,a)))return i;throw new WI("Can't convert object to primitive value")}});var ze=f((pV,mp)=>{"use strict";mp.exports=!0});var gp=f((hV,bp)=>{"use strict";var fp=se(),YI=Object.defineProperty;bp.exports=function(a,e){try{YI(fp,a,{value:e,configurable:!0,writable:!0})}catch(t){fp[a]=e}return e}});var Er=f((mV,yp)=>{"use strict";var zI=ze(),KI=se(),XI=gp(),vp="__core-js_shared__",Sp=yp.exports=KI[vp]||XI(vp,{});(Sp.versions||(Sp.versions=[])).push({version:"3.38.0",mode:zI?"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 Po=f((fV,Ip)=>{"use strict";var Tp=Er();Ip.exports=function(a,e){return Tp[a]||(Tp[a]=e||{})}});var $i=f((bV,Ep)=>{"use strict";var JI=Mt(),ZI=Object;Ep.exports=function(a){return ZI(JI(a))}});var Ke=f((gV,xp)=>{"use strict";var eE=ce(),tE=$i(),iE=eE({}.hasOwnProperty);xp.exports=Object.hasOwn||function(e,t){return iE(tE(e),t)}});var wo=f((vV,Pp)=>{"use strict";var rE=ce(),aE=0,sE=Math.random(),nE=rE(1 .toString);Pp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+nE(++aE+sE,36)}});var be=f((SV,Ap)=>{"use strict";var oE=se(),uE=Po(),wp=Ke(),lE=wo(),cE=So(),dE=yo(),Mi=oE.Symbol,Ao=uE("wks"),pE=dE?Mi.for||Mi:Mi&&Mi.withoutSetter||lE;Ap.exports=function(a){return wp(Ao,a)||(Ao[a]=cE&&wp(Mi,a)?Mi[a]:pE("Symbol."+a)),Ao[a]}});var $p=f((yV,Lp)=>{"use strict";var hE=Oe(),kp=Be(),Rp=To(),mE=Ir(),fE=hp(),bE=be(),gE=TypeError,vE=bE("toPrimitive");Lp.exports=function(a,e){if(!kp(a)||Rp(a))return a;var t=mE(a,vE),i;if(t){if(e===void 0&&(e="default"),i=hE(t,a,e),!kp(i)||Rp(i))return i;throw new gE("Can't convert object to primitive value")}return e===void 0&&(e="number"),fE(a,e)}});var ko=f((TV,Mp)=>{"use strict";var SE=$p(),yE=To();Mp.exports=function(a){var e=SE(a,"string");return yE(e)?e:e+""}});var Ss=f((IV,Cp)=>{"use strict";var TE=se(),Dp=Be(),Ro=TE.document,IE=Dp(Ro)&&Dp(Ro.createElement);Cp.exports=function(a){return IE?Ro.createElement(a):{}}});var Lo=f((EV,Vp)=>{"use strict";var EE=Ve(),xE=fe(),PE=Ss();Vp.exports=!EE&&!xE(function(){return Object.defineProperty(PE("div"),"a",{get:function(){return 7}}).a!==7})});var _p=f(Bp=>{"use strict";var wE=Ve(),AE=Oe(),kE=ho(),RE=Sr(),LE=ri(),$E=ko(),ME=Ke(),DE=Lo(),Op=Object.getOwnPropertyDescriptor;Bp.f=wE?Op:function(e,t){if(e=LE(e),t=$E(t),DE)try{return Op(e,t)}catch(i){}if(ME(e,t))return RE(!AE(kE.f,e,t),e[t])}});var $o=f((PV,Np)=>{"use strict";var CE=fe(),VE=re(),OE=/#|\.prototype\./,xr=function(a,e){var t=_E[BE(a)];return t===FE?!0:t===NE?!1:VE(e)?CE(e):!!e},BE=xr.normalize=function(a){return String(a).replace(OE,".").toLowerCase()},_E=xr.data={},NE=xr.NATIVE="N",FE=xr.POLYFILL="P";Np.exports=xr});var Di=f((wV,qp)=>{"use strict";var Fp=co(),qE=st(),UE=vr(),HE=Fp(Fp.bind);qp.exports=function(a,e){return qE(a),e===void 0?a:UE?HE(a,e):function(){return a.apply(e,arguments)}}});var Mo=f((AV,Up)=>{"use strict";var jE=Ve(),QE=fe();Up.exports=jE&&QE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=f((kV,Hp)=>{"use strict";var GE=Be(),WE=String,YE=TypeError;Hp.exports=function(a){if(GE(a))return a;throw new YE(WE(a)+" is not an object")}});var si=f(Qp=>{"use strict";var zE=Ve(),KE=Lo(),XE=Mo(),ys=nt(),jp=ko(),JE=TypeError,Do=Object.defineProperty,ZE=Object.getOwnPropertyDescriptor,Co="enumerable",Vo="configurable",Oo="writable";Qp.f=zE?XE?function(e,t,i){if(ys(e),t=jp(t),ys(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Oo in i&&!i[Oo]){var r=ZE(e,t);r&&r[Oo]&&(e[t]=i.value,i={configurable:Vo in i?i[Vo]:r[Vo],enumerable:Co in i?i[Co]:r[Co],writable:!1})}return Do(e,t,i)}:Do:function(e,t,i){if(ys(e),t=jp(t),ys(i),KE)try{return Do(e,t,i)}catch(r){}if("get"in i||"set"in i)throw new JE("Accessors not supported");return"value"in i&&(e[t]=i.value),e}});var Ci=f((LV,Gp)=>{"use strict";var ex=Ve(),tx=si(),ix=Sr();Gp.exports=ex?function(a,e,t){return tx.f(a,e,ix(1,t))}:function(a,e,t){return a[e]=t,a}});var ue=f(($V,Yp)=>{"use strict";var Pr=se(),rx=uo(),ax=co(),sx=re(),nx=_p().f,ox=$o(),Vi=Li(),ux=Di(),Oi=Ci(),Wp=Ke();Er();var lx=function(a){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,i)}return new a(t,i,r)}return rx(a,this,arguments)};return e.prototype=a.prototype,e};Yp.exports=function(a,e){var t=a.target,i=a.global,r=a.stat,s=a.proto,n=i?Pr:r?Pr[t]:Pr[t]&&Pr[t].prototype,o=i?Vi:Vi[t]||Oi(Vi,t,{})[t],u=o.prototype,l,c,d,h,p,m,b,g,v;for(h in e)l=ox(i?h:t+(r?".":"#")+h,a.forced),c=!l&&n&&Wp(n,h),m=o[h],c&&(a.dontCallGetSet?(v=nx(n,h),b=v&&v.value):b=n[h]),p=c&&b?b:e[h],!(!l&&!s&&typeof m==typeof p)&&(a.bind&&c?g=ux(p,Pr):a.wrap&&c?g=lx(p):s&&sx(p)?g=ax(p):g=p,(a.sham||p&&p.sham||m&&m.sham)&&Oi(g,"sham",!0),Oi(o,h,g),s&&(d=t+"Prototype",Wp(Vi,d)||Oi(Vi,d,{}),Oi(Vi[d],h,p),a.real&&u&&(l||!u[h])&&Oi(u,h,p)))}});var Kp=f((MV,zp)=>{"use strict";var cx=Math.ceil,dx=Math.floor;zp.exports=Math.trunc||function(e){var t=+e;return(t>0?dx:cx)(t)}});var wr=f((DV,Xp)=>{"use strict";var px=Kp();Xp.exports=function(a){var e=+a;return e!==e||e===0?0:px(e)}});var Zp=f((CV,Jp)=>{"use strict";var hx=wr(),mx=Math.max,fx=Math.min;Jp.exports=function(a,e){var t=hx(a);return t<0?mx(t+e,0):fx(t,e)}});var Bo=f((VV,eh)=>{"use strict";var bx=wr(),gx=Math.min;eh.exports=function(a){var e=bx(a);return e>0?gx(e,9007199254740991):0}});var Bi=f((OV,th)=>{"use strict";var vx=Bo();th.exports=function(a){return vx(a.length)}});var _o=f((BV,rh)=>{"use strict";var Sx=ri(),yx=Zp(),Tx=Bi(),ih=function(a){return function(e,t,i){var r=Sx(e),s=Tx(r);if(s===0)return!a&&-1;var n=yx(i,s),o;if(a&&t!==t){for(;s>n;)if(o=r[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in r)&&r[n]===t)return a||n||0;return!a&&-1}};rh.exports={includes:ih(!0),indexOf:ih(!1)}});var Ar=f((_V,ah)=>{"use strict";ah.exports=function(){}});var sh=f(()=>{"use strict";var Ix=ue(),Ex=_o().includes,xx=fe(),Px=Ar(),wx=xx(function(){return!Array(1).includes()});Ix({target:"Array",proto:!0,forced:wx},{includes:function(e){return Ex(this,e,arguments.length>1?arguments[1]:void 0)}});Px("includes")});var Dt=f((qV,nh)=>{"use strict";var Ax=ft();nh.exports=Ax});var uh=f((UV,oh)=>{"use strict";sh();var kx=Dt();oh.exports=kx("Array","includes")});var ch=f((HV,lh)=>{"use strict";var Rx=uh();lh.exports=Rx});var qe=f((jV,dh)=>{"use strict";var Lx=ch();dh.exports=Lx});var Es=f((iO,Sh)=>{"use strict";var _x=Po(),Nx=wo(),vh=_x("keys");Sh.exports=function(a){return vh[a]||(vh[a]=Nx(a))}});var Th=f((rO,yh)=>{"use strict";var Fx=fe();yh.exports=!Fx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var xs=f((aO,Eh)=>{"use strict";var qx=Ke(),Ux=re(),Hx=$i(),jx=Es(),Qx=Th(),Ih=jx("IE_PROTO"),qo=Object,Gx=qo.prototype;Eh.exports=Qx?qo.getPrototypeOf:function(a){var e=Hx(a);if(qx(e,Ih))return e[Ih];var t=e.constructor;return Ux(t)&&e instanceof t?t.prototype:e instanceof qo?Gx:null}});var Ps=f((sO,xh)=>{"use strict";xh.exports={}});var Ah=f((nO,wh)=>{"use strict";var Wx=ce(),Uo=Ke(),Yx=ri(),zx=_o().indexOf,Kx=Ps(),Ph=Wx([].push);wh.exports=function(a,e){var t=Yx(a),i=0,r=[],s;for(s in t)!Uo(Kx,s)&&Uo(t,s)&&Ph(r,s);for(;e.length>i;)Uo(t,s=e[i++])&&(~zx(r,s)||Ph(r,s));return r}});var Ho=f((oO,kh)=>{"use strict";kh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var jo=f((uO,Rh)=>{"use strict";var Xx=Ah(),Jx=Ho();Rh.exports=Object.keys||function(e){return Xx(e,Jx)}});var Qo=f((lO,Ch)=>{"use strict";var $h=Ve(),Zx=fe(),Mh=ce(),eP=xs(),tP=jo(),iP=ri(),rP=ho().f,Dh=Mh(rP),aP=Mh([].push),sP=$h&&Zx(function(){var a=Object.create(null);return a[2]=2,!Dh(a,2)}),Lh=function(a){return function(e){for(var t=iP(e),i=tP(t),r=sP&&eP(t)===null,s=i.length,n=0,o=[],u;s>n;)u=i[n++],(!$h||(r?u in t:Dh(t,u)))&&aP(o,a?[u,t[u]]:t[u]);return o}};Ch.exports={entries:Lh(!0),values:Lh(!1)}});var Vh=f(()=>{"use strict";var nP=ue(),oP=Qo().entries;nP({target:"Object",stat:!0},{entries:function(e){return oP(e)}})});var Bh=f((pO,Oh)=>{"use strict";Vh();var uP=Li();Oh.exports=uP.Object.entries});var Nh=f((hO,_h)=>{"use strict";var lP=Bh();_h.exports=lP});var _i=f((mO,Fh)=>{"use strict";var cP=Nh();Fh.exports=cP});var ni=f((fO,qh)=>{"use strict";qh.exports={}});var jh=f((bO,Hh)=>{"use strict";var dP=se(),pP=re(),Uh=dP.WeakMap;Hh.exports=pP(Uh)&&/native code/.test(String(Uh))});var zo=f((gO,Wh)=>{"use strict";var hP=jh(),Gh=se(),mP=Be(),fP=Ci(),Go=Ke(),Wo=Er(),bP=Es(),gP=Ps(),Qh="Object already initialized",Yo=Gh.TypeError,vP=Gh.WeakMap,ws,kr,As,SP=function(a){return As(a)?kr(a):ws(a,{})},yP=function(a){return function(e){var t;if(!mP(e)||(t=kr(e)).type!==a)throw new Yo("Incompatible receiver, "+a+" required");return t}};hP||Wo.state?(Xe=Wo.state||(Wo.state=new vP),Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,ws=function(a,e){if(Xe.has(a))throw new Yo(Qh);return e.facade=a,Xe.set(a,e),e},kr=function(a){return Xe.get(a)||{}},As=function(a){return Xe.has(a)}):(oi=bP("state"),gP[oi]=!0,ws=function(a,e){if(Go(a,oi))throw new Yo(Qh);return e.facade=a,fP(a,oi,e),e},kr=function(a){return Go(a,oi)?a[oi]:{}},As=function(a){return Go(a,oi)});var Xe,oi;Wh.exports={set:ws,get:kr,has:As,enforce:SP,getterFor:yP}});var Jo=f((vO,zh)=>{"use strict";var Ko=Ve(),TP=Ke(),Yh=Function.prototype,IP=Ko&&Object.getOwnPropertyDescriptor,Xo=TP(Yh,"name"),EP=Xo&&function(){}.name==="something",xP=Xo&&(!Ko||Ko&&IP(Yh,"name").configurable);zh.exports={EXISTS:Xo,PROPER:EP,CONFIGURABLE:xP}});var Xh=f(Kh=>{"use strict";var PP=Ve(),wP=Mo(),AP=si(),kP=nt(),RP=ri(),LP=jo();Kh.f=PP&&!wP?Object.defineProperties:function(e,t){kP(e);for(var i=RP(t),r=LP(t),s=r.length,n=0,o;s>n;)AP.f(e,o=r[n++],i[o]);return e}});var Zo=f((yO,Jh)=>{"use strict";var $P=ft();Jh.exports=$P("document","documentElement")});var ru=f((TO,sm)=>{"use strict";var MP=nt(),DP=Xh(),Zh=Ho(),CP=Ps(),VP=Zo(),OP=Ss(),BP=Es(),em=">",tm="<",tu="prototype",iu="script",rm=BP("IE_PROTO"),eu=function(){},am=function(a){return tm+iu+em+a+tm+"/"+iu+em},im=function(a){a.write(am("")),a.close();var e=a.parentWindow.Object;return a=null,e},_P=function(){var a=OP("iframe"),e="java"+iu+":",t;return a.style.display="none",VP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(am("document.F=Object")),t.close(),t.F},ks,Rs=function(){try{ks=new ActiveXObject("htmlfile")}catch(e){}Rs=typeof document!="undefined"?document.domain&&ks?im(ks):_P():im(ks);for(var a=Zh.length;a--;)delete Rs[tu][Zh[a]];return Rs()};CP[rm]=!0;sm.exports=Object.create||function(e,t){var i;return e!==null?(eu[tu]=MP(e),i=new eu,eu[tu]=null,i[rm]=e):i=Rs(),t===void 0?i:DP.f(i,t)}});var Ni=f((IO,nm)=>{"use strict";var NP=Ci();nm.exports=function(a,e,t,i){return i&&i.enumerable?a[e]=t:NP(a,e,t),a}});var ou=f((EO,lm)=>{"use strict";var FP=fe(),qP=re(),UP=Be(),HP=ru(),om=xs(),jP=Ni(),QP=be(),GP=ze(),nu=QP("iterator"),um=!1,bt,au,su;[].keys&&(su=[].keys(),"next"in su?(au=om(om(su)),au!==Object.prototype&&(bt=au)):um=!0);var WP=!UP(bt)||FP(function(){var a={};return bt[nu].call(a)!==a});WP?bt={}:GP&&(bt=HP(bt));qP(bt[nu])||jP(bt,nu,function(){return this});lm.exports={IteratorPrototype:bt,BUGGY_SAFARI_ITERATORS:um}});var Ls=f((xO,dm)=>{"use strict";var YP=be(),zP=YP("toStringTag"),cm={};cm[zP]="z";dm.exports=String(cm)==="[object z]"});var Rr=f((PO,pm)=>{"use strict";var KP=Ls(),XP=re(),$s=ii(),JP=be(),ZP=JP("toStringTag"),ew=Object,tw=$s(function(){return arguments}())==="Arguments",iw=function(a,e){try{return a[e]}catch(t){}};pm.exports=KP?$s:function(a){var e,t,i;return a===void 0?"Undefined":a===null?"Null":typeof(t=iw(e=ew(a),ZP))=="string"?t:tw?$s(e):(i=$s(e))==="Object"&&XP(e.callee)?"Arguments":i}});var mm=f((wO,hm)=>{"use strict";var rw=Ls(),aw=Rr();hm.exports=rw?{}.toString:function(){return"[object "+aw(this)+"]"}});var Lr=f((AO,bm)=>{"use strict";var sw=Ls(),nw=si().f,ow=Ci(),uw=Ke(),lw=mm(),cw=be(),fm=cw("toStringTag");bm.exports=function(a,e,t,i){var r=t?a:a&&a.prototype;r&&(uw(r,fm)||nw(r,fm,{configurable:!0,value:e}),i&&!sw&&ow(r,"toString",lw))}});var vm=f((kO,gm)=>{"use strict";var dw=ou().IteratorPrototype,pw=ru(),hw=Sr(),mw=Lr(),fw=ni(),bw=function(){return this};gm.exports=function(a,e,t,i){var r=e+" Iterator";return a.prototype=pw(dw,{next:hw(+!i,t)}),mw(a,r,!1,!0),fw[r]=bw,a}});var ym=f((RO,Sm)=>{"use strict";var gw=ce(),vw=st();Sm.exports=function(a,e,t){try{return gw(vw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(i){}}});var Im=f((LO,Tm)=>{"use strict";var Sw=Be();Tm.exports=function(a){return Sw(a)||a===null}});var xm=f(($O,Em)=>{"use strict";var yw=Im(),Tw=String,Iw=TypeError;Em.exports=function(a){if(yw(a))return a;throw new Iw("Can't set "+Tw(a)+" as a prototype")}});var uu=f((MO,Pm)=>{"use strict";var Ew=ym(),xw=Be(),Pw=Mt(),ww=xm();Pm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=Ew(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(i){}return function(r,s){return Pw(r),ww(s),xw(r)&&(a?t(r,s):r.__proto__=s),r}}():void 0)});var Om=f((DO,Vm)=>{"use strict";var Aw=ue(),kw=Oe(),Ms=ze(),Dm=Jo(),Rw=re(),Lw=vm(),wm=xs(),Am=uu(),$w=Lr(),Mw=Ci(),lu=Ni(),Dw=be(),km=ni(),Cm=ou(),Cw=Dm.PROPER,Vw=Dm.CONFIGURABLE,Rm=Cm.IteratorPrototype,Ds=Cm.BUGGY_SAFARI_ITERATORS,$r=Dw("iterator"),Lm="keys",Mr="values",$m="entries",Mm=function(){return this};Vm.exports=function(a,e,t,i,r,s,n){Lw(t,e,i);var o=function(v){if(v===r&&h)return h;if(!Ds&&v&&v in c)return c[v];switch(v){case Lm:return function(){return new t(this,v)};case Mr:return function(){return new t(this,v)};case $m:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[$r]||c["@@iterator"]||r&&c[r],h=!Ds&&d||o(r),p=e==="Array"&&c.entries||d,m,b,g;if(p&&(m=wm(p.call(new a)),m!==Object.prototype&&m.next&&(!Ms&&wm(m)!==Rm&&(Am?Am(m,Rm):Rw(m[$r])||lu(m,$r,Mm)),$w(m,u,!0,!0),Ms&&(km[u]=Mm))),Cw&&r===Mr&&d&&d.name!==Mr&&(!Ms&&Vw?Mw(c,"name",Mr):(l=!0,h=function(){return kw(d,this)})),r)if(b={values:o(Mr),keys:s?h:o(Lm),entries:o($m)},n)for(g in b)(Ds||l||!(g in c))&&lu(c,g,b[g]);else Aw({target:e,proto:!0,forced:Ds||l},b);return(!Ms||n)&&c[$r]!==h&&lu(c,$r,h,{name:r}),km[e]=h,b}});var _m=f((CO,Bm)=>{"use strict";Bm.exports=function(a,e){return{value:a,done:e}}});var du=f((VO,Hm)=>{"use strict";var Ow=ri(),cu=Ar(),Nm=ni(),qm=zo(),Bw=si().f,_w=Om(),Cs=_m(),Nw=ze(),Fw=Ve(),Um="Array Iterator",qw=qm.set,Uw=qm.getterFor(Um);Hm.exports=_w(Array,"Array",function(a,e){qw(this,{type:Um,target:Ow(a),index:0,kind:e})},function(){var a=Uw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Cs(void 0,!0);switch(a.kind){case"keys":return Cs(t,!1);case"values":return Cs(e[t],!1)}return Cs([t,e[t]],!1)},"values");var Fm=Nm.Arguments=Nm.Array;cu("keys");cu("values");cu("entries");if(!Nw&&Fw&&Fm.name!=="values")try{Bw(Fm,"name",{value:"values"})}catch(a){}});var Qm=f((OO,jm)=>{"use strict";var Hw=be(),jw=ni(),Qw=Hw("iterator"),Gw=Array.prototype;jm.exports=function(a){return a!==void 0&&(jw.Array===a||Gw[Qw]===a)}});var pu=f((BO,Wm)=>{"use strict";var Ww=Rr(),Gm=Ir(),Yw=Ri(),zw=ni(),Kw=be(),Xw=Kw("iterator");Wm.exports=function(a){if(!Yw(a))return Gm(a,Xw)||Gm(a,"@@iterator")||zw[Ww(a)]}});var zm=f((_O,Ym)=>{"use strict";var Jw=Oe(),Zw=st(),eA=nt(),tA=Tr(),iA=pu(),rA=TypeError;Ym.exports=function(a,e){var t=arguments.length<2?iA(a):e;if(Zw(t))return eA(Jw(t,a));throw new rA(tA(a)+" is not iterable")}});var Jm=f((NO,Xm)=>{"use strict";var aA=Oe(),Km=nt(),sA=Ir();Xm.exports=function(a,e,t){var i,r;Km(a);try{if(i=sA(a,"return"),!i){if(e==="throw")throw t;return t}i=aA(i,a)}catch(s){r=!0,i=s}if(e==="throw")throw t;if(r)throw i;return Km(i),t}});var Os=f((FO,rf)=>{"use strict";var nA=Di(),oA=Oe(),uA=nt(),lA=Tr(),cA=Qm(),dA=Bi(),Zm=yr(),pA=zm(),hA=pu(),ef=Jm(),mA=TypeError,Vs=function(a,e){this.stopped=a,this.result=e},tf=Vs.prototype;rf.exports=function(a,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=nA(e,i),l,c,d,h,p,m,b,g=function(S){return l&&ef(l,"normal",S),new Vs(!0,S)},v=function(S){return r?(uA(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=hA(a),!c)throw new mA(lA(a)+" is not iterable");if(cA(c)){for(d=0,h=dA(a);h>d;d++)if(p=v(a[d]),p&&Zm(tf,p))return p;return new Vs(!1)}l=pA(a,c)}for(m=s?a.next:l.next;!(b=oA(m,l)).done;){try{p=v(b.value)}catch(S){ef(l,"throw",S)}if(typeof p=="object"&&p&&Zm(tf,p))return p}return new Vs(!1)}});var sf=f((qO,af)=>{"use strict";var fA=Ve(),bA=si(),gA=Sr();af.exports=function(a,e,t){fA?bA.f(a,e,gA(0,t)):a[e]=t}});var nf=f(()=>{"use strict";var vA=ue(),SA=Os(),yA=sf();vA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return SA(e,function(i,r){yA(t,i,r)},{AS_ENTRIES:!0}),t}})});var uf=f((jO,of)=>{"use strict";du();nf();var TA=Li();of.exports=TA.Object.fromEntries});var cf=f((QO,lf)=>{"use strict";lf.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 pf=f(()=>{"use strict";du();var IA=cf(),EA=se(),xA=Lr(),df=ni();for(Bs in IA)xA(EA[Bs],Bs),df[Bs]=df.Array;var Bs});var mf=f((YO,hf)=>{"use strict";var PA=uf();pf();hf.exports=PA});var hu=f((zO,ff)=>{"use strict";var wA=mf();ff.exports=wA});var bf=f(()=>{"use strict"});var mu=f((JO,gf)=>{"use strict";var Dr=se(),AA=ai(),kA=ii(),_s=function(a){return AA.slice(0,a.length)===a};gf.exports=function(){return _s("Bun/")?"BUN":_s("Cloudflare-Workers")?"CLOUDFLARE":_s("Deno/")?"DENO":_s("Node.js/")?"NODE":Dr.Bun&&typeof Bun.version=="string"?"BUN":Dr.Deno&&typeof Deno.version=="object"?"DENO":kA(Dr.process)==="process"?"NODE":Dr.window&&Dr.document?"BROWSER":"REST"}()});var Ns=f((ZO,vf)=>{"use strict";var RA=mu();vf.exports=RA==="NODE"});var yf=f((eB,Sf)=>{"use strict";var LA=si();Sf.exports=function(a,e,t){return LA.f(a,e,t)}});var Ef=f((tB,If)=>{"use strict";var $A=ft(),MA=yf(),DA=be(),CA=Ve(),Tf=DA("species");If.exports=function(a){var e=$A(a);CA&&e&&!e[Tf]&&MA(e,Tf,{configurable:!0,get:function(){return this}})}});var Pf=f((iB,xf)=>{"use strict";var VA=yr(),OA=TypeError;xf.exports=function(a,e){if(VA(e,a))return a;throw new OA("Incorrect invocation")}});var bu=f((rB,wf)=>{"use strict";var BA=ce(),_A=re(),fu=Er(),NA=BA(Function.toString);_A(fu.inspectSource)||(fu.inspectSource=function(a){return NA(a)});wf.exports=fu.inspectSource});var vu=f((aB,$f)=>{"use strict";var FA=ce(),qA=fe(),Af=re(),UA=Rr(),HA=ft(),jA=bu(),kf=function(){},Rf=HA("Reflect","construct"),gu=/^\s*(?:class|function)\b/,QA=FA(gu.exec),GA=!gu.test(kf),Cr=function(e){if(!Af(e))return!1;try{return Rf(kf,[],e),!0}catch(t){return!1}},Lf=function(e){if(!Af(e))return!1;switch(UA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return GA||!!QA(gu,jA(e))}catch(t){return!0}};Lf.sham=!0;$f.exports=!Rf||qA(function(){var a;return Cr(Cr.call)||!Cr(Object)||!Cr(function(){a=!0})||a})?Lf:Cr});var Df=f((sB,Mf)=>{"use strict";var WA=vu(),YA=Tr(),zA=TypeError;Mf.exports=function(a){if(WA(a))return a;throw new zA(YA(a)+" is not a constructor")}});var Su=f((nB,Vf)=>{"use strict";var Cf=nt(),KA=Df(),XA=Ri(),JA=be(),ZA=JA("species");Vf.exports=function(a,e){var t=Cf(a).constructor,i;return t===void 0||XA(i=Cf(t)[ZA])?e:KA(i)}});var Bf=f((oB,Of)=>{"use strict";var ek=ce();Of.exports=ek([].slice)});var Nf=f((uB,_f)=>{"use strict";var tk=TypeError;_f.exports=function(a,e){if(a<e)throw new tk("Not enough arguments");return a}});var yu=f((lB,Ff)=>{"use strict";var ik=ai();Ff.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(ik)});var Ru=f((cB,zf)=>{"use strict";var _e=se(),rk=uo(),ak=Di(),qf=re(),sk=Ke(),Yf=fe(),Uf=Zo(),nk=Bf(),Hf=Ss(),ok=Nf(),uk=yu(),lk=Ns(),wu=_e.setImmediate,Au=_e.clearImmediate,ck=_e.process,Tu=_e.Dispatch,dk=_e.Function,jf=_e.MessageChannel,pk=_e.String,Iu=0,Vr={},Qf="onreadystatechange",Or,ui,Eu,xu;Yf(function(){Or=_e.location});var ku=function(a){if(sk(Vr,a)){var e=Vr[a];delete Vr[a],e()}},Pu=function(a){return function(){ku(a)}},Gf=function(a){ku(a.data)},Wf=function(a){_e.postMessage(pk(a),Or.protocol+"//"+Or.host)};(!wu||!Au)&&(wu=function(e){ok(arguments.length,1);var t=qf(e)?e:dk(e),i=nk(arguments,1);return Vr[++Iu]=function(){rk(t,void 0,i)},ui(Iu),Iu},Au=function(e){delete Vr[e]},lk?ui=function(a){ck.nextTick(Pu(a))}:Tu&&Tu.now?ui=function(a){Tu.now(Pu(a))}:jf&&!uk?(Eu=new jf,xu=Eu.port2,Eu.port1.onmessage=Gf,ui=ak(xu.postMessage,xu)):_e.addEventListener&&qf(_e.postMessage)&&!_e.importScripts&&Or&&Or.protocol!=="file:"&&!Yf(Wf)?(ui=Wf,_e.addEventListener("message",Gf,!1)):Qf in Hf("script")?ui=function(a){Uf.appendChild(Hf("script"))[Qf]=function(){Uf.removeChild(this),ku(a)}}:ui=function(a){setTimeout(Pu(a),0)});zf.exports={set:wu,clear:Au}});var Jf=f((dB,Xf)=>{"use strict";var Kf=se(),hk=Ve(),mk=Object.getOwnPropertyDescriptor;Xf.exports=function(a){if(!hk)return Kf[a];var e=mk(Kf,a);return e&&e.value}});var Lu=f((pB,eb)=>{"use strict";var Zf=function(){this.head=null,this.tail=null};Zf.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}}};eb.exports=Zf});var ib=f((hB,tb)=>{"use strict";var fk=ai();tb.exports=/ipad|iphone|ipod/i.test(fk)&&typeof Pebble!="undefined"});var ab=f((mB,rb)=>{"use strict";var bk=ai();rb.exports=/web0s(?!.*chrome)/i.test(bk)});var db=f((fB,cb)=>{"use strict";var qi=se(),gk=Jf(),sb=Di(),$u=Ru().set,vk=Lu(),Sk=yu(),yk=ib(),Tk=ab(),Mu=Ns(),nb=qi.MutationObserver||qi.WebKitMutationObserver,ob=qi.document,ub=qi.process,Fs=qi.Promise,Vu=gk("queueMicrotask"),Fi,Du,Cu,qs,lb;Vu||(Br=new vk,_r=function(){var a,e;for(Mu&&(a=ub.domain)&&a.exit();e=Br.get();)try{e()}catch(t){throw Br.head&&Fi(),t}a&&a.enter()},!Sk&&!Mu&&!Tk&&nb&&ob?(Du=!0,Cu=ob.createTextNode(""),new nb(_r).observe(Cu,{characterData:!0}),Fi=function(){Cu.data=Du=!Du}):!yk&&Fs&&Fs.resolve?(qs=Fs.resolve(void 0),qs.constructor=Fs,lb=sb(qs.then,qs),Fi=function(){lb(_r)}):Mu?Fi=function(){ub.nextTick(_r)}:($u=sb($u,qi),Fi=function(){$u(_r)}),Vu=function(a){Br.head||Fi(),Br.add(a)});var Br,_r;cb.exports=Vu});var hb=f((bB,pb)=>{"use strict";pb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Us=f((gB,mb)=>{"use strict";mb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var li=f((vB,fb)=>{"use strict";var Ik=se();fb.exports=Ik.Promise});var Ui=f((SB,Sb)=>{"use strict";var Ek=se(),Nr=li(),xk=re(),Pk=$o(),wk=bu(),Ak=be(),bb=mu(),kk=ze(),Ou=vo(),gb=Nr&&Nr.prototype,Rk=Ak("species"),Bu=!1,vb=xk(Ek.PromiseRejectionEvent),Lk=Pk("Promise",function(){var a=wk(Nr),e=a!==String(Nr);if(!e&&Ou===66||kk&&!(gb.catch&&gb.finally))return!0;if(!Ou||Ou<51||!/native code/.test(a)){var t=new Nr(function(s){s(1)}),i=function(s){s(function(){},function(){})},r=t.constructor={};if(r[Rk]=i,Bu=t.then(function(){})instanceof i,!Bu)return!0}return!e&&(bb==="BROWSER"||bb==="DENO")&&!vb});Sb.exports={CONSTRUCTOR:Lk,REJECTION_EVENT:vb,SUBCLASSING:Bu}});var Hi=f((yB,Tb)=>{"use strict";var yb=st(),$k=TypeError,Mk=function(a){var e,t;this.promise=new a(function(i,r){if(e!==void 0||t!==void 0)throw new $k("Bad Promise constructor");e=i,t=r}),this.resolve=yb(e),this.reject=yb(t)};Tb.exports.f=function(a){return new Mk(a)}});var Fb=f(()=>{"use strict";var Dk=ue(),Ck=ze(),Gs=Ns(),Ct=se(),Wi=Oe(),Ib=Ni(),Eb=uu(),Vk=Lr(),Ok=Ef(),Bk=st(),Qs=re(),_k=Be(),Nk=Pf(),Fk=Su(),kb=Ru().set,Uu=db(),qk=hb(),Uk=Us(),Hk=Lu(),Rb=zo(),Ws=li(),Hu=Ui(),Lb=Hi(),Ys="Promise",$b=Hu.CONSTRUCTOR,jk=Hu.REJECTION_EVENT,Qk=Hu.SUBCLASSING,_u=Rb.getterFor(Ys),Gk=Rb.set,ji=Ws&&Ws.prototype,ci=Ws,Hs=ji,Mb=Ct.TypeError,Nu=Ct.document,ju=Ct.process,Fu=Lb.f,Wk=Fu,Yk=!!(Nu&&Nu.createEvent&&Ct.dispatchEvent),Db="unhandledrejection",zk="rejectionhandled",xb=0,Cb=1,Kk=2,Qu=1,Vb=2,js,Pb,Xk,wb,Ob=function(a){var e;return _k(a)&&Qs(e=a.then)?e:!1},Bb=function(a,e){var t=e.value,i=e.state===Cb,r=i?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{r?(i||(e.rejection===Vb&&Zk(e),e.rejection=Qu),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),c=!0)),u===a.promise?n(new Mb("Promise-chain cycle")):(l=Ob(u))?Wi(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},_b=function(a,e){a.notified||(a.notified=!0,Uu(function(){for(var t=a.reactions,i;i=t.get();)Bb(i,a);a.notified=!1,e&&!a.rejection&&Jk(a)}))},Nb=function(a,e,t){var i,r;Yk?(i=Nu.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(a,!1,!0),Ct.dispatchEvent(i)):i={promise:e,reason:t},!jk&&(r=Ct["on"+a])?r(i):a===Db&&qk("Unhandled promise rejection",t)},Jk=function(a){Wi(kb,Ct,function(){var e=a.facade,t=a.value,i=Ab(a),r;if(i&&(r=Uk(function(){Gs?ju.emit("unhandledRejection",t,e):Nb(Db,e,t)}),a.rejection=Gs||Ab(a)?Vb:Qu,r.error))throw r.value})},Ab=function(a){return a.rejection!==Qu&&!a.parent},Zk=function(a){Wi(kb,Ct,function(){var e=a.facade;Gs?ju.emit("rejectionHandled",e):Nb(zk,e,a.value)})},Qi=function(a,e,t){return function(i){a(e,i,t)}},Gi=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Kk,_b(a,!0))},qu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new Mb("Promise can't be resolved itself");var i=Ob(e);i?Uu(function(){var r={done:!1};try{Wi(i,e,Qi(qu,r,a),Qi(Gi,r,a))}catch(s){Gi(r,s,a)}}):(a.value=e,a.state=Cb,_b(a,!1))}catch(r){Gi({done:!1},r,a)}}};if($b&&(ci=function(e){Nk(this,Hs),Bk(e),Wi(js,this);var t=_u(this);try{e(Qi(qu,t),Qi(Gi,t))}catch(i){Gi(t,i)}},Hs=ci.prototype,js=function(e){Gk(this,{type:Ys,done:!1,notified:!1,parent:!1,reactions:new Hk,rejection:!1,state:xb,value:void 0})},js.prototype=Ib(Hs,"then",function(e,t){var i=_u(this),r=Fu(Fk(this,ci));return i.parent=!0,r.ok=Qs(e)?e:!0,r.fail=Qs(t)&&t,r.domain=Gs?ju.domain:void 0,i.state===xb?i.reactions.add(r):Uu(function(){Bb(r,i)}),r.promise}),Pb=function(){var a=new js,e=_u(a);this.promise=a,this.resolve=Qi(qu,e),this.reject=Qi(Gi,e)},Lb.f=Fu=function(a){return a===ci||a===Xk?new Pb(a):Wk(a)},!Ck&&Qs(Ws)&&ji!==Object.prototype)){wb=ji.then,Qk||Ib(ji,"then",function(e,t){var i=this;return new ci(function(r,s){Wi(wb,i,r,s)}).then(e,t)},{unsafe:!0});try{delete ji.constructor}catch(a){}Eb&&Eb(ji,Hs)}Dk({global:!0,constructor:!0,wrap:!0,forced:$b},{Promise:ci});Vk(ci,Ys,!1,!0);Ok(Ys)});var Qb=f((EB,jb)=>{"use strict";var eR=be(),Ub=eR("iterator"),Hb=!1;try{qb=0,Gu={next:function(){return{done:!!qb++}},return:function(){Hb=!0}},Gu[Ub]=function(){return this},Array.from(Gu,function(){throw 2})}catch(a){}var qb,Gu;jb.exports=function(a,e){try{if(!e&&!Hb)return!1}catch(r){return!1}var t=!1;try{var i={};i[Ub]=function(){return{next:function(){return{done:t=!0}}}},a(i)}catch(r){}return t}});var Wu=f((xB,Gb)=>{"use strict";var tR=li(),iR=Qb(),rR=Ui().CONSTRUCTOR;Gb.exports=rR||!iR(function(a){tR.all(a).then(void 0,function(){})})});var Wb=f(()=>{"use strict";var aR=ue(),sR=Oe(),nR=st(),oR=Hi(),uR=Us(),lR=Os(),cR=Wu();aR({target:"Promise",stat:!0,forced:cR},{all:function(e){var t=this,i=oR.f(t),r=i.resolve,s=i.reject,n=uR(function(){var o=nR(t.resolve),u=[],l=0,c=1;lR(e,function(d){var h=l++,p=!1;c++,sR(o,t,d).then(function(m){p||(p=!0,u[h]=m,--c||r(u))},s)}),--c||r(u)});return n.error&&s(n.value),i.promise}})});var zb=f(()=>{"use strict";var dR=ue(),pR=ze(),hR=Ui().CONSTRUCTOR,zu=li(),mR=ft(),fR=re(),bR=Ni(),Yb=zu&&zu.prototype;dR({target:"Promise",proto:!0,forced:hR,real:!0},{catch:function(a){return this.then(void 0,a)}});!pR&&fR(zu)&&(Yu=mR("Promise").prototype.catch,Yb.catch!==Yu&&bR(Yb,"catch",Yu,{unsafe:!0}));var Yu});var Kb=f(()=>{"use strict";var gR=ue(),vR=Oe(),SR=st(),yR=Hi(),TR=Us(),IR=Os(),ER=Wu();gR({target:"Promise",stat:!0,forced:ER},{race:function(e){var t=this,i=yR.f(t),r=i.reject,s=TR(function(){var n=SR(t.resolve);IR(e,function(o){vR(n,t,o).then(i.resolve,r)})});return s.error&&r(s.value),i.promise}})});var Xb=f(()=>{"use strict";var xR=ue(),PR=Hi(),wR=Ui().CONSTRUCTOR;xR({target:"Promise",stat:!0,forced:wR},{reject:function(e){var t=PR.f(this),i=t.reject;return i(e),t.promise}})});var Ku=f((DB,Jb)=>{"use strict";var AR=nt(),kR=Be(),RR=Hi();Jb.exports=function(a,e){if(AR(a),kR(e)&&e.constructor===a)return e;var t=RR.f(a),i=t.resolve;return i(e),t.promise}});var tg=f(()=>{"use strict";var LR=ue(),$R=ft(),Zb=ze(),MR=li(),eg=Ui().CONSTRUCTOR,DR=Ku(),CR=$R("Promise"),VR=Zb&&!eg;LR({target:"Promise",stat:!0,forced:Zb||eg},{resolve:function(e){return DR(VR&&this===CR?MR:this,e)}})});var ig=f(()=>{"use strict";Fb();Wb();zb();Kb();Xb();tg()});var ng=f(()=>{"use strict";var OR=ue(),BR=ze(),zs=li(),_R=fe(),ag=ft(),sg=re(),NR=Su(),rg=Ku(),FR=Ni(),Ju=zs&&zs.prototype,qR=!!zs&&_R(function(){Ju.finally.call({then:function(){}},function(){})});OR({target:"Promise",proto:!0,real:!0,forced:qR},{finally:function(a){var e=NR(this,ag("Promise")),t=sg(a);return this.then(t?function(i){return rg(e,a()).then(function(){return i})}:a,t?function(i){return rg(e,a()).then(function(){throw i})}:a)}});!BR&&sg(zs)&&(Xu=ag("Promise").prototype.finally,Ju.finally!==Xu&&FR(Ju,"finally",Xu,{unsafe:!0}));var Xu});var ug=f((FB,og)=>{"use strict";bf();ig();ng();var UR=Dt();og.exports=UR("Promise","finally")});var cg=f((qB,lg)=>{"use strict";var HR=ug();lg.exports=HR});var Ks=f((UB,dg)=>{"use strict";var jR=cg();dg.exports=jR});var xg=f(()=>{"use strict";var aL=ue(),sL=Qo().values;aL({target:"Object",stat:!0},{values:function(e){return sL(e)}})});var wg=f((w_,Pg)=>{"use strict";xg();var nL=Li();Pg.exports=nL.Object.values});var kg=f((A_,Ag)=>{"use strict";var oL=wg();Ag.exports=oL});var zi=f((k_,Rg)=>{"use strict";var uL=kg();Rg.exports=uL});var Gg=f(()=>{"use strict";var ML=ue(),DL=$i(),CL=Bi(),VL=wr(),OL=Ar();ML({target:"Array",proto:!0},{at:function(e){var t=DL(this),i=CL(t),r=VL(e),s=r>=0?r:i+r;return s<0||s>=i?void 0:t[s]}});OL("at")});var Yg=f((FN,Wg)=>{"use strict";Gg();var BL=Dt();Wg.exports=BL("Array","at")});var Kg=f((qN,zg)=>{"use strict";var _L=Yg();zg.exports=_L});var Nt=f((UN,Xg)=>{"use strict";var NL=Kg();Xg.exports=NL});var xl=f((Lq,Mv)=>{"use strict";var I$=ii();Mv.exports=Array.isArray||function(e){return I$(e)==="Array"}});var Cv=f(($q,Dv)=>{"use strict";var E$=TypeError,x$=9007199254740991;Dv.exports=function(a){if(a>x$)throw E$("Maximum allowed index exceeded");return a}});var Bv=f((Mq,Ov)=>{"use strict";var P$=xl(),w$=Bi(),A$=Cv(),k$=Di(),Vv=function(a,e,t,i,r,s,n,o){for(var u=r,l=0,c=n?k$(n,o):!1,d,h;l<i;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&P$(d)?(h=w$(d),u=Vv(a,e,d,h,u,s-1)-1):(A$(u+1),a[u]=d),u++),l++;return u};Ov.exports=Vv});var qv=f((Dq,Fv)=>{"use strict";var _v=xl(),R$=vu(),L$=Be(),$$=be(),M$=$$("species"),Nv=Array;Fv.exports=function(a){var e;return _v(a)&&(e=a.constructor,R$(e)&&(e===Nv||_v(e.prototype))?e=void 0:L$(e)&&(e=e[M$],e===null&&(e=void 0))),e===void 0?Nv:e}});var Hv=f((Cq,Uv)=>{"use strict";var D$=qv();Uv.exports=function(a,e){return new(D$(a))(e===0?0:e)}});var jv=f(()=>{"use strict";var C$=ue(),V$=Bv(),O$=st(),B$=$i(),_$=Bi(),N$=Hv();C$({target:"Array",proto:!0},{flatMap:function(e){var t=B$(this),i=_$(t),r;return O$(e),r=N$(t,0),r.length=V$(r,t,t,i,0,1,e,arguments.length>1?arguments[1]:void 0),r}})});var Qv=f(()=>{"use strict";var F$=Ar();F$("flatMap")});var Wv=f((Nq,Gv)=>{"use strict";jv();Qv();var q$=Dt();Gv.exports=q$("Array","flatMap")});var zv=f((Fq,Yv)=>{"use strict";var U$=Wv();Yv.exports=U$});var Pl=f((qq,Kv)=>{"use strict";var H$=zv();Kv.exports=H$});var ia=f((Uq,Xv)=>{"use strict";var j$=Rr(),Q$=String;Xv.exports=function(a){if(j$(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return Q$(a)}});var wl=f((Hq,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 tS=f((jq,eS)=>{"use strict";var G$=ce(),W$=Mt(),Y$=ia(),kl=wl(),Zv=G$("".replace),z$=RegExp("^["+kl+"]+"),K$=RegExp("(^|[^"+kl+"])["+kl+"]+$"),Al=function(a){return function(e){var t=Y$(W$(e));return a&1&&(t=Zv(t,z$,"")),a&2&&(t=Zv(t,K$,"$1")),t}};eS.exports={start:Al(1),end:Al(2),trim:Al(3)}});var sS=f((Qq,aS)=>{"use strict";var X$=Jo().PROPER,J$=fe(),iS=wl(),rS="\u200B\x85\u180E";aS.exports=function(a){return J$(function(){return!!iS[a]()||rS[a]()!==rS||X$&&iS[a].name!==a})}});var Rl=f((Gq,nS)=>{"use strict";var Z$=tS().start,eM=sS();nS.exports=eM("trimStart")?function(){return Z$(this)}:"".trimStart});var uS=f(()=>{"use strict";var tM=ue(),oS=Rl();tM({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==oS},{trimLeft:oS})});var cS=f(()=>{"use strict";uS();var iM=ue(),lS=Rl();iM({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==lS},{trimStart:lS})});var pS=f((Xq,dS)=>{"use strict";cS();var rM=Dt();dS.exports=rM("String","trimLeft")});var mS=f((Jq,hS)=>{"use strict";var aM=pS();hS.exports=aM});var bS=f((Zq,fS)=>{"use strict";var sM=mS();fS.exports=sM});var MS=f(()=>{"use strict"});var DS=f(()=>{"use strict"});var VS=f((OH,CS)=>{"use strict";var kM=Be(),RM=ii(),LM=be(),$M=LM("match");CS.exports=function(a){var e;return kM(a)&&((e=a[$M])!==void 0?!!e:RM(a)==="RegExp")}});var BS=f((BH,OS)=>{"use strict";var MM=nt();OS.exports=function(){var a=MM(this),e="";return a.hasIndices&&(e+="d"),a.global&&(e+="g"),a.ignoreCase&&(e+="i"),a.multiline&&(e+="m"),a.dotAll&&(e+="s"),a.unicode&&(e+="u"),a.unicodeSets&&(e+="v"),a.sticky&&(e+="y"),e}});var FS=f((_H,NS)=>{"use strict";var DM=Oe(),CM=Ke(),VM=yr(),OM=BS(),_S=RegExp.prototype;NS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in _S)&&!CM(a,"flags")&&VM(_S,a)?DM(OM,a):e}});var US=f((NH,qS)=>{"use strict";var Bl=ce(),BM=$i(),_M=Math.floor,Vl=Bl("".charAt),NM=Bl("".replace),Ol=Bl("".slice),FM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qM=/\$([$&'`]|\d{1,2})/g;qS.exports=function(a,e,t,i,r,s){var n=t+a.length,o=i.length,u=qM;return r!==void 0&&(r=BM(r),u=FM),NM(s,u,function(l,c){var d;switch(Vl(c,0)){case"$":return"$";case"&":return a;case"`":return Ol(e,0,t);case"'":return Ol(e,n);case"<":d=r[Ol(c,1,-1)];break;default:var h=+c;if(h===0)return l;if(h>o){var p=_M(h/10);return p===0?l:p<=o?i[p-1]===void 0?Vl(c,1):i[p-1]+Vl(c,1):l}d=i[h-1]}return d===void 0?"":d})}});var QS=f(()=>{"use strict";var UM=ue(),HM=Oe(),Nl=ce(),HS=Mt(),jM=re(),QM=Ri(),GM=VS(),tr=ia(),WM=Ir(),YM=FS(),zM=US(),KM=be(),XM=ze(),JM=KM("replace"),ZM=TypeError,_l=Nl("".indexOf),eD=Nl("".replace),jS=Nl("".slice),tD=Math.max;UM({target:"String",proto:!0},{replaceAll:function(e,t){var i=HS(this),r,s,n,o,u,l,c,d,h,p,m=0,b="";if(!QM(e)){if(r=GM(e),r&&(s=tr(HS(YM(e))),!~_l(s,"g")))throw new ZM("`.replaceAll` does not allow non-global regexes");if(n=WM(e,JM),n)return HM(n,e,i,t);if(XM&&r)return eD(tr(i),e,t)}for(o=tr(i),u=tr(e),l=jM(t),l||(t=tr(t)),c=u.length,d=tD(1,c),h=_l(o,u);h!==-1;)p=l?tr(t(u,h,o)):zM(u,o,h,[],void 0,t),b+=jS(o,m,h)+p,m=h+c,h=h+d>o.length?-1:_l(o,u,h+d);return m<o.length&&(b+=jS(o,m)),b}})});var WS=f((UH,GS)=>{"use strict";MS();DS();QS();var iD=Dt();GS.exports=iD("String","replaceAll")});var zS=f((HH,YS)=>{"use strict";var rD=WS();YS.exports=rD});var XS=f((jH,KS)=>{"use strict";var aD=zS();KS.exports=aD});var ZS=f((QH,JS)=>{"use strict";var sD=wr(),nD=ia(),oD=Mt(),uD=RangeError;JS.exports=function(e){var t=nD(oD(this)),i="",r=sD(e);if(r<0||r===1/0)throw new uD("Wrong number of repetitions");for(;r>0;(r>>>=1)&&(t+=t))r&1&&(i+=t);return i}});var ay=f((GH,ry)=>{"use strict";var iy=ce(),lD=Bo(),ey=ia(),cD=ZS(),dD=Mt(),pD=iy(cD),hD=iy("".slice),mD=Math.ceil,ty=function(a){return function(e,t,i){var r=ey(dD(e)),s=lD(t),n=r.length,o=i===void 0?" ":ey(i),u,l;return s<=n||o===""?r:(u=s-n,l=pD(o,mD(u/o.length)),l.length>u&&(l=hD(l,0,u)),a?r+l:l+r)}};ry.exports={start:ty(!1),end:ty(!0)}});var ny=f((WH,sy)=>{"use strict";var fD=ai();sy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(fD)});var oy=f(()=>{"use strict";var bD=ue(),gD=ay().start,vD=ny();bD({target:"String",proto:!0,forced:vD},{padStart:function(e){return gD(this,e,arguments.length>1?arguments[1]:void 0)}})});var ly=f((KH,uy)=>{"use strict";oy();var SD=Dt();uy.exports=SD("String","padStart")});var dy=f((XH,cy)=>{"use strict";var yD=ly();cy.exports=yD});var hy=f((JH,py)=>{"use strict";var TD=dy();py.exports=TD});var Sd="2.0.130-dev.ca914dc0.0";var Ce=(r=>(r.STOPPED="stopped",r.READY="ready",r.PLAYING="playing",r.PAUSED="paused",r))(Ce||{}),mt=(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))(mt||{});var fs=(r=>(r.NOT_AVAILABLE="NOT_AVAILABLE",r.AVAILABLE="AVAILABLE",r.CONNECTING="CONNECTING",r.CONNECTED="CONNECTED",r))(fs||{}),so=(i=>(i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic",i))(so||{});var no=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(no||{}),bs=(i=>(i.TRAFFIC_SAVING="traffic_saving",i.HIGH_QUALITY="high_quality",i.UNKNOWN="unknown",i))(bs||{});var YT=B(qe(),1);import{assertNever as gh,assertNonNullable as $x,isNonNullable as Ts,ValueSubject as No,Subject as Mx,Subscription as Dx,merge as Cx,observableFrom as Vx,fromEvent as hh,map as mh,tap as fh,filterChanged as Ox,isNullable as Fo,ErrorCategory as bh}from"@vkontakte/videoplayer-shared/es2015";var ph=a=>new Promise((e,t)=>{let i=document.createElement("script");i.setAttribute("src",a),i.onload=()=>e(),i.onerror=r=>t(r),document.body.appendChild(i)});var Is=class{constructor(e){this.connection$=new No(void 0);this.castState$=new No("NOT_AVAILABLE");this.errorEvent$=new Mx;this.realCastState$=new No("NOT_AVAILABLE");this.subscription=new Dx;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 i=Ts((s=window.chrome)==null?void 0:s.cast),r=!!window.__onGCastApiAvailable;i?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},r||ph("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:bh.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,s;(s=(r=(i=cast.framework.CastContext.getInstance())==null?void 0:i.getCurrentSession())==null?void 0:r.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ts(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Fo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Fo(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),i=cast.framework.CastContext.getInstance();this.subscription.add(hh(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var s,n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=i.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 gh(r.sessionState)}})).add(Cx(hh(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(fh(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),mh(r=>r.castState)),Vx([i.getCastState()])).pipe(Ox(),mh(Bx),fh(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var o,u;let s=r==="CONNECTED",n=Ts(this.connection$.getValue());if(s&&!n){let l=i.getCurrentSession();$x(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Fo(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(r==="CONNECTED"?Ts(this.connection$.getValue())?"CONNECTED":"AVAILABLE":r)}))}initializeCastApi(){var r;let e,t,i;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,i=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(r=this.params.receiverApplicationId)!=null?r:t,autoJoinPolicy:i}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:bh.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Bx=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 gh(a)}};var xc=B(qe(),1),RT=B(_i(),1),LT=B(hu(),1);var Tg=B(Ks(),1);import{assertNever as pg}from"@vkontakte/videoplayer-shared/es2015";var ge=(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 i=new URL(a);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case 2:{let i=new URL(a);return!i.searchParams.get("offset_p")&&e===0?a:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:pg(t)}return a},Xs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let i=new URL(a);return Number(i.searchParams.get("playback_shift"))}case 2:{let i=new URL(a);return Number((t=i.searchParams.get("offset_p"))!=null?t:0)}default:pg(e)}};var R=(a,e,t=!1)=>{let i=a.getTransition();(t||!i||i.to===e)&&a.setState(e)};import{isNonNullable as QR,Subject as Js,merge as hg}from"@vkontakte/videoplayer-shared/es2015";var _=class{constructor(e){this.transitionStarted$=new Js;this.transitionEnded$=new Js;this.transitionUpdated$=new Js;this.forceChanged$=new Js;this.stateChangeStarted$=hg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=hg(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,i=this.state;i===e||QR(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as GR}from"@vkontakte/videoplayer-shared/es2015";var mg=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 GR(a)}};import{assertNever as Yi,assertNonNullable as di,debounce as fg,ErrorCategory as bg,fromEvent as pi,isNonNullable as gg,map as vg,merge as Sg,observableFrom as WR,Subject as YR,Subscription as Zu,timeout as zR,getHighestQuality as KR}from"@vkontakte/videoplayer-shared/es2015";var XR=5,JR=5,ZR=500,yg=7e3,Fr=class{constructor(e){this.subscription=new Zu;this.loadMediaTimeoutSubscription=new Zu;this.videoState=new _("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(i){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Yi(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:Yi(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:Yi(e)}break}default:Yi(i)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(mg(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(Sg(this.videoState.stateChangeStarted$.pipe(vg(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(vg(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));let t=(r,s)=>this.subscription.add(r.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let r=new YR;e.add(r.pipe(fg(ZR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(pi(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)>XR)&&r.next(o),s=o})),e.add(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);let{remotePlayer:s}=this.params.connection,n=r.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(),R(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:Yi(n)}}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(pi(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});let i=Sg(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,WR(["init"])).pipe(fg(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),R(this.params.desiredState.playbackState,"playing"));let i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),R(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"),R(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"&&R(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var r,s;let t=this.params.output.volume$.getValue(),i={volume:(r=e.volume)!=null?r:t.volume,muted:(s=e.muted)!=null?s:t.muted};(i.volume!==t.volume||i.muted!==i.muted)&&this.params.output.volume$.next(i)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,i,r,s;switch(e){case"MPEG":{let c=t[e];di(c);let d=KR(Object.keys(c));di(d);let h=c[d];di(h),i=h,r="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];di(c),i=c.url,r="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];di(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];di(c),i=c.url,r="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];di(c),i=ge(c.url),r="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:bg.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Yi(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:i,r);n.contentUrl=i,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return gg(o)&&(n.metadata.title=o),gg(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let i=this.params.desiredState.seekState.getState();return i.state==="applying"||i.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),i=new Promise((r,s)=>{this.loadMediaTimeoutSubscription.add(zR(yg).subscribe(()=>s(`timeout(${yg})`)))});(0,Tg.default)(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:bg.VIDEO_PIPELINE,message:s,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var Il=B(qe(),1);import{clearVideoElement as Eg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as eL}from"@vkontakte/videoplayer-shared/es2015";var Ig=a=>{try{a.pause(),a.playbackRate=0,eL(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as tL,Subscription as iL}from"@vkontakte/videoplayer-shared/es2015";var el=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)}},tl=window.WeakMap?new WeakMap:new el,il=window.WeakMap?new WeakMap:new Map,rL=(a,e=20)=>{let t=0;return tL(a,"ratechange").subscribe(i=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Ae=(a,{audioVideoSyncRate:e,disableYandexPiP:t})=>{let i=a.querySelector("video"),r=!!i;i?Eg(i):(i=document.createElement("video"),a.appendChild(i)),tl.set(i,r);let s=new iL;return s.add(rL(i,e)),il.set(i,s),i.setAttribute("crossorigin","anonymous"),i.setAttribute("playsinline","playsinline"),t&&i.setAttribute("x-yandex-pip","false"),i.controls=!1,i.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i},ke=a=>{let e=il.get(a);e==null||e.unsubscribe(),il.delete(a);let t=tl.get(a);tl.delete(a),t?Eg(a):Ig(a)};var al=B(zi(),1);import{assertNonNullable as qr,isNonNullable as ut,isNullable as dL,fromEvent as Ki,merge as Lg,observableFrom as $g,filterChanged as Mg,map as Ur,Subject as Dg,Subscription as pL,ValueSubject as hL,ErrorCategory as mL}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as rl,isNullable as lL,Subscription as cL}from"@vkontakte/videoplayer-shared/es2015";var Zs=(a,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:s}={})=>{let n=a.getState(),o=e(),u=lL(r),l=new cL;return r&&l.add(r.subscribe(c=>{let d=a.getState();i(c,d)&&a.setState(c)},s)),i(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)=>Zs(e,()=>a.loop,i=>{rl(i)&&(a.loop=i)},{onError:t}),Re=(a,e,t,i)=>Zs(e,()=>({muted:a.muted,volume:a.volume}),r=>{rl(r)&&(a.muted=r.muted,a.volume=r.volume)},{equal:(r,s)=>r===s||(r==null?void 0:r.muted)===(s==null?void 0:s.muted)&&(r==null?void 0:r.volume)===(s==null?void 0:s.volume),changed$:t,onError:i}),Ue=(a,e,t,i)=>Zs(e,()=>a.playbackRate,r=>{rl(r)&&(a.playbackRate=r)},{changed$:t,onError:i}),Vt=Zs;var fL=a=>["__",a.language,a.label].join("|"),bL=(a,e)=>{if(a.id===e)return!0;let[t,i,r]=e.split("|");return a.language===i&&a.label===r},sl=class a{constructor(e){this.available$=new Dg;this.current$=new hL(void 0);this.error$=new Dg;this.subscription=new pL;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let r=s=>{this.error$.next({id:"TextTracksManager",category:mL.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Vt(t.internalTextTracks,()=>(0,al.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(Ur(s=>s.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Vt(t.externalTextTracks,()=>(0,al.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(Ur(s=>s.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Vt(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:r})),this.subscription.add(Vt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){qr(this.video);let{textTracks:e}=this.video;this.subscription.add(Ki(e,"addtrack").subscribe(()=>{let i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(Lg(Ki(e,"addtrack"),Ki(e,"removetrack"),$g(["init"])).pipe(Ur(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),Mg((i,r)=>i.length===r.length&&i.every(({id:s},n)=>s===r[n].id))).subscribe(this.available$)),this.subscription.add(Lg(Ki(e,"change"),$g(["init"])).pipe(Ur(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),Ur(i=>i&&this.htmlTextTrackToITextTrack(i).id),Mg()).subscribe(this.current$));let t=i=>{var r,s;return this.applyCueSettings((s=(r=i.target)==null?void 0:r.activeCues)!=null?s:null)};this.subscription.add(Ki(e,"addtrack").subscribe(i=>{var s,n;(s=i.track)==null||s.addEventListener("cuechange",t);let r=o=>{var l,c,d,h,p;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((h=(d=o.target)==null?void 0:d.cues)!=null?h:null),(p=o.target)==null||p.removeEventListener("cuechange",r))};(n=i.track)==null||n.addEventListener("cuechange",r)})),this.subscription.add(Ki(e,"removetrack").subscribe(i=>{var r;(r=i.track)==null||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let i of Array.from(e)){let r=i;ut(t.align)&&(r.align=t.align),ut(t.position)&&(r.position=t.position),ut(t.size)&&(r.size=t.size),ut(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){qr(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:i}=e,r=e.id?e.id:fL(e),s=this.externalTracks.has(r),n=(l=s?(o=this.externalTracks.get(r))==null?void 0:o.isAuto:(u=this.internalTracks.get(r))==null?void 0:u.isAuto)!=null?l:r.includes("auto");return s?{id:r,type:"external",isAuto:n,language:t,label:i,url:(c=this.externalTracks.get(r))==null?void 0:c.url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:(d=this.internalTracks.get(r))==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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:s})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===s)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){qr(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(dL(e)||!bL(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){qr(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){qr(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},He=sl;var hi=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Cg=a=>{let e=a;for(;!(e instanceof Document)&&!(e instanceof ShadowRoot)&&e!==null;)e=e==null?void 0:e.parentNode;return e!=null?e:void 0},nl=a=>{let e=Cg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Vg=a=>{let e=Cg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as Le,map as Ot,merge as ul,filterChanged as PL,isNonNullable as jg,Subject as wL,filter as jr,mapTo as ll,combine as AL,once as kL,throttle as RL,ErrorCategory as LL,ValueSubject as Qg,Subscription as $L}from"@vkontakte/videoplayer-shared/es2015";var gL=3,Og=(a,e,t=gL)=>{let i=0,r=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=s-1;u>=0;u--)a.end(u)+t>=i&&(i=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=r&&(r=a.end(u))}}return{from:i,to:r}};var en=class{get current(){return this._current}get isYandex(){return this.current==="Yandex"}get isSafari(){return this.current==="Safari"}get isSamsungBrowser(){return this.current==="SamsungBrowser"}get safariVersion(){return this._safariVersion}detect(){let{userAgent:e}=navigator;try{let t=/yabrowser/i.test(e)?"Yandex":void 0,i=/samsungbrowser/i.test(e)?"SamsungBrowser":void 0,r=/chrome|crios/i.test(e)?"Chrome":void 0,s=/chromium/i.test(e)?"Chromium":void 0,n=/firefox|fxios/i.test(e)?"Firefox":void 0,o=/webkit|safari|khtml/i.test(e)?"Safari":void 0,u=/opr\//i.test(e)?"Opera":void 0,l=/edg/i.test(e)?"Edge":void 0;this._current=t||i||n||u||l||r||s||o||"Rest"}catch(t){console.error(t)}this.isSafari&&this.detectSafariVersion()}detectSafariVersion(){try{let{userAgent:e}=window.navigator,t=e.match(/Version\/(\d+)/);if(!t)return;let i=t[1],r=parseInt(i,10);if(isNaN(r))return;this._safariVersion=r}catch(e){console.error(e)}}};var Bg=B(qe(),1);var Hr=()=>{var a,e;return/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test((a=navigator.appVersion)!=null?a:navigator.userAgent)||((e=navigator==null?void 0:navigator.userAgentData)==null?void 0:e.mobile)};var tn=class{constructor(e){this._highEntropyValues={};this._displayChecker=e}get current(){return this._current}get isIOS(){let e=["iPhone","iPad","iPod"];return this._highEntropyValues.platform==="iOS"||(0,Bg.default)(e,this.current)}get isMac(){return this._highEntropyValues.platform==="macOS"||this.current==="Mac"}get isApple(){return this.isIOS||this.isMac}get isIphoneOrOldIpad(){if(!this.isApple||!this._displayChecker.isTouch)return!1;let e=this.current==="iPad"||this._displayChecker.width>700,t=this._iosVersion;return!e||e&&!!t&&t<16}get isAndroid(){return this._highEntropyValues.platform==="Android"||this.current==="Android"}get isMobile(){return this._highEntropyValues.mobile||this._isMobile}get iOSVersion(){return this._iosVersion}detect(){let{userAgent:e}=navigator;try{this._isMobile=Hr()}catch(t){console.error(t)}this.detectDevice(e),this.detectHighEntropyValues(),this.isIOS&&this.detectIOSVersion()}detectHighEntropyValues(){return P(this,null,function*(){let{userAgentData:e}=navigator;if(e){let t=yield e.getHighEntropyValues(["architecture","bitness","brands","mobile","platform","formFactor","model","platformVersion","wow64"]);this._highEntropyValues=t}})}detectDevice(e){try{let t=/android/i.test(e)?"Android":void 0,i=/iphone/i.test(e)?"iPhone":void 0,r=/ipad/i.test(e)?"iPad":void 0,s=/ipod/i.test(e)?"iPod":void 0,n=/mac/i.test(e)?"Mac":void 0,o=/webOS|BlackBerry|IEMobile|Opera Mini/i.test(e)?"RestMobile":void 0;this._current=t||i||r||s||o||n||"Desktop"}catch(t){console.error(t)}}detectIOSVersion(){try{if(this._highEntropyValues.platformVersion){let s=this._highEntropyValues.platformVersion.split(".").slice(0,2).join("."),n=parseFloat(s);this._iosVersion=n;return}let{userAgent:e}=window.navigator,t=e.match(/OS (\d+(_\d+)?)/i);if(!t)return;let i=t[1].replace(/_/g,".");if(!i)return;let r=parseFloat(i);if(isNaN(r))return;this._iosVersion=r}catch(e){console.error(e)}}};var rn=class{get isTouch(){return typeof this._maxTouchPoints=="number"?this._maxTouchPoints>1:"ontouchstart"in window}get maxTouchPoints(){return this._maxTouchPoints}get height(){return this._height}get width(){return this._width}get screenHeight(){return this._screenHeight}get screenWidth(){return this._screenWidth}get pixelRatio(){return this._pixelRatio}get isHDR(){return this._isHdr}get colorDepth(){return this._colorDepth}detect(){var t;let{maxTouchPoints:e}=navigator;try{this._maxTouchPoints=e!=null?e:0,this._isHdr=!!((t=matchMedia("(dynamic-range: high)"))!=null&&t.matches),this._colorDepth=screen.colorDepth}catch(i){console.error(i)}try{this._pixelRatio=window.devicePixelRatio||1,this._height=screen.height,this._width=screen.width,this._height=screen.height,this._screenHeight=this._height*this._pixelRatio,this._screenWidth=this._width*this._pixelRatio}catch(i){console.error(i)}}};var Je=()=>window.ManagedMediaSource||window.MediaSource,an=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},_g=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Ng=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;var vL=document.createElement("video"),SL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',yL='video/mp4; codecs="hev1.1.6.L93.B0"',Fg='video/webm; codecs="vp09.00.10.08"',qg='video/webm; codecs="av01.0.00M.08"',TL='audio/mp4; codecs="mp4a.40.2"',IL='audio/webm; codecs="opus"',Ug,EL=()=>P(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(C(A({},a),{video:C(A({},a.video),{contentType:qg})})),window.navigator.mediaCapabilities.decodingInfo(C(A({},a),{video:C(A({},a.video),{contentType:Fg})}))]);Ug={DASH_WEBM_AV1:e,DASH_WEBM:t}});EL().catch(a=>{console.log(vL),console.error(a)});var sn=class{constructor(e,t){this._deviceChecker=e,this._browserChecker=t}get protocols(){return this._protocols}get containers(){return this._containers}get codecs(){return this._codecs}get webmDecodingInfo(){return Ug}get supportedCodecs(){return Object.keys(this._codecs).filter(e=>this._codecs[e])}get nativeHlsSupported(){return this._nativeHlsSupported}detect(){var e,t,i,r,s,n,o,u,l,c,d,h,p,m,b,g,v,S,y,E;this._video=document.createElement("video");try{this._protocols={mms:an(),mse:_g(),hls:!!((t=(e=this._video).canPlayType)!=null&&t.call(e,"application/x-mpegurl")||(r=(i=this._video).canPlayType)!=null&&r.call(i,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},this._containers={mp4:!!((n=(s=this._video).canPlayType)!=null&&n.call(s,"video/mp4")),webm:!!((u=(o=this._video).canPlayType)!=null&&u.call(o,"video/webm")),cmaf:!0};let I=!!((c=(l=Je())==null?void 0:l.isTypeSupported)!=null&&c.call(l,SL)),$=!!((h=(d=Je())==null?void 0:d.isTypeSupported)!=null&&h.call(d,yL)),O=!!((m=(p=Je())==null?void 0:p.isTypeSupported)!=null&&m.call(p,TL));this._codecs={h264:I,h265:$,vp9:!!((g=(b=Je())==null?void 0:b.isTypeSupported)!=null&&g.call(b,Fg)),av1:!!((S=(v=Je())==null?void 0:v.isTypeSupported)!=null&&S.call(v,qg)),aac:O,opus:!!((E=(y=Je())==null?void 0:y.isTypeSupported)!=null&&E.call(y,IL)),mpeg:(I||$)&&O},this._nativeHlsSupported=this._protocols.hls&&this._containers.mp4}catch(I){console.error(I)}this.destroyVideoElement()}destroyVideoElement(){var t;if(!this._video)return;if(this._video.pause(),this._video.currentTime=0,this._video.removeAttribute("src"),this._video.src="",this._video.load(),this._video.remove){this._video.remove(),this._video=null;return}this._video.parentNode&&this._video.parentNode.removeChild(this._video);let e=this._video.cloneNode(!1);(t=this._video.parentNode)==null||t.replaceChild(e,this._video),this._video=null}};var Hg="audio/mpeg",nn=class{supportMp3(){return this._codecs.mp3&&this._containers.mpeg}detect(){var e,t,i,r;this._audio=document.createElement("audio");try{this._containers={mpeg:!!((t=(e=this._audio).canPlayType)!=null&&t.call(e,Hg))},this._codecs={mp3:!!((r=(i=Je())==null?void 0:i.isTypeSupported)!=null&&r.call(i,Hg))}}catch(s){console.error(s)}this.destroyAudioElement()}destroyAudioElement(){var t;if(!this._audio)return;if(this._audio.pause(),this._audio.currentTime=0,this._audio.removeAttribute("src"),this._audio.src="",this._audio.load(),this._audio.remove){this._audio.remove(),this._audio=null;return}this._audio.parentNode&&this._audio.parentNode.removeChild(this._audio);let e=this._audio.cloneNode(!1);(t=this._audio.parentNode)==null||t.replaceChild(e,this._audio),this._audio=null}};import{ValueSubject as xL}from"@vkontakte/videoplayer-shared/es2015";var ol=class{constructor(){this.isInited$=new xL(!1);this._displayChecker=new rn,this._deviceChecker=new tn(this._displayChecker),this._browserChecker=new en,this._videoChecker=new sn(this._deviceChecker,this._browserChecker),this._audioChecker=new nn,this.detect()}get display(){return this._displayChecker}get device(){return this._deviceChecker}get browser(){return this._browserChecker}get video(){return this._videoChecker}get audio(){return this._audioChecker}detect(){return P(this,null,function*(){this._displayChecker.detect(),this._deviceChecker.detect(),this._browserChecker.detect(),this._videoChecker.detect(),this._audioChecker.detect(),this.isInited$.next(!0)})}},q=new ol;var $e=a=>{let e=w=>Le(a,w).pipe(ll(void 0)),t=new $L,i=()=>t.unsubscribe(),s=ul(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>Le(a,w))).pipe(Ot(w=>w.type==="ended"?a.readyState<2:a.readyState<3),PL()),n=ul(Le(a,"progress"),Le(a,"timeupdate")).pipe(Ot(()=>Og(a.buffered,a.currentTime))),o=q.browser.isSafari?AL({play:e("play").pipe(kL()),playing:e("playing")}).pipe(ll(void 0)):e("playing"),u=Le(a,"volumechange").pipe(Ot(()=>({muted:a.muted,volume:a.volume}))),l=Le(a,"ratechange").pipe(Ot(()=>a.playbackRate)),c=Le(a,"error").pipe(jr(()=>!!(a.error||a.played.length)),Ot(()=>{var H;let w=a.error;return{id:w?`MediaError#${w.code}`:"HtmlVideoError",category:LL.VIDEO_PIPELINE,message:w?w.message:"Error event from HTML video element",thrown:(H=a.error)!=null?H:void 0}})),d=Le(a,"timeupdate").pipe(Ot(()=>a.currentTime)),h=new wL,p=.3,m;t.add(d.subscribe(w=>{a.loop&&jg(m)&&jg(w)&&m>=a.duration-p&&w<=p&&h.next(m),m=w}));let b=e("pause").pipe(jr(()=>!a.error&&m!==a.duration)),g=Le(a,"enterpictureinpicture"),v=Le(a,"leavepictureinpicture"),S=new Qg(Vg(a));t.add(g.subscribe(()=>S.next(!0))),t.add(v.subscribe(()=>S.next(!1)));let y=new Qg(nl(a)),E=Le(a,"fullscreenchange");t.add(E.pipe(Ot(()=>nl(a))).subscribe(y));let I=.1,$=1e3,O=Le(a,"timeupdate").pipe(jr(w=>a.duration-a.currentTime<I)),F=ul(O.pipe(jr(w=>!a.loop)),Le(a,"ended")).pipe(RL($),ll(void 0)),z=O.pipe(jr(w=>a.loop));return{playing$:o,pause$:b,canplay$:e("canplay"),ended$:F,looped$:h,loopExpected$:z,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:Le(a,"durationchange").pipe(Ot(()=>a.duration)),isBuffering$:s,currentBuffer$:n,volumeState$:u,playbackRateState$:l,inPiP$:S,inFullscreen$:y,enterPip$:g,leavePip$:v,destroy:i}};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 Ft=B(Nt(),1),ov=B(qe(),1),ln=B(_i(),1);import{isNonNullable as Ee,isNullable as rv,now as uv,isHigher as av,isHigherOrEqual as hl,isInvariantQuality as sv,isLowerOrEqual as ml,videoSizeToQuality as UL,assertNotEmptyArray as lv,assertNonNullable as HL}from"@vkontakte/videoplayer-shared/es2015";var cl=!1,vt={},Jg=a=>{cl=a},Zg=()=>{vt={}},ev=a=>{a(vt)},Qr=(a,e)=>{var t;cl&&(vt.meta=(t=vt.meta)!=null?t:{},vt.meta[a]=e)},Ie=class{constructor(e){this.name=e}next(e){var i,r;if(!cl)return;vt.series=(i=vt.series)!=null?i:{};let t=(r=vt.series[this.name])!=null?r:[];t.push([Date.now(),e]),vt.series[this.name]=t}};import{isHigher as FL,isHigherOrEqual as YN,isLower as tv,isLowerOrEqual as zN,isNonNullable as on,isNullable as qL,videoHeightToQuality as un}from"@vkontakte/videoplayer-shared/es2015";function dl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!a.max&&a.min===e?"high_quality":!a.min&&a.max===t?"traffic_saving":"unknown"}function pl({limits:a,highQualityLimit:e,trafficSavingLimit:t}){return!!a&&dl({limits:a,highQualityLimit:e,trafficSavingLimit:t})==="high_quality"}function Gr({limits:a,highestAvailableQuality:e,lowestAvailableQuality:t}){return qL(a)||on(a.min)&&on(a.max)&&tv(a.max,a.min)||on(a.min)&&e&&FL(a.min,e)||on(a.max)&&t&&tv(a.max,t)}function iv({limits:a,highestAvailableHeight:e,lowestAvailableHeight:t}){return Gr({limits:{max:a!=null&&a.max?un(a.max):void 0,min:a!=null&&a.min?un(a.min):void 0},highestAvailableQuality:e?un(e):void 0,lowestAvailableQuality:t?un(t):void 0})}var jL=new Ie("best_bitrate"),cv=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var fl=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Wr=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=uv()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},dv='Assertion "ABR Tracks is empty array" failed',cn=(a,e,t,i)=>{var u;let r=[...e].sort(fl(1)),s=[...t].sort(fl(1)),n=s.filter(l=>Ee(l.bitrate)&&Ee(a.bitrate)?a.bitrate/l.bitrate>i:!0),o=(u=(0,Ft.default)(s,Math.round(s.length*r.indexOf(a)/(r.length+1))))!=null?u:(0,Ft.default)(s,-1);return o&&(0,ov.default)(n,o)?o:n.length?(0,Ft.default)(n,-1):(0,Ft.default)(s,0)},nv=a=>"quality"in a,pv=(a,e,t,i)=>{var n;let r=Ee((n=i==null?void 0:i.last)==null?void 0:n.bitrate)&&Ee(t==null?void 0:t.bitrate)&&i.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&i&&i.history[t.id]&&uv()-i.history[t.id]<=r&&(!i.last||t.id!==i.last.id);if(t!=null&&t.id&&i&&!s&&i.recordSelection(t),s&&(i!=null&&i.last)){let o=i.last;i==null||i.recordSwitch(o);let u=nv(o)?"video":"audio",l=nv(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return i==null||i.recordSwitch(t),t},jL=(a,e)=>Math.log(e)/Math.log(a),QL=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&q.display.pixelRatio){let s=q.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,c=jL(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return pl({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,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}},qt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:m,panelSize:b})=>{var ee,le,T,L,K;uv(a,cv);let{containerSizeFactor:g,containerSizeLimit:v}=QL({container:e,tuning:i,limits:r,panelSize:b}),S=i.considerPlaybackRate&&Ee(o)?o:1,y=a.filter(x=>!av(x.quality)).sort((x,D)=>rv(x.quality,D.quality)?-1:1),E=(ee=(0,Ft.default)(y,-1))==null?void 0:ee.quality,I=(le=(0,Ft.default)(y,0))==null?void 0:le.quality,$=Gr({limits:r,lowestAvailableQuality:E,highestAvailableQuality:I}),V=S*lv(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),F={},w=y.filter(x=>{let D=!0;if(v)if(x.size)D=x.size.width<=v.width&&x.size.height<=v.height;else{let pt=v&&qL(v);D=pt?ml(x.quality,pt):!0}if(!D)return F[x.quality]="FitsContainer",!1;let me=p||t,Ti=Ee(me)&&isFinite(me)&&Ee(x.bitrate)?me-s>=x.bitrate*V:!0,dt=pl({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&(r==null?void 0:r.min)===x.quality;if(!Ti&&!dt)return F[x.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Ee(i.minBufferToSwitchUp)&&u&&!av(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&rv(x.quality,u.quality))return F[x.quality]="Buffer",!1;if(!!d&&hl(x.quality,d)&&!dt)return F[x.quality]="DroppedFramesLimit",!1;if(!!h&&hl(x.quality,h)&&!dt)return F[x.quality]="StallsLimit",!1;let we=$||(iv(r==null?void 0:r.max)||ml(x.quality,r.max))&&(iv(r==null?void 0:r.min)||hl(x.quality,r.min)),tt=Ee(c)&&!c?ml(x.quality,i.backgroundVideoQualityLimit):!0;return!we||!tt?(F[x.quality]="FitsQualityLimits",!1):!0})[0];w&&w.bitrate&&HL.next(w.bitrate);let H=(T=w!=null?w:(0,Ft.default)(y,-1))!=null?T:a[0],M=l==null?void 0:l.last,j=dv(i,m,H,l);return Ee(l)&&j.quality!==(M==null?void 0:M.quality)&&m({message:`
9
+ `}),o}return i==null||i.recordSwitch(t),t},QL=(a,e)=>Math.log(e)/Math.log(a),GL=({tuning:a,container:e,limits:t,panelSize:i})=>{let r=a.containerSizeFactor;if(i)return{containerSizeLimit:i,containerSizeFactor:r};if(a.usePixelRatio&&q.display.pixelRatio){let s=q.display.pixelRatio;if(a.pixelRatioMultiplier)r*=a.pixelRatioMultiplier*(s-1)+1;else{let n=a.pixelRatioLogBase,[o=0,u=0,l=0]=a.pixelRatioLogCoefficients,c=QL(n,o*s+u)+l;Number.isFinite(c)&&(r*=c)}}return pl({highQualityLimit:a.highQualityLimit,trafficSavingLimit:a.trafficSavingLimit,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}},qt=(a,{container:e,estimatedThroughput:t,tuning:i,limits:r,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:h,stallsPredictedThroughput:p,abrLogger:m,panelSize:b})=>{var ee,le,T,L,K;lv(a,dv);let{containerSizeFactor:g,containerSizeLimit:v}=GL({container:e,tuning:i,limits:r,panelSize:b}),S=i.considerPlaybackRate&&Ee(o)?o:1,y=a.filter(x=>!sv(x.quality)).sort((x,D)=>av(x.quality,D.quality)?-1:1),E=(ee=(0,Ft.default)(y,-1))==null?void 0:ee.quality,I=(le=(0,Ft.default)(y,0))==null?void 0:le.quality,$=Gr({limits:r,lowestAvailableQuality:E,highestAvailableQuality:I}),O=S*cv(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),F={},w=y.filter(x=>{let D=!0;if(v)if(x.size)D=x.size.width<=v.width&&x.size.height<=v.height;else{let pt=v&&UL(v);D=pt?ml(x.quality,pt):!0}if(!D)return F[x.quality]="FitsContainer",!1;let me=p||t,Ti=Ee(me)&&isFinite(me)&&Ee(x.bitrate)?me-s>=x.bitrate*O:!0,dt=pl({highQualityLimit:i.highQualityLimit,trafficSavingLimit:i.trafficSavingLimit,limits:r})&&(r==null?void 0:r.min)===x.quality;if(!Ti&&!dt)return F[x.quality]="FitsThroughput",!1;if(i.lazyQualitySwitch&&Ee(i.minBufferToSwitchUp)&&u&&!sv(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&av(x.quality,u.quality))return F[x.quality]="Buffer",!1;if(!!d&&hl(x.quality,d)&&!dt)return F[x.quality]="DroppedFramesLimit",!1;if(!!h&&hl(x.quality,h)&&!dt)return F[x.quality]="StallsLimit",!1;let we=$||(rv(r==null?void 0:r.max)||ml(x.quality,r.max))&&(rv(r==null?void 0:r.min)||hl(x.quality,r.min)),tt=Ee(c)&&!c?ml(x.quality,i.backgroundVideoQualityLimit):!0;return!we||!tt?(F[x.quality]="FitsQualityLimits",!1):!0})[0];w&&w.bitrate&&jL.next(w.bitrate);let H=(T=w!=null?w:(0,Ft.default)(y,-1))!=null?T:a[0],M=l==null?void 0:l.last,j=pv(i,m,H,l);return Ee(l)&&j.quality!==(M==null?void 0:M.quality)&&m({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
12
  ${a.map(x=>{var D,me;return`{ id: ${x.id}, quality: ${x.quality}, bitrate: ${x.bitrate}, size: ${(D=x.size)==null?void 0:D.width}:${(me=x.size)==null?void 0:me.height} }`}).join(`
@@ -25,7 +25,7 @@ var tI=Object.create;var ro=Object.defineProperty,iI=Object.defineProperties,rI=
25
25
  playbackRate: ${o},
26
26
  playbackRateFactor: ${S},
27
27
  forwardBufferHealth: ${n},
28
- bitrateFactor: ${V},
28
+ bitrateFactor: ${O},
29
29
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
30
30
  droppedVideoMaxQualityLimit: ${d},
31
31
  stallsVideoMaxQualityLimit: ${h},
@@ -39,7 +39,7 @@ var tI=Object.create;var ro=Object.defineProperty,iI=Object.defineProperties,rI=
39
39
 
40
40
  [best video track] ${w==null?void 0:w.quality}
41
41
  [selected video track] ${j==null?void 0:j.quality}
42
- `}),j},pv=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{uv(t,cv);let c=r.considerPlaybackRate&&Ee(s)?s:1,d=[...t].sort(fl(-1)),h=a.bitrate;UL(h);let p=c*lv(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=cn(a,e,t,r.minVideoAudioRatio),g=l||i;Ee(g)&&isFinite(g)&&(m=d.find(y=>Ee(y.bitrate)&&Ee(b==null?void 0:b.bitrate)?g-h>=y.bitrate*p&&y.bitrate>=b.bitrate:!1)),m||(m=b);let v=o==null?void 0:o.last,S=m&&dv(r,u,m,o);return Ee(o)&&(S==null?void 0:S.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
42
+ `}),j},hv=(a,e,t,{estimatedThroughput:i,tuning:r,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{lv(t,dv);let c=r.considerPlaybackRate&&Ee(s)?s:1,d=[...t].sort(fl(-1)),h=a.bitrate;HL(h);let p=c*cv(n!=null?n:.5,r.bitrateAudioFactorAtEmptyBuffer,r.bitrateAudioFactorAtFullBuffer),m,b=cn(a,e,t,r.minVideoAudioRatio),g=l||i;Ee(g)&&isFinite(g)&&(m=d.find(y=>Ee(y.bitrate)&&Ee(b==null?void 0:b.bitrate)?g-h>=y.bitrate*p&&y.bitrate>=b.bitrate:!1)),m||(m=b);let v=o==null?void 0:o.last,S=m&&pv(r,u,m,o);return Ee(o)&&(S==null?void 0:S.bitrate)!==(v==null?void 0:v.bitrate)&&u({message:`
43
43
  [AUDIO TRACKS ABR]
44
44
  [available audio tracks]
45
45
  ${t.map(y=>`{ id: ${y.id}, bitrate: ${y.bitrate} }`).join(`
@@ -60,14 +60,14 @@ var tI=Object.create;var ro=Object.defineProperty,iI=Object.defineProperties,rI=
60
60
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
61
61
 
62
62
  [selected audio track] ${S==null?void 0:S.id}
63
- `}),S};var de=a=>new URL(a).hostname;import{assertNever as Ev,assertNonNullable as xv,combine as p$,debounce as h$,ErrorCategory as Pv,filter as wv,filterChanged as m$,isNonNullable as yl,map as fn,merge as Av,observableFrom as f$,once as b$,Subscription as g$,ValueSubject as Tl,videoQualityToHeight as kv,videoSizeToQuality as v$}from"@vkontakte/videoplayer-shared/es2015";var Sv=B(Nt(),1);var mv=B(qe(),1);var hv=a=>{if(a instanceof DOMException&&(0,mv.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"))},Me=(a,e)=>P(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(i){if(!hv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{yield a.play()}catch(r){return hv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as pn,isNullable as YL,assertNonNullable as Kr}from"@vkontakte/videoplayer-shared/es2015";var bv=B(zi(),1);import{isNonNullable as fv,assertNonNullable as dn,now as GL}from"@vkontakte/videoplayer-shared/es2015";function pe(){return GL()}function bl(a){return pe()-a}function gl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(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 gv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Xi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;dn(c);let M=bl(c),j;if(M<b){j=b-M,setTimeout(g,j);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,$()},v=M=>(s=M,H),S=M=>(d=M,H),y=()=>(p="json",H),E=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},I=M=>(h=M,H),$=()=>{c=pe(),n=new r,n.open("get",a);let M=0,j,ee=0,le=()=>(dn(c),Math.max(c,Math.max(j||0,ee||0)));if(s&&n.addEventListener("progress",T=>{let L=pe();s.updateChunk&&T.loaded>M&&(s.updateChunk(le(),T.loaded-M),M=T.loaded,j=L)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;dn(n);let T=n.status;if(T>=200&&T<300){let{response:L,responseType:K}=n,x=L==null?void 0:L.byteLength;if(typeof x=="number"&&s){let D=x-M;D&&s.updateChunk&&s.updateChunk(le(),D)}K==="json"&&(!L||!(0,bv.default)(L).length)?E():(d&&d(),e(L))}else E()}),n.addEventListener("error",()=>{E()}),h){let T=()=>{dn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ee=pe(),n.removeEventListener("readystatechange",T))};n.addEventListener("readystatechange",T)}return n.responseType=p,n.send(),H},H={withBitrateReporting:v,withParallel:I,withJSONResponse:y,withRetryCount:M=>(l=M,H),withRetryInterval:(M,j)=>(fv(M)&&(b=M),fv(j)&&(m=j),H),withTimeout:M=>(o=M,H),withFinally:S,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return H}var Yr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/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(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var vv=B(zi(),1);var zr=class{constructor(e,t,i,r,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=i,this.MAX_PARALLEL_REQUESTS=r,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 i=pe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=pe()-i,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=Xi(t,s,()=>r("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=pe()}_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=pe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,vv.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,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}`),i(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=i,s._retryCB=r,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 zL}from"@vkontakte/videoplayer-shared/es2015";var hn=1e4,vl=3;var KL=6e4,XL=10,JL=1,ZL=500,Xr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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 zL,this.chunkRateEstimator=new Yr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=gl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=gl(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(q.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!tv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,Sv.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||pn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{gv(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 zr(vl,hn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let E=s&&(!c||c===this.rep);return E||t("Not running!"),E},h=(E,I,$)=>{u&&u.abort(),u=Xi(this.urlResolver.resolve(E,!1),I,$,()=>this._retryCallback()).withTimeout(hn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(vl).withFinally(()=>{u=null}).send()},p=(E,I,$)=>{Kr(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let I=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${I}=>${E}`),i.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let $=pe()-1e4,V=0;for(let z=0;z<this.bufferStates.length;z++){let w=this.bufferStates[z];E=Math.min(E,w.buf),w.ts<$&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${E} drop=${V} jitter=${this.sourceJitter}`);let F=E-JL;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?m(1.15):F>1?m(1.1):F>.3?m(1.05):m(1)}},v=E=>{let I,$=()=>I&&I.start?I.start.length:0,V=T=>I.start[T]/1e3,F=T=>I.dur[T]/1e3,z=T=>I.fragIndex+T,w=(T,L)=>({chunkIdx:z(T),startTS:V(T),dur:F(T),discontinuity:L}),H=()=>{let T=0;if(I&&I.dur){let L=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,K=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,x=L;this.sourceJitter>1&&(x+=this.sourceJitter-1);let D=I.dur.length-1;for(;D>=0&&(x-=I.dur[D],!(x<=0));--D);T=Math.min(D,I.dur.length-1-K),T=Math.max(T,0)}return w(T,!0)},M=T=>{let L=$();if(!(L<=0)){if(pn(T)){for(let K=0;K<L;K++)if(V(K)>T)return w(K)}return H()}},j=T=>{let L=$(),K=T?T.chunkIdx+1:0,x=K-I.fragIndex;if(!(L<=0)){if(!T||x<0||x-L>XL)return t(`Resync: offset=${x} bChunks=${L} chunk=`+JSON.stringify(T)),H();if(!(x>=L))return w(K-I.fragIndex,!1)}},ee=(T,L,K)=>{l&&l.abort(),l=Xi(this.urlResolver.resolve(T,!0,this.lowLatency),L,K,()=>this._retryCallback()).withTimeout(hn).withRetryCount(vl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(T,L)=>{ee(E,K=>{if(!d())return;I=K;let x=!!I.lowLatency;x!==this.lowLatency&&b(x);let D=0;for(let me=0;me<I.dur.length;++me)D+=I.dur[me];D>0&&(Kr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(D/I.dur.length)),r({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,T(M(L))},()=>this._handleNetworkError())},nextChunk:j}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Kr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:I,logger:$}=this.params,V=v(e.jidxUrl),F,z,w,H,M=0,j,ee,le,T=()=>{j&&(clearTimeout(j),j=void 0);let W=Math.max(ZL,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=M+W,Pe=pe(),we=Math.min(1e4,ye-Pe);M=Pe;let tt=()=>{l||d()&&V.seek(()=>{d()&&(M=pe(),L(),T())})};we>0?j=window.setTimeout(()=>{this.paused?T():tt()},we):tt()},L=()=>{let W;for(;W=V.nextChunk(H);)H=W,Ti(W);let ye=V.nextChunk(w);if(ye){if(w&&ye.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?T():(S(),this._initPlayerWith(e));return}me(ye)}else T()},K=(W,ye)=>{if(!d()||!this.sourceBuffer)return;let Pe,we,tt,pt=Pt=>{window.setTimeout(()=>{d()&&K(W,ye)},Pt)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),pt(100);else{let Pt=pe(),zt=I.currentTime;!this.paused&&I.buffered.length>1&&ee===zt&&Pt-le>500&&($("Stall suspected; trying to fix"),this._fixupStall()),ee!==zt&&(ee=zt,le=Pt);let Ii=this._getBufferSizeSec();if(Ii>30)$(`Buffered ${Ii} seconds; delaying appendBuffer`),pt(2e3);else try{this.sourceBuffer.appendBuffer(W),this.videoPlayStarted?(this.bufferStates.push({ts:Pt,buf:Ii}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(cr){if(cr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(Pe=this.sourceBuffer.buffered.start(0),we=zt,we-Pe>4&&this.sourceBuffer.remove(Pe,we-3)),pt(1e3);else throw cr}}},x=()=>{z&&F&&($([`Appending chunk, sz=${z.byteLength}:`,JSON.stringify(w)]),K(z,function(){z=null,L()}))},D=W=>e.fragUrlTemplate.replace("%%id%%",W.chunkIdx),me=W=>{d()&&p(D(W),(ye,Pe)=>{if(d()){if(Pe/=1e3,z=ye,w=W,n=W.startTS,Pe){let we=Math.min(10,W.dur/Pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}x()}},()=>this._handleNetworkError())},Ti=W=>{d()&&(Kr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(D(W),!1)))},dt=W=>{d()&&(e.cachedHeader=W,K(W,()=>{F=!0,x()}))};s=!0,V.seek(W=>{if(d()){if(M=pe(),!W){T();return}H=W,!YL(E)||W.startTS>E?me(W):(w=W,L())}},E),e.cachedHeader?dt(e.cachedHeader):h(e.headerUrl,dt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),pn(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Kr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return pn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=pe();if(this.chunkRateEstimator.addInterval(h,m,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&bl(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=pe();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Xi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(hn).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;Me(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,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):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},KL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Iv=B(_i(),1);import{debounce as e$,filter as yv,fromEvent as t$,interval as i$,isHigher as r$,isInvariantQuality as a$,isLower as s$,merge as n$,Subject as Tv,Subscription as o$}from"@vkontakte/videoplayer-shared/es2015";var Sl=class{constructor(){this.onDroopedVideoFramesLimit$=new Tv;this.subscription=new o$;this.playing=!1;this.tracks=[];this.forceChecker$=new Tv;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&&!a$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&r$(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((n=this.limitCounts[this.currentQuality])!=null?n:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(e,t)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.tracks=e.tracks,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(t$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=i$(this.droppedFramesChecker.checkTime).pipe(yv(()=>this.playing),yv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(e$(this.droppedFramesChecker.checkTime)),i=n$(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,Iv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>s$(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},mn=Sl;import{map as u$,Observable as l$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as c$}from"@vkontakte/videoplayer-shared/es2015";var Jr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var d$=(a,e)=>new l$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Jr()))},A(A({},i),e));r.observe(a);let s=c$(document,"visibilitychange").pipe(u$(n=>!document.hidden||Jr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),je=d$;var S$=["paused","playing","ready"],y$=["paused","playing","ready"],Zr=class{constructor(e){this.subscription=new g$;this.videoState=new _("stopped");this.representations$=new Tl([]);this.droppedFramesManager=new mn;this.maxSeekBackTime$=new Tl(1/0);this.zeroTime$=new Tl(void 0);this.liveOffset=new hi;this._dashCb=e=>{var t,i,r,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:Pv.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=(i=_t(u.name))!=null?i:v$(u.video),d=u.bitrate/1e3,h=A({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.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),yl(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(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Il.default)(y$,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Il.default)(S$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ge(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ge(this.params.source.url,u))}return;default:return Ev(e)}};this.textTracksManager=new He(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:Pv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(Av(this.videoState.stateChangeStarted$.pipe(fn(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(fn(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ae(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(de(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 i=$e(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(fn(r=>r.map(({track:s})=>s)),wv(r=>!!r.length),b$()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(m$(),fn(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(p$({zeroTime:this.zeroTime$.pipe(wv(yl)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Re(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ue(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&kv(r),min:s&&kv(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((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 Ev(r.to)}},t)).add(Av(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,f$(["init"])).pipe(h$(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),ke(this.video)}createLiveDashPlayer(){let e=new Xr({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&yl(t)?t:qt(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,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=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;xv(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;xv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ge(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Rv=Zr;var Jy=B(qe(),1);var Ji=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as tC,assertNonNullable as iC,debounce as rC,ErrorCategory as Yy,filter as zy,filterChanged as qa,fromEvent as aC,isNonNullable as Ky,map as lc,merge as On,observableFrom as cc,once as Xy,Subscription as sC}from"@vkontakte/videoplayer-shared/es2015";var bn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];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}},Zi=class extends bn{constructor(){super(),this.listeners||bn.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)}},ea=class{constructor(){Object.defineProperty(this,"signal",{value:new Zi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ea.prototype[Symbol.toStringTag]="AbortController",Zi.prototype[Symbol.toStringTag]="AbortSignal");function gn(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 El(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!gn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var ta=gn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Lv=ta?El({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ta?Lv.fetch:window.fetch,Aq=ta?Lv.Request:window.Request,ve=ta?ea:window.AbortController,kq=ta?Zi:window.AbortSignal;var sc=B(Pl(),1);var bS=B(fS(),1);import{ErrorCategory as ra}from"@vkontakte/videoplayer-shared/es2015";var gS=a=>{if(!a)return{id:"EmptyResponse",category:ra.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ra.NETWORK,message:`UV Error ${a}`};let e=(0,bS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ra.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:ra.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ra.PARSER,message:"Response is valid XML, but parser failed"}};var Ut=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as ic,assertNonNullable as sr,combine as nr,ErrorCategory as ct,filter as Rn,filterChanged as _a,flattenObject as Na,fromEvent as It,getTraceSubscriptionMethod as BD,interval as rc,isNonNullable as Fa,isNullable as qy,map as or,merge as Si,now as ac,Subject as Ln,Subscription as Uy,tap as _D,throttle as ND,ValueSubject as ie}from"@vkontakte/videoplayer-shared/es2015";var Sn=B(qe(),1),rr=B(Nt(),1),yn=B(Pl(),1);var sM=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},nM=a=>window.clearTimeout(a),vS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),SS=!vS(window.requestIdleCallback)||!vS(window.cancelIdleCallback),Ll=SS?sM:window.requestIdleCallback,aa=SS?nM:window.cancelIdleCallback;var ky=B(Ks(),1);import{assertNever as oM,ErrorCategory as yS,Subject as TS}from"@vkontakte/videoplayer-shared/es2015";var uM=18,IS=!1;try{IS=q.browser.isSafari&&!!q.browser.safariVersion&&q.browser.safariVersion<=uM}catch(a){console.error(a)}var $l=class{constructor(e){this.bufferFull$=new TS;this.error$=new TS;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:yS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return P(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return P(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return P(this,null,function*(){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};IS&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:yS.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:oM(t)}}},ES=$l;var Ml=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 jt,assertNonNullable as De,ErrorCategory as Tt,fromEvent as zl,getExponentialDelay as Kl,isNonNullable as ir,isNullable as Se,now as vn,once as xD,Subject as PD,Subscription as wD,ValueSubject as bi}from"@vkontakte/videoplayer-shared/es2015";var Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),i>e.byteLength-e.byteOffset&&(this.size32=NaN);let r=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,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var er=class extends Q{};var sa=class extends Q{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var na=class extends Q{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var oa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var te=class extends Q{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ua=class extends te{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 la=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ca=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var mi=class extends te{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 i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var da=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends te{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 ma=class extends te{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var fa=class extends te{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ba=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends te{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 va=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends te{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ta=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends te{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 Ea=class extends te{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var xa=class extends te{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Pa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends te{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Aa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var cM={ftyp:na,moov:oa,mvhd:ua,moof:la,mdat:ca,sidx:mi,trak:da,mdia:ba,mfhd:ya,tkhd:ga,traf:Ta,tfhd:Ia,tfdt:Ea,trun:xa,minf:va,sv3d:pa,st3d:ha,prhd:ma,proj:Sa,equi:fa,uuid:sa,stbl:Pa,stsd:wa,avc1:Aa,unknown:er},St=class a{constructor(e={}){this.options=A({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=cM[e];return i?new i(t,new a):new er(t,new a)}};var Ht=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var pM=new TextDecoder("ascii"),hM=a=>pM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",mM=a=>{let e=new mi(a,new St),t=e.earliestPresentationTime/e.timescale*1e3,i=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:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},fM=(a,e)=>{let i=new St().parse(a),r=new Ht(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.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)},bM=a=>{let t=new St().parse(a),i=new Ht(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},gM=a=>{var r;let t=new St().parse(a);return(r=new Ht(t).find("sidx"))==null?void 0:r.timescale},vM=(a,e)=>{let i=new St().parse(a),s=new Ht(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},SM=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}}},i=new St().parse(a),r=new Ht(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},xS={validateData:hM,parseInit:SM,getIndexRange:()=>{},parseSegments:mM,parseFeedableSegmentChunk:fM,getChunkEndTime:vM,getServerLatencyTimestamps:bM,getTimescaleFromIndex:gM};var Ra=B(qe(),1);import{assertNonNullable as Cl,isNonNullable as kS,isNullable as TM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as yM}from"@vkontakte/videoplayer-shared/es2015";var PS={440786851:{type:"master"},17030:{type:"uint"},17143:{type:"uint"},17138:{type:"uint"},17139:{type:"uint"},17026:{type:"string"},17031:{type:"uint"},17029:{type:"uint"},236:{type:"binary"},408125543:{type:"master"},290298740:{type:"master"},19899:{type:"master"},21419:{type:"binary"},21420:{type:"uint"},357149030:{type:"master"},2807729:{type:"uint"},17545:{type:"float"},374648427:{type:"master"},174:{type:"master"},224:{type:"master"},30320:{type:"master"},30321:{type:"uint"},30322:{type:"master"},272869232:{type:"master"},524531317:{type:"master"},231:{type:"uint"},22612:{type:"master"},22743:{type:"uint"},167:{type:"uint"},171:{type:"uint"},163:{type:"binary"},160:{type:"master"},175:{type:"binary"},423732329:{type:"master"},307544935:{type:"master"},475249515:{type:"master"},187:{type:"master"},179:{type:"uint"},183:{type:"master"},247:{type:"uint"},241:{type:"uint"},240:{type:"uint"},178:{type:"uint"},21368:{type:"uint"},234:{type:"uint"},219:{type:"master"},150:{type:"uint"}},wS=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 i=ka(a,t),r=i in PS,s=r?PS[i].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=ka(u),d=l*at(2,(o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},ka=(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},Ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ka(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:yM(e)}},fi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=wS(i);if(!e(r))return;r.type==="master"&&fi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},AS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=wS(a);return fi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=Ze(o,n):s===17026?t=Ze(o,n):s===17029&&(i=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var RS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],IM=[231,22612,22743,167,171,163,160,175],EM=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return fi(a,({tag:h,type:p,value:m,valueSize:b})=>{if(h===21419){let g=Ze(m,p);l=ka(g)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=Ze(m,p):h===17545?r=Ze(m,p):h===21420&&l===475249515?u=Ze(m,p):h===374648427?fi(m,({tag:g,type:v,value:S})=>g===30321?(c=Ze(S,v)===1,!1):!0):s&&n&&(0,Ra.default)(RS,h)&&(o=!0),!o}),Cl(e,"Failed to parse webm Segment start"),Cl(t,"Failed to parse webm Segment end"),Cl(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},xM=a=>{if(TM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},PM=(a,e)=>{let t=!1,i=!1,r=o=>kS(o.time)&&kS(o.position),s=[],n;return fi(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ze(l,u));break;case 183:break;case 241:n&&(n.position=Ze(l,u));break;default:t&&(0,Ra.default)(RS,o)&&(i=!0)}return!(t&&i)}),n&&r(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}}})},wM=a=>{let e=0,t=!1;try{fi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ra.default)(IM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,Ra.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},LS={validateData:AS,parseInit:EM,getIndexRange:xM,parseSegments:PM,parseFeedableSegmentChunk:wM};var La=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return LS;case"mp4":return xS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Gl=B(KS(),1),Iy=B(_i(),1),Ey=B(py(),1),xy=B(Nt(),1),Wl=B(zi(),1);var hy=B(qe(),1),Fl=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,hy.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as ED,isNullable as yy}from"@vkontakte/videoplayer-shared/es2015";var my=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var fy=a=>{var e;try{let t=TD(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.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=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.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 TD(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
63
+ `}),S};var de=a=>new URL(a).hostname;import{assertNever as xv,assertNonNullable as Pv,combine as h$,debounce as m$,ErrorCategory as wv,filter as Av,filterChanged as f$,isNonNullable as yl,map as fn,merge as kv,observableFrom as b$,once as g$,Subscription as v$,ValueSubject as Tl,videoQualityToHeight as Rv,videoSizeToQuality as S$}from"@vkontakte/videoplayer-shared/es2015";var yv=B(Nt(),1);var fv=B(qe(),1);var mv=a=>{if(a instanceof DOMException&&(0,fv.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"))},Me=(a,e)=>P(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(i){if(!mv(i))return!1;if(e&&e(),t)return console.warn(i),!1;a.muted=!0;try{yield a.play()}catch(r){return mv(r)&&(a.muted=!1,console.warn(r)),!1}}return!0});import{isNonNullable as pn,isNullable as zL,assertNonNullable as Kr}from"@vkontakte/videoplayer-shared/es2015";var gv=B(zi(),1);import{isNonNullable as bv,assertNonNullable as dn,now as WL}from"@vkontakte/videoplayer-shared/es2015";function pe(){return WL()}function bl(a){return pe()-a}function gl(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(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 vv(a,e,t){let i=(...r)=>{t.apply(null,r),a.removeEventListener(e,i)};a.addEventListener(e,i)}function Xi(a,e,t,i){let r=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,h=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;dn(c);let M=bl(c),j;if(M<b){j=b-M,setTimeout(g,j);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new r,$()},v=M=>(s=M,H),S=M=>(d=M,H),y=()=>(p="json",H),E=()=>{if(!u){if(--l>=0){g(),i&&i();return}u=!0,d&&d(),t&&t()}},I=M=>(h=M,H),$=()=>{c=pe(),n=new r,n.open("get",a);let M=0,j,ee=0,le=()=>(dn(c),Math.max(c,Math.max(j||0,ee||0)));if(s&&n.addEventListener("progress",T=>{let L=pe();s.updateChunk&&T.loaded>M&&(s.updateChunk(le(),T.loaded-M),M=T.loaded,j=L)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;dn(n);let T=n.status;if(T>=200&&T<300){let{response:L,responseType:K}=n,x=L==null?void 0:L.byteLength;if(typeof x=="number"&&s){let D=x-M;D&&s.updateChunk&&s.updateChunk(le(),D)}K==="json"&&(!L||!(0,gv.default)(L).length)?E():(d&&d(),e(L))}else E()}),n.addEventListener("error",()=>{E()}),h){let T=()=>{dn(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ee=pe(),n.removeEventListener("readystatechange",T))};n.addEventListener("readystatechange",T)}return n.responseType=p,n.send(),H},H={withBitrateReporting:v,withParallel:I,withJSONResponse:y,withRetryCount:M=>(l=M,H),withRetryInterval:(M,j)=>(bv(M)&&(b=M),bv(j)&&(m=j),H),withTimeout:M=>(o=M,H),withFinally:S,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return H}var Yr=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let i=0,r=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)i+=s.end-s.start,r+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;i+=n;let u=s.bytes*n/o;r+=u,s.start=t,s.bytes-=u}}}if(r>0&&i>0){let s=r*8/(i/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(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Sv=B(zi(),1);var zr=class{constructor(e,t,i,r,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=i,this.MAX_PARALLEL_REQUESTS=r,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 i=pe(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=pe()-i,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=Xi(t,s,()=>r("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=pe()}_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=pe();if(Object.keys(this.activeRequests).length>=e)return!1;let i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Sv.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,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}`),i(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=i,s._retryCB=r,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 KL}from"@vkontakte/videoplayer-shared/es2015";var hn=1e4,vl=3;var XL=6e4,JL=10,ZL=1,e$=500,Xr=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.autoQualityLimits=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 KL,this.chunkRateEstimator=new Yr(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=gl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setAutoQualityLimits(e){this.autoQualityLimits=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=gl(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)==null?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,i=t.buffered.length,r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){let{videoElement:t}=this.params,i,r,s,n=t&&1.62*(q.display.pixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o){s=this.manifest[o];let{max:u,min:l}=this.autoQualityLimits||{};!iv({limits:this.autoQualityLimits,highestAvailableHeight:this.manifest[0].video.height,lowestAvailableHeight:(0,yv.default)(this.manifest,-1).video.height})&&(u&&s.video.height>u||l&&s.video.height<l)||(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!r||s.bitrate>r.bitrate)&&(r=s):(!i||i.bitrate>s.bitrate)&&(i=s))}return r||i}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||pn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:i,videoElement:r,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{vv(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 zr(vl,hn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:i,playerCallback:r}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let E=s&&(!c||c===this.rep);return E||t("Not running!"),E},h=(E,I,$)=>{u&&u.abort(),u=Xi(this.urlResolver.resolve(E,!1),I,$,()=>this._retryCallback()).withTimeout(hn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(vl).withFinally(()=>{u=null}).send()},p=(E,I,$)=>{Kr(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),I,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{let I=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${I}=>${E}`),i.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let $=pe()-1e4,O=0;for(let z=0;z<this.bufferStates.length;z++){let w=this.bufferStates[z];E=Math.min(E,w.buf),w.ts<$&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${E} drop=${O} jitter=${this.sourceJitter}`);let F=E-ZL;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?m(1.15):F>1?m(1.1):F>.3?m(1.05):m(1)}},v=E=>{let I,$=()=>I&&I.start?I.start.length:0,O=T=>I.start[T]/1e3,F=T=>I.dur[T]/1e3,z=T=>I.fragIndex+T,w=(T,L)=>({chunkIdx:z(T),startTS:O(T),dur:F(T),discontinuity:L}),H=()=>{let T=0;if(I&&I.dur){let L=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,K=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,x=L;this.sourceJitter>1&&(x+=this.sourceJitter-1);let D=I.dur.length-1;for(;D>=0&&(x-=I.dur[D],!(x<=0));--D);T=Math.min(D,I.dur.length-1-K),T=Math.max(T,0)}return w(T,!0)},M=T=>{let L=$();if(!(L<=0)){if(pn(T)){for(let K=0;K<L;K++)if(O(K)>T)return w(K)}return H()}},j=T=>{let L=$(),K=T?T.chunkIdx+1:0,x=K-I.fragIndex;if(!(L<=0)){if(!T||x<0||x-L>JL)return t(`Resync: offset=${x} bChunks=${L} chunk=`+JSON.stringify(T)),H();if(!(x>=L))return w(K-I.fragIndex,!1)}},ee=(T,L,K)=>{l&&l.abort(),l=Xi(this.urlResolver.resolve(T,!0,this.lowLatency),L,K,()=>this._retryCallback()).withTimeout(hn).withRetryCount(vl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(T,L)=>{ee(E,K=>{if(!d())return;I=K;let x=!!I.lowLatency;x!==this.lowLatency&&b(x);let D=0;for(let me=0;me<I.dur.length;++me)D+=I.dur[me];D>0&&(Kr(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(D/I.dur.length)),r({name:"index",zeroTime:I.zeroTime,shiftDuration:I.shiftDuration}),this.sourceJitter=I.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,I.jitter/1e3)):1,T(M(L))},()=>this._handleNetworkError())},nextChunk:j}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Kr(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{let{videoElement:I,logger:$}=this.params,O=v(e.jidxUrl),F,z,w,H,M=0,j,ee,le,T=()=>{j&&(clearTimeout(j),j=void 0);let W=Math.max(e$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=M+W,Pe=pe(),we=Math.min(1e4,ye-Pe);M=Pe;let tt=()=>{l||d()&&O.seek(()=>{d()&&(M=pe(),L(),T())})};we>0?j=window.setTimeout(()=>{this.paused?T():tt()},we):tt()},L=()=>{let W;for(;W=O.nextChunk(H);)H=W,Ti(W);let ye=O.nextChunk(w);if(ye){if(w&&ye.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?T():(S(),this._initPlayerWith(e));return}me(ye)}else T()},K=(W,ye)=>{if(!d()||!this.sourceBuffer)return;let Pe,we,tt,pt=Pt=>{window.setTimeout(()=>{d()&&K(W,ye)},Pt)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),pt(100);else{let Pt=pe(),zt=I.currentTime;!this.paused&&I.buffered.length>1&&ee===zt&&Pt-le>500&&($("Stall suspected; trying to fix"),this._fixupStall()),ee!==zt&&(ee=zt,le=Pt);let Ii=this._getBufferSizeSec();if(Ii>30)$(`Buffered ${Ii} seconds; delaying appendBuffer`),pt(2e3);else try{this.sourceBuffer.appendBuffer(W),this.videoPlayStarted?(this.bufferStates.push({ts:Pt,buf:Ii}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(cr){if(cr.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(Pe=this.sourceBuffer.buffered.start(0),we=zt,we-Pe>4&&this.sourceBuffer.remove(Pe,we-3)),pt(1e3);else throw cr}}},x=()=>{z&&F&&($([`Appending chunk, sz=${z.byteLength}:`,JSON.stringify(w)]),K(z,function(){z=null,L()}))},D=W=>e.fragUrlTemplate.replace("%%id%%",W.chunkIdx),me=W=>{d()&&p(D(W),(ye,Pe)=>{if(d()){if(Pe/=1e3,z=ye,w=W,n=W.startTS,Pe){let we=Math.min(10,W.dur/Pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}x()}},()=>this._handleNetworkError())},Ti=W=>{d()&&(Kr(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(D(W),!1)))},dt=W=>{d()&&(e.cachedHeader=W,K(W,()=>{F=!0,x()}))};s=!0,O.seek(W=>{if(d()){if(M=pe(),!W){T();return}H=W,!zL(E)||W.startTS>E?me(W):(w=W,L())}},E),e.cachedHeader?dt(e.cachedHeader):h(e.headerUrl,dt,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:i}=this.params,r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),pn(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Kr(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return pn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,i=d=>{if(!this.autoQuality)return;let h,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(p=this._getBufferSizeSec(),m=d/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}h=this._selectQuality(d),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(h,p)=>{let m=pe();if(this.chunkRateEstimator.addInterval(h,m,p)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-h,speed:g}),!0}},get:()=>{let h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&bl(n)<3e4)return;i(d)}u=this.autoQuality};return{updateChunk:(d,h)=>{let p=s.updateChunk(d,h);return p&&l(),p},notifySwitch:d=>{let h=pe();d<o&&(n=h),o=d}}}_fetchManifest(e,t,i){this.manifestRequest=Xi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(hn).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;Me(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:i,videoElement:r}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{var c,d;u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&((d=(c=window.MediaSource)==null?void 0:c.isTypeSupported)!=null&&d.call(c,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):(i({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},XL))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var Ev=B(_i(),1);import{debounce as t$,filter as Tv,fromEvent as i$,interval as r$,isHigher as a$,isInvariantQuality as s$,isLower as n$,merge as o$,Subject as Iv,Subscription as u$}from"@vkontakte/videoplayer-shared/es2015";var Sl=class{constructor(){this.onDroopedVideoFramesLimit$=new Iv;this.subscription=new u$;this.playing=!1;this.tracks=[];this.forceChecker$=new Iv;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&&!s$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),i=e-this.prevTotalVideoFrames,r=t-this.prevDroppedVideoFrames,s=1-(i-r)/i;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&a$(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(i$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=r$(this.droppedFramesChecker.checkTime).pipe(Tv(()=>this.playing),Tv(()=>{let r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(t$(this.droppedFramesChecker.checkTime)),i=o$(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var i,r;let t=(r=(i=(0,Ev.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>n$(s,n)?-1:1))==null?void 0:i[0])==null?void 0:r[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},mn=Sl;import{map as l$,Observable as c$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as d$}from"@vkontakte/videoplayer-shared/es2015";var Jr=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var p$=(a,e)=>new c$(t=>{if(!window.IntersectionObserver)return;let i={root:null},r=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Jr()))},A(A({},i),e));r.observe(a);let s=d$(document,"visibilitychange").pipe(l$(n=>!document.hidden||Jr())).subscribe(n=>t.next(n));return()=>{r.unobserve(a),s.unsubscribe()}}),je=p$;var y$=["paused","playing","ready"],T$=["paused","playing","ready"],Zr=class{constructor(e){this.subscription=new v$;this.videoState=new _("stopped");this.representations$=new Tl([]);this.droppedFramesManager=new mn;this.maxSeekBackTime$=new Tl(1/0);this.zeroTime$=new Tl(void 0);this.liveOffset=new hi;this._dashCb=e=>{var t,i,r,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:wv.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=(i=_t(u.name))!=null?i:S$(u.video),d=u.bitrate/1e3,h=A({},u.video);if(!c)continue;let p={id:l,quality:c,bitrate:d,size:h};o.push({track:p,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((r=this.videoState.getTransition())==null?void 0:r.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),yl(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(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(s)};`}),i==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,Il.default)(T$,e)&&(n||o)){this.prepare();return}if((r==null?void 0:r.to)!=="paused"&&s.state==="requested"&&(0,Il.default)(y$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(ge(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(i==="paused")this.videoState.setState("paused");else if(i==="playing"){this.videoState.startTransitionTo("playing");let u=r==null?void 0:r.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":i==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(ge(this.params.source.url,u))}return;default:return xv(e)}};this.textTracksManager=new He(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=r=>{e.output.error$.next({id:"DashLiveProvider",category:wv.WTF,message:"DashLiveProvider internal logic error",thrown:r})};this.subscription.add(kv(this.videoState.stateChangeStarted$.pipe(fn(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(fn(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(r)}`})})),this.video=Ae(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(de(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 i=$e(this.video);this.subscription.add(()=>i.destroy()),this.subscription.add(this.representations$.pipe(fn(r=>r.map(({track:s})=>s)),Av(r=>!!r.length),g$()).subscribe(r=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:r}))),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())==null?void 0:r.to)==="ready"&&this.videoState.setState("ready")},t)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(f$(),fn(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(h$({zeroTime:this.zeroTime$.pipe(Av(yl)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:s})=>this.params.output.liveTime$.next(r+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Re(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ue(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(je(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r,min:s}})=>{this.dash.setAutoQualityLimits({max:r&&Rv(r),min:s&&Rv(s)}),this.params.output.autoVideoTrackLimits$.next({max:r,min:s})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var s;switch(r.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((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 xv(r.to)}},t)).add(kv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,b$(["init"])).pipe(m$(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),ke(this.video)}createLiveDashPlayer(){let e=new Xr({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,h,p,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),i=(h=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?h:this.params.desiredState.autoVideoTrackSwitching.getState(),r=!i&&yl(t)?t:qt(e.map(({track:b})=>b),{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,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=r==null?void 0:r.id,n=this.params.desiredState.videoTrack.getTransition(),o=(p=this.params.desiredState.videoTrack.getState())==null?void 0:p.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r&&(n||s!==o)&&this.setVideoTrack(r),u&&this.setAutoQuality(i),n||u||s!==o){let b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;Pv(b,"Representations missing"),this.dash.startPlay(b,i)}}setVideoTrack(e){var i;let t=(i=this.representations$.getValue().find(({track:r})=>r.id===e.id))==null?void 0:i.representation;Pv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t==="paused"&&i==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ge(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}};var Lv=Zr;var Jy=B(qe(),1);var Ji=(a,e)=>{let t=0;for(let i=0;i<a.length;i++){let r=a.start(i)*1e3,s=a.end(i)*1e3;r<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as iC,assertNonNullable as rC,debounce as aC,ErrorCategory as zy,filter as lc,filterChanged as qa,fromEvent as sC,isNonNullable as Ky,map as cc,merge as On,observableFrom as dc,once as Xy,Subscription as nC}from"@vkontakte/videoplayer-shared/es2015";var bn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;let i=this.listeners[e];for(let r=0,s=i.length;r<s;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let i=this.listeners[e.type].slice();for(let r=0,s=i.length;r<s;r++){let n=i[r];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}},Zi=class extends bn{constructor(){super(),this.listeners||bn.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)}},ea=class{constructor(){Object.defineProperty(this,"signal",{value:new Zi,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ea.prototype[Symbol.toStringTag]="AbortController",Zi.prototype[Symbol.toStringTag]="AbortSignal");function gn(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 El(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=a;if(!gn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let h=new t(l,c);return d&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),h},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(p){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let h=new Promise((p,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([h,n(u,l)])}return n(u,l)},Request:s}}var ta=gn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),$v=ta?El({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,lt=ta?$v.fetch:window.fetch,Aq=ta?$v.Request:window.Request,ve=ta?ea:window.AbortController,kq=ta?Zi:window.AbortSignal;var sc=B(Pl(),1);var gS=B(bS(),1);import{ErrorCategory as ra}from"@vkontakte/videoplayer-shared/es2015";var vS=a=>{if(!a)return{id:"EmptyResponse",category:ra.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:ra.NETWORK,message:`UV Error ${a}`};let e=(0,gS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:ra.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:ra.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:ra.PARSER,message:"Response is valid XML, but parser failed"}};var Ut=(a,e,t=0)=>{for(let i=0;i<a.length;i++)if(a.start(i)*1e3-t<=e&&a.end(i)*1e3+t>e)return!0;return!1};import{abortable as ic,assertNonNullable as sr,combine as nr,ErrorCategory as ct,filter as Rn,filterChanged as _a,flattenObject as Na,fromEvent as It,getTraceSubscriptionMethod as _D,interval as rc,isNonNullable as Fa,isNullable as Uy,map as or,merge as Si,now as ac,Subject as Ln,Subscription as Hy,tap as ND,throttle as FD,ValueSubject as ie}from"@vkontakte/videoplayer-shared/es2015";var Sn=B(qe(),1),rr=B(Nt(),1),yn=B(Pl(),1);var nM=(a,e={})=>{let i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},oM=a=>window.clearTimeout(a),SS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),yS=!SS(window.requestIdleCallback)||!SS(window.cancelIdleCallback),Ll=yS?nM:window.requestIdleCallback,aa=yS?oM:window.cancelIdleCallback;var Ry=B(Ks(),1);import{assertNever as uM,ErrorCategory as TS,Subject as IS}from"@vkontakte/videoplayer-shared/es2015";var lM=18,ES=!1;try{ES=q.browser.isSafari&&!!q.browser.safariVersion&&q.browser.safariVersion<=lM}catch(a){console.error(a)}var $l=class{constructor(e){this.bufferFull$=new IS;this.error$=new IS;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:TS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return P(this,null,function*(){return t&&t.aborted?!1:new Promise(i=>{let r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return P(this,null,function*(){return i&&i.aborted?!1:new Promise(r=>{let s={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(s),this.pull()})})}abort(e){return P(this,null,function*(){return new Promise(t=>{let i,r=s=>{this.abortRequested=!1,t(s)};ES&&e?i={operation:"safariAbort",init:e,callback:r}:i={operation:"abort",callback:r};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,i&&(this.queue=[i]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var r;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((r=e.signal)!=null&&r.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(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:TS.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:uM(t)}}},xS=$l;var Ml=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 jt,assertNonNullable as De,ErrorCategory as Tt,fromEvent as zl,getExponentialDelay as Kl,isNonNullable as ir,isNullable as Se,now as vn,once as PD,Subject as wD,Subscription as AD,ValueSubject as bi}from"@vkontakte/videoplayer-shared/es2015";var Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let i=this.readUint32();this.type=this.readString(4),this.size32=i<=e.buffer.byteLength-e.byteOffset?i:NaN;let r=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,r)}get id(){return this.type}get size(){return this.size32}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var er=class extends Q{};var sa=class extends Q{constructor(t,i){super(t,i);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let r=this.content.byteOffset,s=r+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(r,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var na=class extends Q{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let i=this.size-this.cursor;for(;i;){let r=this.readString(4);this.compatibleBrands.push(r),i-=4}}};var oa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var te=class extends Q{constructor(e,t){super(e,t);let i=this.readUint32();this.version=i>>>24,this.flags=i&16777215}};var ua=class extends te{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 la=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ca=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var mi=class extends te{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 i=0;i<this.referenceCount;i++){let r=this.readUint32(),s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();let u=r>>>28,l=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var da=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var pa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ha=class extends te{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 ma=class extends te{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var fa=class extends te{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ba=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ga=class extends te{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 va=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Sa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var ya=class extends te{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ta=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var Ia=class extends te{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 Ea=class extends te{constructor(t,i){super(t,i);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var xa=class extends te{constructor(t,i){super(t,i);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let r=0;r<this.sampleCount;r++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var Pa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(this.content)}};var wa=class extends te{constructor(e,t){super(e,t),this.entryCount=this.readUint32(),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+8,this.content.byteLength-8))}};var Aa=class extends Q{constructor(e,t){super(e,t),this.children=this.scanForBoxes(new DataView(this.content.buffer,this.content.byteOffset+78,this.content.byteLength-78))}};var dM={ftyp:na,moov:oa,mvhd:ua,moof:la,mdat:ca,sidx:mi,trak:da,mdia:ba,mfhd:ya,tkhd:ga,traf:Ta,tfhd:Ia,tfdt:Ea,trun:xa,minf:va,sv3d:pa,st3d:ha,prhd:ma,proj:Sa,equi:fa,uuid:sa,stbl:Pa,stsd:wa,avc1:Aa,unknown:er},St=class a{constructor(e={}){this.options=A({offset:0},e)}parse(e){let t=[],i=this.options.offset;for(;i<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+i+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+i,e.byteLength-i));if(!n.size)break;t.push(n),i+=n.size}catch(r){break}return t}createBox(e,t){let i=dM[e];return i?new i(t,new a):new er(t,new a)}};var Ht=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var i,r,s;(s=(i=this.index)[r=t.type])!=null||(i[r]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var hM=new TextDecoder("ascii"),mM=a=>hM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",fM=a=>{let e=new mi(a,new St),t=e.earliestPresentationTime/e.timescale*1e3,i=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:i,to:i+s.referencedSize-1}};return t+=n,i+=s.referencedSize,o})},bM=(a,e)=>{let i=new St().parse(a),r=new Ht(i),s=r.findAll("moof"),n=e?r.findAll("uuid"):r.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)},gM=a=>{let t=new St().parse(a),i=new Ht(t),r={},s=i.findAll("uuid");return s.length?s[s.length-1]:r},vM=a=>{var r;let t=new St().parse(a);return(r=new Ht(t).find("sidx"))==null?void 0:r.timescale},SM=(a,e)=>{let i=new St().parse(a),s=new Ht(i).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,h)=>d+h,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},yM=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}}},i=new St().parse(a),r=new Ht(i);if(r.find("sv3d")){e.is3dVideo=!0;let n=r.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=r.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=r.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},PS={validateData:mM,parseInit:yM,getIndexRange:()=>{},parseSegments:fM,parseFeedableSegmentChunk:bM,getChunkEndTime:SM,getServerLatencyTimestamps:gM,getTimescaleFromIndex:vM};var Ra=B(qe(),1);import{assertNonNullable as Cl,isNonNullable as RS,isNullable as IM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as TM}from"@vkontakte/videoplayer-shared/es2015";var wS={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"}},AS=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 i=ka(a,t),r=i in wS,s=r?wS[i].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=ka(u),d=l*at(2,(o-1)*8)+c,h=t+o,p;return h+d>a.byteLength?p=new DataView(a.buffer,a.byteOffset+h):p=new DataView(a.buffer,a.byteOffset+h,d),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:s,tagHeaderSize:h,tagSize:h+d,value:p,valueSize:d}},ka=(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},Ze=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return ka(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:TM(e)}},fi=(a,e)=>{let t=0;for(;t<a.byteLength;){let i=new DataView(a.buffer,a.byteOffset+t),r=AS(i);if(!e(r))return;r.type==="master"&&fi(r.value,e),t=r.value.byteOffset-a.byteOffset+r.valueSize}},kS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,i,r=AS(a);return fi(r.value,({tag:s,type:n,value:o})=>(s===17143?e=Ze(o,n):s===17026?t=Ze(o,n):s===17029&&(i=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)};var LS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],EM=[231,22612,22743,167,171,163,160,175],xM=a=>{let e,t,i,r,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return fi(a,({tag:h,type:p,value:m,valueSize:b})=>{if(h===21419){let g=Ze(m,p);l=ka(g)}else h!==21420&&(l=void 0);return h===408125543?(e=m.byteOffset,t=m.byteOffset+b):h===357149030?s=!0:h===290298740?n=!0:h===2807729?i=Ze(m,p):h===17545?r=Ze(m,p):h===21420&&l===475249515?u=Ze(m,p):h===374648427?fi(m,({tag:g,type:v,value:S})=>g===30321?(c=Ze(S,v)===1,!1):!0):s&&n&&(0,Ra.default)(LS,h)&&(o=!0),!o}),Cl(e,"Failed to parse webm Segment start"),Cl(t,"Failed to parse webm Segment end"),Cl(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},PM=a=>{if(IM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},wM=(a,e)=>{let t=!1,i=!1,r=o=>RS(o.time)&&RS(o.position),s=[],n;return fi(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&r(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ze(l,u));break;case 183:break;case 241:n&&(n.position=Ze(l,u));break;default:t&&(0,Ra.default)(LS,o)&&(i=!0)}return!(t&&i)}),n&&r(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}}})},AM=a=>{let e=0,t=!1;try{fi(a,i=>i.tag===524531317?i.tagSize<=a.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):(0,Ra.default)(EM,i.tag)?(e+i.tagSize<=a.byteLength&&(e+=i.tagSize,t||(t=(0,Ra.default)([163,160,175],i.tag))),!0):!1)}catch(i){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},$S={validateData:kS,parseInit:xM,getIndexRange:PM,parseSegments:wM,parseFeedableSegmentChunk:AM};var La=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,i]=e;if(t==="audio"||t==="video")switch(i){case"webm":return $S;case"mp4":return PS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Gl=B(XS(),1),Ey=B(_i(),1),xy=B(hy(),1),Py=B(Nt(),1),Wl=B(zi(),1);var my=B(qe(),1),Fl=a=>{let e=a.split("."),[t,...i]=e;if(!t)return!1;switch(t){case"av01":{let[r,s,n]=i;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[r,s,n]=i;return!!(r&&parseInt(r,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let r=i[0];if(!r||r.length!==6)return!1;let[s,n]=r.toUpperCase(),o=s+n;return(0,my.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as xD,isNullable as Ty}from"@vkontakte/videoplayer-shared/es2015";var fy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var by=a=>{var e;try{let t=ID(),i=a.match(t),{groups:r}=i!=null?i:{};if(r){let s={};if(r.extensions){let u=r.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=r.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:r.extlang,langtag:r.langtag,language:r.language,privateuse:r.privateuse||r.privateuse2,region:r.region,script:r.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 ID(){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 Ul=B(Nt(),1);import{videoSizeToQuality as ID}from"@vkontakte/videoplayer-shared/es2015";var by=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?_t(s):void 0)!=null?u:ID({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},gy=({id:a,bitrate:e})=>({id:a,bitrate:e}),vy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Sy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Hl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Ul.default)(i.split("."),0),isDefault:r}),jl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Ul.default)(r.split("."),0)}),Ql=a=>"url"in a,xe=a=>a.type==="template",$a=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Ty=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},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},yt=(a,e)=>{let t=a;t=(0,Gl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,Iy.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Gl.default)(t,n,(o,u)=>yy(s)?o:yy(u)?s:(0,Ey.default)(s,parseInt(u,10),"0"))}return t},Py=(a,e)=>{var z,w,H,M,j,ee,le,T,L,K,x,D,me,Ti,dt,W,ye,Pe,we,tt,pt,Pt,zt,Ii,cr,$c,Mc,Dc,Cc,Vc,Oc,Bc,_c,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td,id,rd,ad,sd,nd,od,ud,ld,cd,dd,pd;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Qe=>{var Z,Kt;return(Kt=(Z=Qe.textContent)==null?void 0:Z.trim())!=null?Kt:""}),o=(z=(0,xy.default)(n,0))!=null?z:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],h=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let v,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],E=y.reduce((Qe,Z)=>C(A({},Qe),{[Z.id]:Z.children}),{}),I=y.reduce((Qe,Z)=>C(A({},Qe),{[Z.id]:Z.getAttribute("duration")}),{});S?v=Ty(S):(0,Wl.default)(I).filter(Qe=>Qe).length&&!u?v=(0,Wl.default)(I).reduce((Qe,Z)=>{var Kt;return Qe+((Kt=Ty(Z))!=null?Kt:0)},0):b&&(v=parseInt(b,10));let $=0,V=(H=(w=s.getAttribute("profiles"))==null?void 0:w.split(","))!=null?H:[];for(let Qe of y.map(Z=>Z.id))for(let Z of E[Qe]){let Kt=(M=Z.getAttribute("id"))!=null?M:"id"+($++).toString(10),dr=(j=Z.getAttribute("mimeType"))!=null?j:"",Jn=(ee=Z.getAttribute("codecs"))!=null?ee:"",Zn=(le=Z.getAttribute("contentType"))!=null?le:dr==null?void 0:dr.split("/")[0],YT=(L=(T=Z.getAttribute("profiles"))==null?void 0:T.split(","))!=null?L:[],hd=(x=fy((K=Z.getAttribute("lang"))!=null?K:""))!=null?x:{},es=(Ti=(me=(D=Z.querySelector("Label"))==null?void 0:D.textContent)==null?void 0:me.trim())!=null?Ti:void 0,zT=Z.querySelectorAll("Representation"),KT=Z.querySelector("SegmentTemplate"),XT=(W=(dt=Z.querySelector("Role"))==null?void 0:dt.getAttribute("value"))!=null?W:void 0,Ei=Zn,ae={id:Kt,language:hd.language,isDefault:XT==="main",label:es,codecs:Jn,hdr:Ei==="video"&&Fl(Jn),mime:dr,representations:[]};for(let J of zT){let wt=(ye=J.getAttribute("lang"))!=null?ye:void 0,pr=(we=(Pe=es!=null?es:Z.getAttribute("label"))!=null?Pe:J.getAttribute("label"))!=null?we:void 0,ts=(Pt=(pt=(tt=J.querySelector("BaseURL"))==null?void 0:tt.textContent)==null?void 0:pt.trim())!=null?Pt:"",Xt=new URL(ts||o,e).toString(),At=(zt=J.getAttribute("mimeType"))!=null?zt:dr,is=(cr=(Ii=J.getAttribute("codecs"))!=null?Ii:Jn)!=null?cr:"",rs;if(Zn==="text"){let kt=J.getAttribute("id")||"",as=(($c=hd.privateuse)==null?void 0:$c.includes("x-auto"))||kt.includes("_auto"),Jt=J.querySelector("SegmentTemplate");if(Jt){let hr={representationId:(Mc=J.getAttribute("id"))!=null?Mc:void 0,bandwidth:(Dc=J.getAttribute("bandwidth"))!=null?Dc:void 0},ss=parseInt((Cc=J.getAttribute("bandwidth"))!=null?Cc:"",10)/1e3,ns=(Oc=parseInt((Vc=Jt.getAttribute("startNumber"))!=null?Vc:"",10))!=null?Oc:1,xi=parseInt((Bc=Jt.getAttribute("timescale"))!=null?Bc:"",10),eo=(_c=Jt.querySelectorAll("SegmentTimeline S"))!=null?_c:[],Pi=Jt.getAttribute("media");if(!Pi)continue;let os=[],us=0,ls="",wi=0,mr=ns,Te=0;for(let Ge of eo){let Zt=parseInt((Nc=Ge.getAttribute("d"))!=null?Nc:"",10),Fe=parseInt((Fc=Ge.getAttribute("r"))!=null?Fc:"",10)||0,Rt=parseInt((qc=Ge.getAttribute("t"))!=null?qc:"",10);Te=Number.isFinite(Rt)?Rt:Te;let ei=Zt/xi*1e3,Lt=Te/xi*1e3;for(let it=0;it<Fe+1;it++){let $t=yt(Pi,C(A({},hr),{segmentNumber:mr.toString(10),segmentTime:(Te+it*Zt).toString(10)})),Ai=(Lt!=null?Lt:0)+it*ei,br=Ai+ei;mr++,os.push({time:{from:Ai,to:br},url:$t})}Te+=(Fe+1)*Zt,us+=(Fe+1)*ei}wi=Te/xi*1e3,ls=yt(Pi,C(A({},hr),{segmentNumber:mr.toString(10),segmentTime:Te.toString(10)}));let fr={time:{from:wi,to:1/0},url:ls},ht={type:"template",baseUrl:Xt,segmentTemplateUrl:Pi,initUrl:"",totalSegmentsDurationMs:us,segments:os,nextSegmentBeyondManifest:fr,timescale:xi};rs={id:kt,kind:"text",segmentReference:ht,profiles:[],duration:v,bitrate:ss,mime:"",codecs:"",width:0,height:0,isAuto:as}}else rs={id:kt,isAuto:as,kind:"text",url:Xt}}else{let kt=(Hc=(Uc=J.getAttribute("contentType"))!=null?Uc:At==null?void 0:At.split("/")[0])!=null?Hc:Zn,as=(Qc=(jc=Z.getAttribute("profiles"))==null?void 0:jc.split(","))!=null?Qc:[],Jt=parseInt((Gc=J.getAttribute("width"))!=null?Gc:"",10),hr=parseInt((Wc=J.getAttribute("height"))!=null?Wc:"",10),ss=parseInt((Yc=J.getAttribute("bandwidth"))!=null?Yc:"",10)/1e3,ns=(zc=J.getAttribute("frameRate"))!=null?zc:"",xi=(Kc=J.getAttribute("quality"))!=null?Kc:void 0,eo=ns?my(ns):void 0,Pi=(Xc=J.getAttribute("id"))!=null?Xc:"id"+($++).toString(10),os=kt==="video"?`${hr}p`:kt==="audio"?`${ss}Kbps`:is,us=`${Pi}@${os}`,ls=[...V,...YT,...as],wi,mr=J.querySelector("SegmentBase"),Te=(Jc=J.querySelector("SegmentTemplate"))!=null?Jc:KT;if(mr){let ht=(ed=(Zc=J.querySelector("SegmentBase Initialization"))==null?void 0:Zc.getAttribute("range"))!=null?ed:"",[Ge,Zt]=ht.split("-").map($t=>parseInt($t,10)),Fe={from:Ge,to:Zt},Rt=(td=J.querySelector("SegmentBase"))==null?void 0:td.getAttribute("indexRange"),[ei,Lt]=Rt?Rt.split("-").map($t=>parseInt($t,10)):[],it=Rt?{from:ei,to:Lt}:void 0;wi={type:"byteRange",url:Xt,initRange:Fe,indexRange:it}}else if(Te){let ht={representationId:(id=J.getAttribute("id"))!=null?id:void 0,bandwidth:(rd=J.getAttribute("bandwidth"))!=null?rd:void 0},Ge=parseInt((ad=Te.getAttribute("timescale"))!=null?ad:"",10),Zt=(sd=Te.getAttribute("initialization"))!=null?sd:"",Fe=Te.getAttribute("media"),Rt=(od=parseInt((nd=Te.getAttribute("startNumber"))!=null?nd:"",10))!=null?od:1,ei=yt(Zt,ht);if(!Fe)throw new ReferenceError("No media attribute in SegmentTemplate");let Lt=(ud=Te.querySelectorAll("SegmentTimeline S"))!=null?ud:[],it=[],$t=0,Ai="",br=0;if(Lt.length){let cs=Rt,We=0;for(let ki of Lt){let rt=parseInt((ld=ki.getAttribute("d"))!=null?ld:"",10),ti=parseInt((cd=ki.getAttribute("r"))!=null?cd:"",10)||0,ds=parseInt((dd=ki.getAttribute("t"))!=null?dd:"",10);We=Number.isFinite(ds)?ds:We;let to=rt/Ge*1e3,io=We/Ge*1e3;for(let ps=0;ps<ti+1;ps++){let ZT=yt(Fe,C(A({},ht),{segmentNumber:cs.toString(10),segmentTime:(We+ps*rt).toString(10)})),md=(io!=null?io:0)+ps*to,eI=md+to;cs++,it.push({time:{from:md,to:eI},url:ZT})}We+=(ti+1)*rt,$t+=(ti+1)*to}br=We/Ge*1e3,Ai=yt(Fe,C(A({},ht),{segmentNumber:cs.toString(10),segmentTime:We.toString(10)}))}else if(ED(v)){let We=parseInt((pd=Te.getAttribute("duration"))!=null?pd:"",10)/Ge*1e3,ki=Math.ceil(v/We),rt=0;for(let ti=1;ti<ki;ti++){let ds=yt(Fe,C(A({},ht),{segmentNumber:ti.toString(10),segmentTime:rt.toString(10)}));it.push({time:{from:rt,to:rt+We},url:ds}),rt+=We}br=rt,Ai=yt(Fe,C(A({},ht),{segmentNumber:ki.toString(10),segmentTime:rt.toString(10)}))}let JT={time:{from:br,to:1/0},url:Ai};wi={type:"template",baseUrl:Xt,segmentTemplateUrl:Fe,initUrl:ei,totalSegmentsDurationMs:$t,segments:it,nextSegmentBeyondManifest:JT,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!kt||!At)continue;let fr={video:"video",audio:"audio",text:"text"}[kt];if(!fr)continue;Ei||(Ei=fr),rs={id:us,kind:fr,segmentReference:wi,profiles:ls,duration:v,bitrate:ss,mime:At,codecs:is,width:Jt,height:hr,fps:eo,quality:xi}}ae.language||(ae.language=wt),ae.label||(ae.label=pr),ae.mime||(ae.mime=At),ae.codecs||(ae.codecs=is),ae.hdr||(ae.hdr=Ei==="video"&&Fl(is)),ae.representations.push(rs)}if(Ei){let J=r[Ei].find(wt=>wt.id===ae.id);if(J&&ae.representations.every(wt=>xe(wt.segmentReference)))for(let wt of J.representations){let pr=ae.representations.find(At=>At.id===wt.id),ts=pr==null?void 0:pr.segmentReference,Xt=wt.segmentReference;Xt.segments.push(...ts.segments),Xt.nextSegmentBeyondManifest=ts.nextSegmentBeyondManifest}else r[Ei].push(ae)}}return{duration:v,streams:r,baseUrls:n,live:g}};var Ay=B(qe(),1);import{isNonNullable as wy}from"@vkontakte/videoplayer-shared/es2015";var ne=(a,e)=>wy(a)&&wy(e)&&a.readyState==="open"&&(0,Ay.default)([...a.activeSourceBuffers],e);var Ma=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new bi(0);this.currentLowLatencySegmentLength$=new bi(0);this.currentSegmentLength$=new bi(0);this.onLastSegment$=new bi(!1);this.fullyBuffered$=new bi(!1);this.playingRepresentation$=new bi(void 0);this.playingRepresentationInit$=new bi(void 0);this.error$=new PD;this.gaps=[];this.subscription=new wD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ve;this.switchAbortController=new ve;this.destroyAbortController=new ve;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=jt(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){let t=this.representations.get(e);De(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new ES(this.sourceBuffer),this.subscription.add(zl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Tt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Tt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(zl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Tt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ne(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ml(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);De(i,"No init buffer for starting representation"),De(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=jt(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(!ne(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);De(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Se(s)||Se(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),De(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ne(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();ir(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new ms(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=jt(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(!ne(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);De(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Se(s)||Se(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),De(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ne(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();ir(n)&&(this.isLive||(this.bufferLimit=1/0,yield new ms(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=jt(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){var u,l;let t=(u=(0,yn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!xe(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);De(r);let s=this.segments.get(i);De(s,"No segments for starting representation");let n=this.initData.get(i);if(De(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,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!ne(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ve,jt(this.switchAbortController.signal,function(i,r=!1){return oe(this,null,function*(){this.switchingToRepresentationId=i;let s=this.representations.get(i);De(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Se(o)||Se(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),De(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ne(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ir(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!Se(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return P(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ve,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Se(e)||Se(this.downloadingRepresentationId)||Se(this.playingRepresentationId)||Se(this.sourceBuffer)||!ne(this.mediaSource,this.sourceBuffer)||ir(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(De(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);ir(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Ml(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Sn.default)(u,r))c="high";else{let d=(0,rr.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,rr.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;ir(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,yn.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,yn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!xe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>C(A({},p),{status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,rr.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;De(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!xe(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],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=yt(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 i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&aa&&aa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&aa&&aa(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,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let b=h<=i&&p>=i,g=h>i||b||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=i+v||p<=i+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&ne(this.mediaSource,this.sourceBuffer)&&!(Ut(this.sourceBuffer.buffered,h)&&Ut(this.sourceBuffer.buffered,p)))&&g&&S});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+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=r;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,i="auto"){return P(this,null,function*(){xe(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return P(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield jt(o,function(){return oe(this,null,function*(){let c=Kl(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:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=vn(),!c)return;let d=new DataView(c),h=La(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,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())xe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return P(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:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield jt(n,function(){return oe(this,null,function*(){let u=Kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),zl(window,"online").pipe(xD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=vn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),$a(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(xe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,rr.default)(e,0).byte.from,to:(0,rr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>P(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=vn(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Tt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!xe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=vn();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:Tt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Sn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return P(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!ne(this.mediaSource,this.sourceBuffer))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){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=La(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 P(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!ne(this.mediaSource,this.sourceBuffer))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-i,h=c.byte.to-i,p=h-d+1,m=d<r,b=h<=r;if(!m)continue;let g=La(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,p);(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(p,r-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?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===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!(Se(this.sourceBuffer)||!ne(this.mediaSource,this.sourceBuffer))){!this.isLive&&q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ut(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ut(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Tt.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",Ql(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])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[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Ll(()=>(0,ky.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return P(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?jt(this.destroyAbortController.signal,function(){return oe(this,null,function*(){let o=Kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,La(e.mime),r)).then(o=>P(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&xe(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Tt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return P(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,i=!1){return P(this,null,function*(){if(!this.sourceBuffer||!ne(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Se(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push(A({},u.time)),r=n(r);let l=Ql(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,Sn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(r.length&&i){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 r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return P(this,null,function*(){if(!this.sourceBuffer||!ne(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||!ne(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(e=this.getCurrentPosition()){return!this.sourceBuffer||!ne(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Se(e)?0:Ji(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ne(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.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<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ne(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Ll(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Tt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Se(this.sourceBuffer)||!ne(this.mediaSource,this.sourceBuffer)||Se(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.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?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Tt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Da=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Ry=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as Ca,assertNever as $y,fromEvent as My,merge as AD,now as Va,Subscription as kD,Subject as Dy,ValueSubject as Xl,flattenObject as ar,ErrorCategory as Oa}from"@vkontakte/videoplayer-shared/es2015";var Ly=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var In=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Xl(void 0);this.lastConnectionReused$=new Xl(void 0);this.lastRequestFirstBytes$=new Xl(void 0);this.recoverableError$=new Dy;this.error$=new Dy;this.abortAllController=new ve;this.subscription=new kD;this.fetchManifest=Ca(this.abortAllController.signal,function(e){return oe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Da(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=Ly(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Tn);return r?(t.log("success",ar({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ar({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Ca(this.abortAllController.signal,function(l){return oe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var j,ee,le;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(c,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),c=T.toString();break}default:$y(t)}this.requestQuic&&(c=Da(c));let p=this.abortAllController.signal,m;if(n){let T=new ve;if(m=AD(My(this.abortAllController.signal,"abort"),My(n,"abort")).subscribe(()=>{try{T.abort()}catch(L){Tn(L)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(L){Tn(L)}p=T.signal}let b=Va();h.log("startRequest",ar({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:d,signal:p}),v=Va();if(!g)return h.error("error",{message:"No response in request"}),h.end(),m==null||m.unsubscribe(),null;if((j=this.throughputEstimator)==null||j.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let T=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:T}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){m==null||m.unsubscribe();let T=Va(),L={requestStartedAt:b,requestEndedAt:T,duration:T-b};return h.log("endRequest",ar(L)),h.end(),g.arrayBuffer()}let S=g.body;if(o){let T;[S,T]=g.body.tee(),(ee=this.throughputEstimator)==null||ee.trackStream(T,u)}let y=S.getReader(),E,I=parseInt((le=g.headers.get("content-length"))!=null?le:"",10);Number.isFinite(I)&&(E=I),!E&&i&&(E=i.to-i.from+1);let $=0,V=E?new Uint8Array(E):new Uint8Array(0),F=!1,z=T=>{m==null||m.unsubscribe(),F=!0,Tn(T)},w=Ca(p,function(K){return oe(this,arguments,function*({done:T,value:L}){if($===0&&this.lastRequestFirstBytes$.next(Va()-b),p.aborted){m==null||m.unsubscribe();return}if(!T&&L){if(E)V.set(L,$),$+=L.byteLength;else{let x=new Uint8Array(V.length+L.length);x.set(V),x.set(L,V.length),V=x,$+=L.byteLength}r==null||r(new DataView(V.buffer),$),yield y==null?void 0:y.read().then(w,z)}})}.bind(this));yield y==null?void 0:y.read().then(w,z),m==null||m.unsubscribe();let H=Va(),M={failed:F,requestStartedAt:b,requestEndedAt:H,duration:H-b};return F?(h.error("endRequest",ar(M)),h.end(),null):(h.log("endRequest",ar(M)),h.end(),V.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Ca(this.abortAllController.signal,function(e,t,i){return oe(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,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,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let h=new DataView(d,r-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=(v=e.indexRange)!=null?v:t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,p,m);return{init:p,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Ca(this.abortAllController.signal,function(e,t){return oe(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>C(A({},n),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ry(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return P(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:$y(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return P(this,null,function*(){let i=yield lt(e,t);if(i.ok)return i;let r=yield i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Oa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Oa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Oa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Oa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Oa.FATAL})}})}},Tn=a=>{if(!$a(a))throw a};var gi=(a,e,t)=>t*e+(1-t)*a,Jl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Cy=(a,e,t,i)=>{let r=0,s=t,n=Jl(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as RD,ValueSubject as Vy}from"@vkontakte/videoplayer-shared/es2015";var Qt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Vy(e.initial),this.debounced$=new Vy(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${t}`),this.smoothedSeries$=new Ie(`smoothed_${t}`),this.reportedSeries$=new Ie(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=at(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(RD(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 En=class extends Qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=gi(this.slow,e,this.params.emaAlphaSlow),this.fast=gi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var xn=class extends Qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Jl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=gi(this.emaSmoothed,e,this.params.emaAlpha);let i=Cy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Pn=class extends Qt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?gi(this.smoothed,t,this.params.emaAlpha):t}};var vi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new En({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new xn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Pn(A({initial:e,label:"liveEdgeDelay"},t))}};var Zl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as LD,ValueSubject as $D}from"@vkontakte/videoplayer-shared/es2015";var Ba=class a{constructor(e,t){this.currentRepresentation$=new $D(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(!LD(e))for(let i of this.representations)for(let r of i){let s=r.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(C(A({},r),{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 i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,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&&xe(t.segmentReference))}};var An=B(Nt(),1);import{assertNever as kn}from"@vkontakte/videoplayer-shared/es2015";var Oy=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:s,codecs:n,nativeHlsSupported:o}=q.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!i||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(r.mp4||r.webm);default:return kn(c)}})},wn=a=>{let{webmDecodingInfo:e}=q.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:kn(a)}return[t,i]},By=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...wn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(q.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...wn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...wn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...wn(a),...r,"HLS","HLS_ONDEMAND"];default:kn(e)}return q.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},_y=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=q.device.isMac&&q.browser.isSafari;if(q.device.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:kn(a)}else q.video.nativeHlsSupported&&!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"]},ec=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Ny=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,An.default)(t.value.split("."),0)}for(let t of a){let i=(0,An.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,An.default)(e.value.split("."),0)};var FD=["timeupdate","progress","play","seeked","stalled","waiting"],qD=["timeupdate","progress","loadeddata","playing","seeked"];var $n=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Uy;this.representationSubscription=new Uy;this.state$=new _("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 Ln;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.isActiveLive$=new ie(!1);this.isLowLatency$=new ie(!1);this.liveDuration$=new ie(0);this.liveSeekableDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(0);this.liveStreamStatus$=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.currentStallDuration$=new ie(0);this.videoLastDataObtainedTimestamp$=new ie(0);this.fetcherRecoverableError$=new Ln;this.fetcherError$=new Ln;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Ln;this.gapWatchdogActive=!1;this.destroyController=new ve;this.initManifest=ic(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ge(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ic(this.destroyController.signal,function(){return oe(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:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Py(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=gS(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,h,p,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=Je())==null?void 0:p.isTypeSupported)!=null&&m.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:m})=>i(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=Ny(d);if(h&&(r[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=r.video.some(g=>g.hdr),b=r.video.some(g=>!g.hdr);q.display.isHDR&&p&&m?r.video=r.video.filter(g=>g.hdr):b&&(r.video=r.video.filter(g=>!g.hdr))}}let s=C(A({},t),{streams:r});return this.tracer.log("updateManifestEnd",Na(s)),s})}.bind(this));this.initRepresentations=ic(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",Na({initialVideo:e,initialAudio:t,sourceHls:i})),sr(this.manifest),sr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(It(p,"error").pipe(Rn(m=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?_g():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&an())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new Ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Fa(t)){let p=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Si(...qD.map(p=>It(this.element,p))).pipe(or(p=>this.element?Ji(this.element.buffered,this.element.currentTime*1e3):0),_a(),_D(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Si(It(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(_a()).subscribe(m=>this.liveStreamEndTimestamp=ac())),this.subscription.add(It(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=rc(1e3).subscribe(m=>{let b=Xs(this.manifestUrlString,2);this.manifestUrlString=ge(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(It(this.element,"play").subscribe(m=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add(nr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(or(({isActiveLive:m,isLowLatency:b})=>m&&b),_a()).subscribe(m=>{this.isManualDecreasePlaybackInLive()||Zl(this.element,1)})),this.representationSubscription.add(nr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Rn(({bufferLength:m,isActiveLive:b,isLowLatency:g})=>b&&g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(m=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!m)return;let b=this.liveSeekableDuration$.getValue()-m/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+m/1e3)})),this.representationSubscription.add(nr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Rn(({isLive:m})=>m),_a((m,b)=>b.bufferLength<m.bufferLength),or(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let v=Xs(this.manifestUrlString,2);return(m/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(nr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:m,isActiveLive:b,isLowLatency:g})=>{if(!g||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=m-v;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(E)>S&&(I=1+Math.sign(E)*y),Zl(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var g,v;let b=0;if(m){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var I,$;return($=(I=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?$:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(nr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(ND(1e3)).subscribe(g=>P(this,[g],function*({liveLoadBufferLength:m,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,S=Xs(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,$=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,V=isFinite(m)?m:b,F=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),z=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(z);let w="none";if(F?w="active_low_latency":this.isLowLatency$.getValue()&&z?(this.bufferManagers.forEach(H=>H.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&V<E?w="live_forward_buffering":V<E+$&&(w="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let H=p-(E+I),M=this.normolizeLiveOffset(Math.trunc(S+H/v)),j=Math.abs(M-S),ee=0;!m||j<=this.tuning.dashCmafLive.offsetCalculationError?ee=S:M>0&&j>this.tuning.dashCmafLive.offsetCalculationError&&(ee=M),this.manifestUrlString=ge(this.manifestUrlString,ee,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,yield this.updateLive())}),m=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:m,message:"Failed to update live with subscription"})}))}let l=Si(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(or(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Si(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(or(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=nr({allBuffersFull:l,someBufferEnded:c}).pipe(_a(),or(({allBuffersFull:p,someBufferEnded:m})=>p&&m),Rn(p=>p));if(this.representationSubscription.add(Si(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(p=this.source)==null||p.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add(Si(...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"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((m,b)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){m();return}this.tuning.dash.rejectOnSourceOpenTimeout?b(new Error("Timeout reject when wait sourceopen event")):m()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),m()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,sc.default)((0,sc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],m=>m.representations),m=>{let b=[];return m.duration&&b.push(m.duration),xe(m.segmentReference)&&m.segmentReference.totalSegmentsDurationMs&&b.push(m.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Fa(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,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=rc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new In({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=vi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,A({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return P(this,null,function*(){var r,s,n;sr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ac()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ge(this.manifestUrlString,i,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(s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){sr(this.element),this.state$.setState("running"),this.subscription.add(Si(...FD.map(e=>It(this.element,e)),It(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(It(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(It(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ut(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,m,b,g,v,S,y,E,I,$,V;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=ac(),n=100,o=(b=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(y=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?y:0,c=(I=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?I:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let F=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(F).catch(z=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:z})}),r.liveLastOffset=F}else{let F=this.element.currentTime*1e3;($=this.videoBufferManager)==null||$.maintain(F),(V=this.audioBufferManager)==null||V.maintain(F),r.position=F}this.tracer.log("stallIntervalCallback",Na(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=rc(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return P(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return P(this,null,function*(){var r,s,n,o,u;sr(this.element),sr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ut(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(qy(this.element)||qy(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Na({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Fa(this.element)&&Fa(this.source)&&Fa(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}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.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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=BD(this.tracer.error.bind(this.tracer));this.subscription.add(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 P(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.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=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i=C(A({},i),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Na(i)))}}};var Mn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Dn=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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=A({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*at(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Hy=`attribute vec2 a_vertex;
70
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Ul=B(Nt(),1);import{videoSizeToQuality as ED}from"@vkontakte/videoplayer-shared/es2015";var gy=({id:a,width:e,height:t,bitrate:i,fps:r,quality:s,streamId:n})=>{var u;let o=(u=s?_t(s):void 0)!=null?u:ED({width:e,height:t});return o&&{id:a,quality:o,bitrate:i,size:{width:e,height:t},fps:r,streamId:n}},vy=({id:a,bitrate:e})=>({id:a,bitrate:e}),Sy=({language:a,label:e},{id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),yy=({language:a,label:e,id:t,url:i,isAuto:r})=>({id:t,url:i,isAuto:r,type:"internal",language:a,label:e}),Hl=({id:a,language:e,label:t,codecs:i,isDefault:r})=>({id:a,language:e,label:t,codec:(0,Ul.default)(i.split("."),0),isDefault:r}),jl=({id:a,language:e,label:t,hdr:i,codecs:r})=>({id:a,language:e,hdr:i,label:t,codec:(0,Ul.default)(r.split("."),0)}),Ql=a=>"url"in a,xe=a=>a.type==="template",$a=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Iy=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},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),r=(i==null?void 0:i[1])==="-"?-1:1,s={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},yt=(a,e)=>{let t=a;t=(0,Gl.default)(t,"$$","$");let i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[r,s]of(0,Ey.default)(i)){let n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=(0,Gl.default)(t,n,(o,u)=>Ty(s)?o:Ty(u)?s:(0,xy.default)(s,parseInt(u,10),"0"))}return t},wy=(a,e)=>{var z,w,H,M,j,ee,le,T,L,K,x,D,me,Ti,dt,W,ye,Pe,we,tt,pt,Pt,zt,Ii,cr,Mc,Dc,Cc,Vc,Oc,Bc,_c,Nc,Fc,qc,Uc,Hc,jc,Qc,Gc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td,id,rd,ad,sd,nd,od,ud,ld,cd,dd,pd,hd;let i=new DOMParser().parseFromString(a,"application/xml"),r={video:[],audio:[],text:[]},s=i.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Qe=>{var Z,Kt;return(Kt=(Z=Qe.textContent)==null?void 0:Z.trim())!=null?Kt:""}),o=(z=(0,Py.default)(n,0))!=null?z:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=s.getAttribute("publishTime"),d=s.getElementsByTagName("vk:Attrs")[0],h=d==null?void 0:d.getElementsByTagName("vk:XLatestSegmentPublishTime")[0].textContent,p=d==null?void 0:d.getElementsByTagName("vk:XStreamIsLive")[0].textContent,m=d==null?void 0:d.getElementsByTagName("vk:XStreamIsUnpublished")[0].textContent,b=d==null?void 0:d.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,g;u&&(g={availabilityStartTime:l?new Date(l).getTime():0,publishTime:c?new Date(c).getTime():0,latestSegmentPublishTime:h?new Date(h).getTime():0,streamIsAlive:p==="yes",streamIsUnpublished:m==="yes"});let v,S=s.getAttribute("mediaPresentationDuration"),y=[...s.getElementsByTagName("Period")],E=y.reduce((Qe,Z)=>C(A({},Qe),{[Z.id]:Z.children}),{}),I=y.reduce((Qe,Z)=>C(A({},Qe),{[Z.id]:Z.getAttribute("duration")}),{});S?v=Iy(S):(0,Wl.default)(I).filter(Qe=>Qe).length&&!u?v=(0,Wl.default)(I).reduce((Qe,Z)=>{var Kt;return Qe+((Kt=Iy(Z))!=null?Kt:0)},0):b&&(v=parseInt(b,10));let $=0,O=(H=(w=s.getAttribute("profiles"))==null?void 0:w.split(","))!=null?H:[];for(let Qe of y.map(Z=>Z.id))for(let Z of E[Qe]){let Kt=(M=Z.getAttribute("id"))!=null?M:"id"+($++).toString(10),dr=(j=Z.getAttribute("mimeType"))!=null?j:"",Jn=(ee=Z.getAttribute("codecs"))!=null?ee:"",Zn=(le=Z.getAttribute("contentType"))!=null?le:dr==null?void 0:dr.split("/")[0],zT=(L=(T=Z.getAttribute("profiles"))==null?void 0:T.split(","))!=null?L:[],md=(x=by((K=Z.getAttribute("lang"))!=null?K:""))!=null?x:{},es=(Ti=(me=(D=Z.querySelector("Label"))==null?void 0:D.textContent)==null?void 0:me.trim())!=null?Ti:void 0,KT=Z.querySelectorAll("Representation"),XT=Z.querySelector("SegmentTemplate"),JT=(W=(dt=Z.querySelector("Role"))==null?void 0:dt.getAttribute("value"))!=null?W:void 0,Ei=Zn,ae={id:Kt,language:md.language,isDefault:JT==="main",label:es,codecs:Jn,hdr:Ei==="video"&&Fl(Jn),mime:dr,representations:[]};for(let J of KT){let wt=(ye=J.getAttribute("lang"))!=null?ye:void 0,pr=(we=(Pe=es!=null?es:Z.getAttribute("label"))!=null?Pe:J.getAttribute("label"))!=null?we:void 0,ts=(Pt=(pt=(tt=J.querySelector("BaseURL"))==null?void 0:tt.textContent)==null?void 0:pt.trim())!=null?Pt:"",Xt=new URL(ts||o,e).toString(),At=(zt=J.getAttribute("mimeType"))!=null?zt:dr,is=(cr=(Ii=J.getAttribute("codecs"))!=null?Ii:Jn)!=null?cr:"",rs;if(Zn==="text"){let kt=J.getAttribute("id")||"",as=((Mc=md.privateuse)==null?void 0:Mc.includes("x-auto"))||kt.includes("_auto"),Jt=J.querySelector("SegmentTemplate");if(Jt){let hr={representationId:(Dc=J.getAttribute("id"))!=null?Dc:void 0,bandwidth:(Cc=J.getAttribute("bandwidth"))!=null?Cc:void 0},ss=parseInt((Vc=J.getAttribute("bandwidth"))!=null?Vc:"",10)/1e3,ns=(Bc=parseInt((Oc=Jt.getAttribute("startNumber"))!=null?Oc:"",10))!=null?Bc:1,xi=parseInt((_c=Jt.getAttribute("timescale"))!=null?_c:"",10),eo=(Nc=Jt.querySelectorAll("SegmentTimeline S"))!=null?Nc:[],Pi=Jt.getAttribute("media");if(!Pi)continue;let os=[],us=0,ls="",wi=0,mr=ns,Te=0;for(let Ge of eo){let Zt=parseInt((Fc=Ge.getAttribute("d"))!=null?Fc:"",10),Fe=parseInt((qc=Ge.getAttribute("r"))!=null?qc:"",10)||0,Rt=parseInt((Uc=Ge.getAttribute("t"))!=null?Uc:"",10);Te=Number.isFinite(Rt)?Rt:Te;let ei=Zt/xi*1e3,Lt=Te/xi*1e3;for(let it=0;it<Fe+1;it++){let $t=yt(Pi,C(A({},hr),{segmentNumber:mr.toString(10),segmentTime:(Te+it*Zt).toString(10)})),Ai=(Lt!=null?Lt:0)+it*ei,br=Ai+ei;mr++,os.push({time:{from:Ai,to:br},url:$t})}Te+=(Fe+1)*Zt,us+=(Fe+1)*ei}wi=Te/xi*1e3,ls=yt(Pi,C(A({},hr),{segmentNumber:mr.toString(10),segmentTime:Te.toString(10)}));let fr={time:{from:wi,to:1/0},url:ls},ht={type:"template",baseUrl:Xt,segmentTemplateUrl:Pi,initUrl:"",totalSegmentsDurationMs:us,segments:os,nextSegmentBeyondManifest:fr,timescale:xi};rs={id:kt,kind:"text",segmentReference:ht,profiles:[],duration:v,bitrate:ss,mime:"",codecs:"",width:0,height:0,isAuto:as}}else rs={id:kt,isAuto:as,kind:"text",url:Xt}}else{let kt=(jc=(Hc=J.getAttribute("contentType"))!=null?Hc:At==null?void 0:At.split("/")[0])!=null?jc:Zn,as=(Gc=(Qc=Z.getAttribute("profiles"))==null?void 0:Qc.split(","))!=null?Gc:[],Jt=parseInt((Wc=J.getAttribute("width"))!=null?Wc:"",10),hr=parseInt((Yc=J.getAttribute("height"))!=null?Yc:"",10),ss=parseInt((zc=J.getAttribute("bandwidth"))!=null?zc:"",10)/1e3,ns=(Kc=J.getAttribute("frameRate"))!=null?Kc:"",xi=(Xc=J.getAttribute("quality"))!=null?Xc:void 0,eo=ns?fy(ns):void 0,Pi=(Jc=J.getAttribute("id"))!=null?Jc:"id"+($++).toString(10),os=kt==="video"?`${hr}p`:kt==="audio"?`${ss}Kbps`:is,us=`${Pi}@${os}`,ls=[...O,...zT,...as],wi,mr=J.querySelector("SegmentBase"),Te=(Zc=J.querySelector("SegmentTemplate"))!=null?Zc:XT;if(mr){let ht=(td=(ed=J.querySelector("SegmentBase Initialization"))==null?void 0:ed.getAttribute("range"))!=null?td:"",[Ge,Zt]=ht.split("-").map($t=>parseInt($t,10)),Fe={from:Ge,to:Zt},Rt=(id=J.querySelector("SegmentBase"))==null?void 0:id.getAttribute("indexRange"),[ei,Lt]=Rt?Rt.split("-").map($t=>parseInt($t,10)):[],it=Rt?{from:ei,to:Lt}:void 0;wi={type:"byteRange",url:Xt,initRange:Fe,indexRange:it}}else if(Te){let ht={representationId:(rd=J.getAttribute("id"))!=null?rd:void 0,bandwidth:(ad=J.getAttribute("bandwidth"))!=null?ad:void 0},Ge=parseInt((sd=Te.getAttribute("timescale"))!=null?sd:"",10),Zt=(nd=Te.getAttribute("initialization"))!=null?nd:"",Fe=Te.getAttribute("media"),Rt=(ud=parseInt((od=Te.getAttribute("startNumber"))!=null?od:"",10))!=null?ud:1,ei=yt(Zt,ht);if(!Fe)throw new ReferenceError("No media attribute in SegmentTemplate");let Lt=(ld=Te.querySelectorAll("SegmentTimeline S"))!=null?ld:[],it=[],$t=0,Ai="",br=0;if(Lt.length){let cs=Rt,We=0;for(let ki of Lt){let rt=parseInt((cd=ki.getAttribute("d"))!=null?cd:"",10),ti=parseInt((dd=ki.getAttribute("r"))!=null?dd:"",10)||0,ds=parseInt((pd=ki.getAttribute("t"))!=null?pd:"",10);We=Number.isFinite(ds)?ds:We;let to=rt/Ge*1e3,io=We/Ge*1e3;for(let ps=0;ps<ti+1;ps++){let eI=yt(Fe,C(A({},ht),{segmentNumber:cs.toString(10),segmentTime:(We+ps*rt).toString(10)})),fd=(io!=null?io:0)+ps*to,tI=fd+to;cs++,it.push({time:{from:fd,to:tI},url:eI})}We+=(ti+1)*rt,$t+=(ti+1)*to}br=We/Ge*1e3,Ai=yt(Fe,C(A({},ht),{segmentNumber:cs.toString(10),segmentTime:We.toString(10)}))}else if(xD(v)){let We=parseInt((hd=Te.getAttribute("duration"))!=null?hd:"",10)/Ge*1e3,ki=Math.ceil(v/We),rt=0;for(let ti=1;ti<ki;ti++){let ds=yt(Fe,C(A({},ht),{segmentNumber:ti.toString(10),segmentTime:rt.toString(10)}));it.push({time:{from:rt,to:rt+We},url:ds}),rt+=We}br=rt,Ai=yt(Fe,C(A({},ht),{segmentNumber:ki.toString(10),segmentTime:rt.toString(10)}))}let ZT={time:{from:br,to:1/0},url:Ai};wi={type:"template",baseUrl:Xt,segmentTemplateUrl:Fe,initUrl:ei,totalSegmentsDurationMs:$t,segments:it,nextSegmentBeyondManifest:ZT,timescale:Ge}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!kt||!At)continue;let fr={video:"video",audio:"audio",text:"text"}[kt];if(!fr)continue;Ei||(Ei=fr),rs={id:us,kind:fr,segmentReference:wi,profiles:ls,duration:v,bitrate:ss,mime:At,codecs:is,width:Jt,height:hr,fps:eo,quality:xi}}ae.language||(ae.language=wt),ae.label||(ae.label=pr),ae.mime||(ae.mime=At),ae.codecs||(ae.codecs=is),ae.hdr||(ae.hdr=Ei==="video"&&Fl(is)),ae.representations.push(rs)}if(Ei){let J=r[Ei].find(wt=>wt.id===ae.id);if(J&&ae.representations.every(wt=>xe(wt.segmentReference)))for(let wt of J.representations){let pr=ae.representations.find(At=>At.id===wt.id),ts=pr==null?void 0:pr.segmentReference,Xt=wt.segmentReference;Xt.segments.push(...ts.segments),Xt.nextSegmentBeyondManifest=ts.nextSegmentBeyondManifest}else r[Ei].push(ae)}}return{duration:v,streams:r,baseUrls:n,live:g}};var ky=B(qe(),1);import{isNonNullable as Ay}from"@vkontakte/videoplayer-shared/es2015";var ne=(a,e)=>Ay(a)&&Ay(e)&&a.readyState==="open"&&(0,ky.default)([...a.activeSourceBuffers],e);var Ma=class{constructor(e,t,i,{fetcher:r,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new bi(0);this.currentLowLatencySegmentLength$=new bi(0);this.currentSegmentLength$=new bi(0);this.onLastSegment$=new bi(!1);this.fullyBuffered$=new bi(!1);this.playingRepresentation$=new bi(void 0);this.playingRepresentationInit$=new bi(void 0);this.error$=new wD;this.gaps=[];this.subscription=new AD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new ve;this.switchAbortController=new ve;this.destroyAbortController=new ve;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=jt(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){let t=this.representations.get(e);De(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new xS(this.sourceBuffer),this.subscription.add(zl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Tt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Tt.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(zl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Tt.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ne(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,Ml(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=this.getForwardBufferDuration(o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c).catch(d=>{this.handleAsyncError(d,"pruneBuffer")})})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let i=this.initData.get(t.id),r=this.segments.get(t.id),s=this.parsedInitData.get(t.id);De(i,"No init buffer for starting representation"),De(r,"No segments for starting representation"),i instanceof ArrayBuffer&&(this.searchGaps(r,t),yield this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchTo=jt(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(!ne(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);De(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Se(s)||Se(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),De(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ne(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();ir(n)&&!this.isLive&&(this.bufferLimit=1/0,yield new ms(this.pruneBuffer(n,1/0,!0))),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}this.maintain()}})}.bind(this));this.switchToOld=jt(this.destroyAbortController.signal,function(e,t=!1){return oe(this,null,function*(){if(!ne(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let i=this.representations.get(e);De(i,`No such representation ${e}`);let r=this.segments.get(e),s=this.initData.get(e);if(Se(s)||Se(r)?yield this.loadInit(i,"high",!1):s instanceof Promise&&(yield s),r=this.segments.get(e),De(r,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ne(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();ir(n)&&(this.isLive||(this.bufferLimit=1/0,yield new ms(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=jt(this.destroyAbortController.signal,function(e){return oe(this,null,function*(){var u,l;let t=(u=(0,yn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(m=>m.id===c);d&&this.representations.set(c,d);let h=this.representations.get(c);if(!h||!xe(h.segmentReference))return;let p=this.getActualLiveStartingSegments(h.segmentReference);this.segments.set(h.id,p)}let i=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,r=this.representations.get(i);De(r);let s=this.segments.get(i);De(s,"No segments for starting representation");let n=this.initData.get(i);if(De(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,r),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=r,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.live),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(i.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(i.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchToWithPreviousAbort(e,t=!1){!ne(this.mediaSource,this.sourceBuffer)||e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new ve,jt(this.switchAbortController.signal,function(i,r=!1){return oe(this,null,function*(){this.switchingToRepresentationId=i;let s=this.representations.get(i);De(s,`No such representation ${i}`);let n=this.segments.get(i),o=this.initData.get(i);if(Se(o)||Se(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(i),De(n,"No segments for starting representation"),o=this.initData.get(i),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ne(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),r)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=i,yield this.dropBuffer();else{let u=this.getCurrentPosition();ir(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=i,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!Se(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return P(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ve,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Se(e)||Se(this.downloadingRepresentationId)||Se(this.playingRepresentationId)||Se(this.sourceBuffer)||!ne(this.mediaSource,this.sourceBuffer)||ir(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(De(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;let r=i.find(c=>e>=c.time.from&&e<c.time.to);ir(r)&&isFinite(r.time.from)&&isFinite(r.time.to)&&this.currentSegmentLength$.next((r==null?void 0:r.time.to)-r.time.from);let s=e,n=100;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=this.getForwardBufferDuration(e),d=r?r.time.to+n:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+n&&(s=d)}if(isFinite(this.bufferLimit)&&Ml(this.sourceBuffer.buffered)>=this.bufferLimit){let c=this.getForwardBufferDuration(e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,c<d).catch(h=>{this.handleAsyncError(h,"pruneBuffer")});return}let u=[];if(!this.activeSegments.size&&(u=this.selectForwardBufferSegments(i,t.segmentReference.type,s),u.length)){let c="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if((0,Sn.default)(u,r))c="high";else{let d=(0,rr.default)(u,0);d&&d.time.from-r.time.to>=this.forwardBufferTarget/2&&(c="low")}this.loadSegments(u,t,c).catch(d=>{this.handleAsyncError(d,"loadSegments")})}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status==="fed"&&!u.length&&this.getForwardBufferDuration(e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let l=(0,rr.default)(i,-1);!this.isLive&&l&&(this.fullyBuffered$.next(l.time.to-e-this.getForwardBufferDuration(e)<n),this.onLastSegment$.next(e-l.time.from>0))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let i=0,r=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:s.time.from+r}),i=s.time.to;ir(t.duration)&&t.duration-i>0&&!this.isLive&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[],s=0,n=t.length-1;do r.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<i&&n>=0);return this.liveInitialAdditionalOffset=s-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){let t=(0,yn.default)(e==null?void 0:e.streams[this.kind],r=>r.representations).find(r=>r.id===this.downloadingRepresentationId);if(!t)return;let i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var i,r,s,n;let t=(i=(0,yn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?i:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!xe(o.segmentReference))return;let u=o.segmentReference.segments.map(p=>C(A({},p),{status:"none",size:void 0})),l=100,c=(r=this.segments.get(o.id))!=null?r:[],d=(n=(s=(0,rr.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,h=u==null?void 0:u.findIndex(p=>d>=p.time.from+l&&d<=p.time.to+l);if(h===-1){this.liveUpdateSegmentIndex=0;let p=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,p)}else{let p=u.slice(h+1);this.segments.set(o.id,[...c,...p])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;De(e);let t=this.segments.get(e);if(t!=null&&t.length){let i=t[t.length-1];this.updateLowLatencyLiveIfNeeded(i)}}updateLowLatencyLiveIfNeeded(e){var i;let t=0;for(let r of this.representations.values()){let s=r.segmentReference;if(!xe(s))return;let n=(i=this.segments.get(r.id))!=null?i:[],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=yt(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 i=this.segments.get(t);if(!i)return;let r=i.find(u=>u.time.from<=e&&u.time.to>=e);return(o=r==null?void 0:r.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&aa&&aa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&aa&&aa(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,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){let i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){let r=e.findIndex(({status:d,time:{from:h,to:p}},m)=>{let b=h<=i&&p>=i,g=h>i||b||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=i+v||p<=i+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&ne(this.mediaSource,this.sourceBuffer)&&!(Ut(this.sourceBuffer.buffered,h)&&Ut(this.sourceBuffer.buffered,p)))&&g&&S});if(r===-1)return[];if(t!=="byteRange")return e.slice(r,r+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=r;d<s.length&&(n<=l||o<=c);d++){let h=s[d];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status==="none"||h.status==="partially_ejected")u.push(h);else break}return u}loadSegments(e,t,i="auto"){return P(this,null,function*(){xe(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return P(this,null,function*(){e.status="downloading";let r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield jt(o,function(){return oe(this,null,function*(){let c=Kl(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:i,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=vn(),!c)return;let d=new DataView(c),h=La(t.mime);if(!isFinite(r.segment.time.to)){let b=t.segmentReference.timescale;r.segment.time.to=h.getChunkEndTime(d,b)}u&&r.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:p,serverDataPreparedTime:m}=h.getServerLatencyTimestamps(d);p&&m&&this.currentLiveSegmentServerLatency$.next(m-p),r.segment.status="downloaded",this.onSegmentFullyAppended(r,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())xe(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,i="auto"){return P(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:r,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield jt(n,function(){return oe(this,null,function*(){let u=Kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),zl(window,"online").pipe(PD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:r,onProgress:o,signal:n,priority:i}),this.lastDataObtainedTimestampMs=vn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),$a(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(xe(t.segmentReference))throw new Error("Representation is not byte range type");let i=t.segmentReference.url,r={from:(0,rr.default)(e,0).byte.from,to:(0,rr.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:i,range:r,signal:s,onProgress:(o,u)=>P(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=vn(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Tt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!xe(t.segmentReference))throw new Error("Representation is not template type");let i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");let r=i.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=vn();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:Tt.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:r,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Sn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return P(this,arguments,function*({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:s}){if(!this.activeSegments.size||!ne(this.mediaSource,this.sourceBuffer))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){r();continue}if(u.loadedBytes=i,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=La(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 P(this,arguments,function*({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size||!ne(this.mediaSource,this.sourceBuffer))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-i,h=c.byte.to-i,p=h-d+1,m=d<r,b=h<=r;if(!m)continue;let g=La(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,p);(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(p,r-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===p?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===p&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var i;if(!(Se(this.sourceBuffer)||!ne(this.mediaSource,this.sourceBuffer))){!this.isLive&&q.browser.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(Ut(this.sourceBuffer.buffered,e.segment.time.from,100)&&Ut(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Tt.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",Ql(e.segment)&&(e.segment.size=e.fedBytes);for(let r of this.representations.values())if(r.id!==t)for(let s of(i=this.segments.get(r.id))!=null?i:[])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[r,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let i=this.representations.get(e);i&&(this.initLoadIdleCallback=Ll(()=>(0,Ry.default)(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return P(this,null,function*(){let r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?jt(this.destroyAbortController.signal,function(){return oe(this,null,function*(){let o=Kl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,La(e.mime),r)).then(o=>P(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let h=c;this.isLive&&xe(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:Tt.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return P(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,i=!1){return P(this,null,function*(){if(!this.sourceBuffer||!ne(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Se(e))return!1;let r=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:h}=u[c],p=l[l.length-1];p.to>=d?p.to=Math.max(p.to,h):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return r;r.push(A({},u.time)),r=n(r);let l=Ql(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let h of this.segments.values())for(let p of h)(0,Sn.default)(["none","partially_ejected"],p.status)&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let h={time:{from:l,to:c},url:"",status:"none"};o(h)}}if(r.length&&i){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 r.length?(yield Promise.all(r.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return P(this,null,function*(){if(!this.sourceBuffer||!ne(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||!ne(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(e=this.getCurrentPosition()){return!this.sourceBuffer||!ne(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Se(e)?0:Ji(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ne(this.mediaSource,this.sourceBuffer))){if(this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));for(let i of t){let r={representation:e,from:i.time.from,to:i.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<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(s=>r&&s.from===r.from&&s.to===r.to)&&this.gaps.push(r)}}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ne(this.mediaSource,this.sourceBuffer))){if(!this.tuning.useRefactoredSearchGap)for(let i=0;i<this.sourceBuffer.buffered.length;i++)this.gaps=this.gaps.filter(r=>this.sourceBuffer&&(Math.round(r.from)<Math.round(this.sourceBuffer.buffered.start(i)*1e3)||Math.round(r.to)>Math.round(this.sourceBuffer.buffered.end(i)*1e3)));this.gapDetectionIdleCallback=Ll(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:Tt.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Se(this.sourceBuffer)||!ne(this.mediaSource,this.sourceBuffer)||Se(this.playingRepresentationId))return;let e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){let r=Math.floor(this.sourceBuffer.buffered.start(i)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:s})}let t=100;for(let i of this.segments.values())for(let r of i){let{status:s}=r;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(r.time.from),o=Math.ceil(r.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?r.status="partially_ejected":this.gaps.some(c=>c.from===r.time.from||c.to===r.time.to)?r.status="partially_ejected":r.status="none")}}handleAsyncError(e,t){this.error$.next({id:t,category:Tt.VIDEO_PIPELINE,thrown:e,message:"Something went wrong"})}};var Da=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var Ly=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),i=e===null?"http1":e!=null?e:void 0,r=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:i,reused:r}};import{abortable as Ca,assertNever as My,fromEvent as Dy,merge as kD,now as Va,Subscription as RD,Subject as Cy,ValueSubject as Xl,flattenObject as ar,ErrorCategory as Oa}from"@vkontakte/videoplayer-shared/es2015";var $y=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var In=class{constructor({throughputEstimator:e,requestQuic:t,tracer:i,compatibilityMode:r=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Xl(void 0);this.lastConnectionReused$=new Xl(void 0);this.lastRequestFirstBytes$=new Xl(void 0);this.recoverableError$=new Cy;this.error$=new Cy;this.abortAllController=new ve;this.subscription=new RD;this.fetchManifest=Ca(this.abortAllController.signal,function(e){return oe(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),i=e;this.requestQuic&&(i=Da(i)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(i=$y(i));let r=yield this.doFetch(i,{signal:this.abortAllController.signal}).catch(Tn);return r?(t.log("success",ar({url:i,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(r.headers),r.text()):(t.error("error",ar({url:i,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Ca(this.abortAllController.signal,function(l){return oe(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:i,onProgress:r,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var j,ee,le;let c=e,d=new Headers,h=this.tracer.createComponentTracer("Fetch");if(i)switch(t){case 0:{d.append("Range",`bytes=${i.from}-${i.to}`);break}case 1:{let T=new URL(c,location.href);T.searchParams.append("bytes",`${i.from}-${i.to}`),c=T.toString();break}default:My(t)}this.requestQuic&&(c=Da(c));let p=this.abortAllController.signal,m;if(n){let T=new ve;if(m=kD(Dy(this.abortAllController.signal,"abort"),Dy(n,"abort")).subscribe(()=>{try{T.abort()}catch(L){Tn(L)}}),this.subscription.add(m),this.abortAllController.signal.aborted||n.aborted)try{T.abort()}catch(L){Tn(L)}p=T.signal}let b=Va();h.log("startRequest",ar({url:c,priority:s,rangeMethod:t,range:i,isLowLatency:u,requestStartedAt:b}));let g=yield this.doFetch(c,{priority:s,headers:d,signal:p}),v=Va();if(!g)return h.error("error",{message:"No response in request"}),h.end(),m==null||m.unsubscribe(),null;if((j=this.throughputEstimator)==null||j.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let T=`Fetch error ${g.status}: ${g.statusText}`;return h.error("error",{message:T}),h.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!r&&!o){m==null||m.unsubscribe();let T=Va(),L={requestStartedAt:b,requestEndedAt:T,duration:T-b};return h.log("endRequest",ar(L)),h.end(),g.arrayBuffer()}let S=g.body;if(o){let T;[S,T]=g.body.tee(),(ee=this.throughputEstimator)==null||ee.trackStream(T,u)}let y=S.getReader(),E,I=parseInt((le=g.headers.get("content-length"))!=null?le:"",10);Number.isFinite(I)&&(E=I),!E&&i&&(E=i.to-i.from+1);let $=0,O=E?new Uint8Array(E):new Uint8Array(0),F=!1,z=T=>{m==null||m.unsubscribe(),F=!0,Tn(T)},w=Ca(p,function(K){return oe(this,arguments,function*({done:T,value:L}){if($===0&&this.lastRequestFirstBytes$.next(Va()-b),p.aborted){m==null||m.unsubscribe();return}if(!T&&L){if(E)O.set(L,$),$+=L.byteLength;else{let x=new Uint8Array(O.length+L.length);x.set(O),x.set(L,O.length),O=x,$+=L.byteLength}r==null||r(new DataView(O.buffer),$),yield y==null?void 0:y.read().then(w,z)}})}.bind(this));yield y==null?void 0:y.read().then(w,z),m==null||m.unsubscribe();let H=Va(),M={failed:F,requestStartedAt:b,requestEndedAt:H,duration:H-b};return F?(h.error("endRequest",ar(M)),h.end(),null):(h.log("endRequest",ar(M)),h.end(),O.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Ca(this.abortAllController.signal,function(e,t,i){return oe(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:r,to:s}=e.initRange,n=r,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,r),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:i,measureThroughput:!1});if(!d)return null;let h=new DataView(d,r-n,s-n+1);if(!t.validateData(h))throw new Error("Invalid media file");let p=t.parseInit(h),m=(v=e.indexRange)!=null?v:t.getIndexRange(p);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:i,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,p,m);return{init:p,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Ca(this.abortAllController.signal,function(e,t){return oe(this,null,function*(){if(e.type!=="template")return null;let i=new URL(e.initUrl,e.baseUrl).toString(),r=yield this.fetch(i,{priority:t,measureThroughput:!1});return r?{init:null,segments:e.segments.map(n=>C(A({},n),{status:"none",size:void 0})),dataView:new DataView(r)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r,this.tracer=i.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:i}=Ly(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){return P(this,null,function*(){var s,n;let{type:r}=e;switch(r){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,i))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,i))!=null?n:null;default:My(r)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}doFetch(e,t){return P(this,null,function*(){let i=yield lt(e,t);if(i.ok)return i;let r=yield i.text(),s=parseInt(r);if(!isNaN(s))switch(s){case 1:this.recoverableError$.next({id:"VideoDataLinkExpiredError",message:"Video data links have expired",category:Oa.FATAL});break;case 8:this.recoverableError$.next({id:"VideoDataLinkBlockedForFloodError",message:"Url blocked for flood",category:Oa.FATAL});break;case 18:this.recoverableError$.next({id:"VideoDataLinkIllegalIpChangeError",message:"Client IP has changed",category:Oa.FATAL});break;case 21:this.recoverableError$.next({id:"VideoDataLinkIllegalHostChangeError",message:"Request HOST has changed",category:Oa.FATAL});break;default:this.error$.next({id:"GeneralVideoDataFetchError",message:`Generic video data fetch error (${s})`,category:Oa.FATAL})}})}},Tn=a=>{if(!$a(a))throw a};var gi=(a,e,t)=>t*e+(1-t)*a,Jl=(a,e)=>a.reduce((t,i)=>t+i,0)/e,Vy=(a,e,t,i)=>{let r=0,s=t,n=Jl(a,e),o=e<i?e:i;for(let u=0;u<o;u++)a[s]>n?r++:r--,s=(a.length+s-1)%a.length;return Math.abs(r)===o};import{isNullable as LD,ValueSubject as Oy}from"@vkontakte/videoplayer-shared/es2015";var Qt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var i;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Oy(e.initial),this.debounced$=new Oy(e.initial);let t=(i=e.label)!=null?i:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${t}`),this.smoothedSeries$=new Ie(`smoothed_${t}`),this.reportedSeries$=new Ie(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=at(this.pastMeasures[o]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;let r=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(LD(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 En=class extends Qt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=gi(this.slow,e,this.params.emaAlphaSlow),this.fast=gi(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var xn=class extends Qt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Jl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=gi(this.emaSmoothed,e,this.params.emaAlpha);let i=Vy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}};var Pn=class extends Qt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?gi(this.smoothed,t,this.params.emaAlpha):t}};var vi=class{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new En({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new xn({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Pn(A({initial:e,label:"liveEdgeDelay"},t))}};var Zl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as $D,ValueSubject as MD}from"@vkontakte/videoplayer-shared/es2015";var Ba=class a{constructor(e,t){this.currentRepresentation$=new MD(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(!$D(e))for(let i of this.representations)for(let r of i){let s=r.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(C(A({},r),{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 i=a.filterRepresentations(t.representations);if(i){this.representations[this.representationsCursor]=i,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&&xe(t.segmentReference))}};var An=B(Nt(),1);import{assertNever as kn}from"@vkontakte/videoplayer-shared/es2015";var By=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:i})=>{let{containers:r,protocols:s,codecs:n,nativeHlsSupported:o}=q.video,u=(n.h264||n.h265)&&n.aac,l=s.mse&&(!i||!!window.MediaStreamTrack)||s.mms&&t;return a.filter(c=>{switch(c){case"DASH_SEP":return l&&r.mp4&&u;case"DASH_WEBM":return l&&r.webm&&n.vp9&&n.opus;case"DASH_WEBM_AV1":return l&&r.webm&&n.av1&&n.opus;case"DASH_STREAMS":return l&&(r.mp4&&u||r.webm&&(n.vp9||n.av1)&&(n.opus||n.aac));case"DASH_LIVE":return l&&r.mp4&&u;case"DASH_LIVE_CMAF":return l&&r.mp4&&u&&r.cmaf;case"DASH_ONDEMAND":return l&&r.mp4&&u;case"HLS":case"HLS_ONDEMAND":return o||e&&l&&r.mp4&&u;case"HLS_LIVE":case"HLS_LIVE_CMAF":return o;case"MPEG":return r.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return s.webrtc&&s.ws&&n.h264&&(r.mp4||r.webm);default:return kn(c)}})},wn=a=>{let{webmDecodingInfo:e}=q.video,t="DASH_WEBM",i="DASH_WEBM_AV1";switch(a){case"vp9":return[t,i];case"av1":return[i,t];case"none":return[];case"smooth":return e?e[i].smooth?[i,t]:e[t].smooth?[t,i]:[i,t]:[t,i];case"power_efficient":return e?e[i].powerEfficient?[i,t]:e[t].powerEfficient?[t,i]:[i,t]:[t,i];default:kn(a)}return[t,i]},_y=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let i=[...t?["DASH_STREAMS"]:[],...wn(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],r=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(q.device.isAndroid)switch(e){case"mpeg":return["MPEG",...i,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...i,"MPEG"];case"dash":return[...i,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...r,"MPEG",...wn(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...wn(a),"MPEG",...r,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...wn(a),...r,"HLS","HLS_ONDEMAND"];default:kn(e)}return q.video.nativeHlsSupported?[...i,"HLS","HLS_ONDEMAND","MPEG"]:[...i,"HLS","HLS_ONDEMAND","MPEG"]},Ny=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let i=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],r=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...i,...r],n=[...r,...i],o,u=q.device.isMac&&q.browser.isSafari;if(q.device.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:kn(a)}else q.video.nativeHlsSupported&&!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"]},ec=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Fy=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,An.default)(t.value.split("."),0)}for(let t of a){let i=(0,An.default)(t.split("."),0);if(i==="opus"||i==="vp09"||i==="av01")return i}let e=a.values().next();return(0,An.default)(e.value.split("."),0)};var qD=["timeupdate","progress","play","seeked","stalled","waiting"],UD=["timeupdate","progress","loadeddata","playing","seeked"];var $n=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Hy;this.representationSubscription=new Hy;this.state$=new _("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 Ln;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.isActiveLive$=new ie(!1);this.isLowLatency$=new ie(!1);this.liveDuration$=new ie(0);this.liveSeekableDuration$=new ie(0);this.liveAvailabilityStartTime$=new ie(0);this.liveStreamStatus$=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.currentStallDuration$=new ie(0);this.videoLastDataObtainedTimestamp$=new ie(0);this.fetcherRecoverableError$=new Ln;this.fetcherError$=new Ln;this.liveStreamEndTimestamp=0;this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.forceEnded$=new Ln;this.gapWatchdogActive=!1;this.destroyController=new ve;this.initManifest=ic(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var r;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=ge(t,i,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(r=this.manifest)!=null&&r.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:ct.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=ic(this.destroyController.signal,function(){return oe(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:ct.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=wy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=vS(e))!=null?n:{id:"ManifestParsing",category:ct.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let i=(u,l,c)=>{var d,h,p,m;return!!((h=(d=this.element)==null?void 0:d.canPlayType)!=null&&h.call(d,l)&&((m=(p=Je())==null?void 0:p.isTypeSupported)!=null&&m.call(p,`${l}; codecs="${c}"`))||u==="text")};if(t.live){this.isLive$.next(!!t.live);let{availabilityStartTime:u,latestSegmentPublishTime:l,streamIsUnpublished:c,streamIsAlive:d}=t.live,h=((o=t.duration)!=null?o:0)/1e3;this.liveSeekableDuration$.next(-1*h),this.liveDuration$.next((l-u)/1e3),this.liveAvailabilityStartTime$.next(t.live.availabilityStartTime);let p="active";d||(p=c?"unpublished":"unexpectedly_down"),this.liveStreamStatus$.next(p)}let r={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:p,codecs:m})=>i(u,p,m)),d=new Set(c.map(({codecs:p})=>p)),h=Fy(d);if(h&&(r[u]=c.filter(({codecs:p})=>p.startsWith(h))),u==="video"){let p=this.tuning.preferHDR,m=r.video.some(g=>g.hdr),b=r.video.some(g=>!g.hdr);q.display.isHDR&&p&&m?r.video=r.video.filter(g=>g.hdr):b&&(r.video=r.video.filter(g=>!g.hdr))}}let s=C(A({},t),{streams:r});return this.tracer.log("updateManifestEnd",Na(s)),s})}.bind(this));this.initRepresentations=ic(this.destroyController.signal,function(e,t,i){return oe(this,null,function*(){var h;this.tracer.log("initRepresentationsStart",Na({initialVideo:e,initialAudio:t,sourceHls:i})),sr(this.manifest),sr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let r=p=>{this.representationSubscription.add(It(p,"error").pipe(Rn(m=>{var b;return!!((b=this.element)!=null&&b.played.length)})).subscribe(m=>{this.error$.next({id:"VideoSource",category:ct.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:m})}))};this.source=this.tuning.useManagedMediaSource?Ng():new MediaSource;let s=document.createElement("source");if(r(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&an())if(i){let p=document.createElement("source");r(p),p.type="application/x-mpegurl",p.src=i.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLive$.next(this.isLive$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,m)=>[...p,...m.representations],[]);if(this.videoBufferManager=new Ma("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Fa(t)){let p=this.manifest.streams.audio.reduce((m,b)=>[...m,...b.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$));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Si(...UD.map(p=>It(this.element,p))).pipe(or(p=>this.element?Ji(this.element.buffered,this.element.currentTime*1e3):0),_a(),ND(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Si(It(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.subscription.add(this.liveDuration$.pipe(_a()).subscribe(m=>this.liveStreamEndTimestamp=ac())),this.subscription.add(It(this.element,"pause").subscribe(()=>{this.livePauseWatchdogSubscription=rc(1e3).subscribe(m=>{let b=Xs(this.manifestUrlString,2);this.manifestUrlString=ge(this.manifestUrlString,b+1e3,2),this.liveStreamStatus$.getValue()==="active"&&this.updateManifest()}),this.subscription.add(this.livePauseWatchdogSubscription)})).add(It(this.element,"play").subscribe(m=>{var b;return(b=this.livePauseWatchdogSubscription)==null?void 0:b.unsubscribe()})),this.representationSubscription.add(nr({isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(or(({isActiveLive:m,isLowLatency:b})=>m&&b),_a()).subscribe(m=>{this.isManualDecreasePlaybackInLive()||Zl(this.element,1)})),this.representationSubscription.add(nr({bufferLength:this.bufferLength$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).pipe(Rn(({bufferLength:m,isActiveLive:b,isLowLatency:g})=>b&&g&&!!m)).subscribe(({bufferLength:m})=>this.liveBuffer.next(m))),this.representationSubscription.add(this.videoBufferManager.currentLowLatencySegmentLength$.subscribe(m=>{if(!this.isActiveLive$.getValue()&&!this.isLowLatency$.getValue()&&!m)return;let b=this.liveSeekableDuration$.getValue()-m/1e3;this.liveSeekableDuration$.next(Math.max(b,-1*this.tuning.dashCmafLive.maxLiveDuration)),this.liveDuration$.next(this.liveDuration$.getValue()+m/1e3)})),this.representationSubscription.add(nr({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Rn(({isLive:m})=>m),_a((m,b)=>b.bufferLength<m.bufferLength),or(({rtt:m,bufferLength:b,segmentServerLatency:g})=>{let v=Xs(this.manifestUrlString,2);return(m/2+b+g+v)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(nr({liveBuffer:this.liveBuffer.smoothed$,isActiveLive:this.isActiveLive$,isLowLatency:this.isLowLatency$}).subscribe(({liveBuffer:m,isActiveLive:b,isLowLatency:g})=>{if(!g||!b)return;let v=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,S=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,y=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=m-v;if(this.isManualDecreasePlaybackInLive())return;let I=1;Math.abs(E)>S&&(I=1+Math.sign(E)*y),Zl(this.element,I)})),this.representationSubscription.add(this.bufferLength$.subscribe(m=>{var g,v;let b=0;if(m){let S=((v=(g=this.element)==null?void 0:g.currentTime)!=null?v:0)*1e3;b=Math.min(...this.bufferManagers.map(E=>{var I,$;return($=(I=E.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?$:S}))-S}this.liveLoadBufferLength$.getValue()!==b&&this.liveLoadBufferLength$.next(b)}));let p=0;this.representationSubscription.add(nr({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(FD(1e3)).subscribe(g=>P(this,[g],function*({liveLoadBufferLength:m,bufferLength:b}){if(!this.element||this.isUpdatingLive)return;let v=this.element.playbackRate,S=Xs(this.manifestUrlString,2),y=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,E=Math.min(y,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*v),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*v,$=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*v,O=isFinite(m)?m:b,F=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),z=y<=this.tuning.live.activeLiveDelay;this.isActiveLive$.next(z);let w="none";if(F?w="active_low_latency":this.isLowLatency$.getValue()&&z?(this.bufferManagers.forEach(H=>H.proceedLowLatencyLive()),w="active_low_latency"):S!==0&&O<E?w="live_forward_buffering":O<E+$&&(w="live_with_target_offset"),isFinite(m)&&(p=m>p?m:p),w==="live_forward_buffering"||w==="live_with_target_offset"){let H=p-(E+I),M=this.normolizeLiveOffset(Math.trunc(S+H/v)),j=Math.abs(M-S),ee=0;!m||j<=this.tuning.dashCmafLive.offsetCalculationError?ee=S:M>0&&j>this.tuning.dashCmafLive.offsetCalculationError&&(ee=M),this.manifestUrlString=ge(this.manifestUrlString,ee,2)}(w==="live_with_target_offset"||w==="live_forward_buffering")&&(p=0,yield this.updateLive())}),m=>{this.error$.next({id:"updateLive",category:ct.VIDEO_PIPELINE,thrown:m,message:"Failed to update live with subscription"})}))}let l=Si(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(or(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Si(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(or(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue()))),d=nr({allBuffersFull:l,someBufferEnded:c}).pipe(_a(),or(({allBuffersFull:p,someBufferEnded:m})=>p&&m),Rn(p=>p));if(this.representationSubscription.add(Si(this.forceEnded$,d).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(m=>!m.updating))try{(p=this.source)==null||p.endOfStream()}catch(m){this.error$.next({id:"EndOfStream",category:ct.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:m})}})),this.representationSubscription.add(Si(...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"){let p=this.tuning.dash.sourceOpenTimeout>=0;yield new Promise((m,b)=>{var g;p&&(this.timeoutSourceOpenId=setTimeout(()=>{var v;if(((v=this.source)==null?void 0:v.readyState)==="open"){m();return}this.tuning.dash.rejectOnSourceOpenTimeout?b(new Error("Timeout reject when wait sourceopen event")):m()},this.tuning.dash.sourceOpenTimeout)),(g=this.source)==null||g.addEventListener("sourceopen",()=>{this.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),m()},{once:!0})})}if(!this.isLive$.getValue()){let p=[(h=this.manifest.duration)!=null?h:0,...(0,sc.default)((0,sc.default)([...this.manifest.streams.audio,...this.manifest.streams.video],m=>m.representations),m=>{let b=[];return m.duration&&b.push(m.duration),xe(m.segmentReference)&&m.segmentReference.totalSegmentsDurationMs&&b.push(m.segmentReference.totalSegmentsDurationMs),b})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Fa(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,i,r,s;if(!this.element||!this.videoBufferManager||((t=this.source)==null?void 0:t.readyState)!=="open")return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(i=this.audioBufferManager)==null||i.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(s=this.audioBufferManager)!=null&&s.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=rc(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:ct.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new In({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.subscription.add(this.fetcher.recoverableError$.subscribe(this.fetcherRecoverableError$)),this.subscription.add(this.fetcher.error$.subscribe(this.fetcherError$)),this.liveBuffer=vi.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,A({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return P(this,null,function*(){var r,s,n;sr(this.element);let t=this.liveStreamStatus$.getValue()!=="active"?ac()-this.liveStreamEndTimestamp:0,i=this.normolizeLiveOffset(e+t);this.isActiveLive$.next(i===0),this.manifestUrlString=ge(this.manifestUrlString,i,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(s=this.audioBufferManager)==null?void 0:s.seekLive(this.manifest.streams.audio),(n=this.liveTextManager)==null||n.seekLive(this.manifest.streams.text))})}initBuffer(){sr(this.element),this.state$.setState("running"),this.subscription.add(Si(...qD.map(e=>It(this.element,e)),It(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:ct.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(It(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(It(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&Ut(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var p,m,b,g,v,S,y,E,I,$,O;if(!this.element||((p=this.source)==null?void 0:p.readyState)!=="open")return;let i=this.currentStallDuration$.getValue();i+=50,this.currentStallDuration$.next(i);let r={timeInWaiting:i},s=ac(),n=100,o=(b=(m=this.videoBufferManager)==null?void 0:m.lastDataObtainedTimestamp)!=null?b:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(v=(g=this.audioBufferManager)==null?void 0:g.lastDataObtainedTimestamp)!=null?v:0,l=(y=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?y:0,c=(I=(E=this.audioBufferManager)==null?void 0:E.getForwardBufferDuration())!=null?I:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,h=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||h)&&i>this.tuning.dash.crashOnStallTWithoutDataTimeout||i>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${i} ms`);if(this.isLive$.getValue()&&i%2e3===0){let F=this.normolizeLiveOffset(-1*this.livePositionFromPlayer$.getValue()*1e3);this.seekLive(F).catch(z=>{this.error$.next({id:"stallIntervalCallback",category:ct.VIDEO_PIPELINE,message:"stallIntervalCallback failed",thrown:z})}),r.liveLastOffset=F}else{let F=this.element.currentTime*1e3;($=this.videoBufferManager)==null||$.maintain(F),(O=this.audioBufferManager)==null||O.maintain(F),r.position=F}this.tracer.log("stallIntervalCallback",Na(r))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=rc(50).subscribe(e,i=>{this.error$.next({id:"StallWatchdogCallback",category:ct.NETWORK,message:"Can't restore DASH after stall.",thrown:i})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,i=!1){return P(this,null,function*(){let r={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return this.tuning.useNewSwitchTo?this.currentStallDuration$.getValue()>0?r==null?void 0:r.switchToWithPreviousAbort(t,i):r==null?void 0:r.switchTo(t,i):r==null?void 0:r.switchToOld(t,i)})}seek(e,t){return P(this,null,function*(){var r,s,n,o,u;sr(this.element),sr(this.videoBufferManager);let i;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?i=e:i=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!=null?r:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),this.warmUpMediaSourceIfNeeded(i),Ut(this.element.buffered,i)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),!(Uy(this.element)||Uy(this.videoBufferManager))&&(this.videoBufferManager.maintain(i),(u=this.audioBufferManager)==null||u.maintain(i),this.element.currentTime=i/1e3,this.tracer.log("seek",Na({requestedPosition:e,forcePrecise:t,position:i})))})}warmUpMediaSourceIfNeeded(e=(t=>(t=this.element)==null?void 0:t.currentTime)()){var i;Fa(this.element)&&Fa(this.source)&&Fa(e)&&((i=this.source)==null?void 0:i.readyState)==="ended"&&this.element.duration*1e3-e>this.tuning.dash.seekBiasInTheEnd&&this.bufferManagers.forEach(r=>r.warmUpMediaSource())}get isStreamEnded(){var e;return((e=this.source)==null?void 0:e.readyState)==="ended"}stop(){var e,t,i;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(r=>{URL.revokeObjectURL(r.src),r.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(i=this.audioBufferManager)==null||i.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}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.timeoutSourceOpenId&&clearTimeout(this.timeoutSourceOpenId),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=_D(this.tracer.error.bind(this.tracer));this.subscription.add(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 P(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(i=>i.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=this.isActiveLive$.getValue()&&this.isLowLatency$.getValue(),i={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:t,initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!t&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,s=[],n=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let o of this.bufferManagers)for(let u of o.gaps)o.playingRepresentation$.getValue()===u.representation&&u.from-n<=r&&u.to+n>r&&(this.element.duration*1e3-u.to<this.tuning.endGapTolerance?s.push(1/0):s.push(u.to));if(s.length){let o=Math.max(...s)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,o===1/0?this.forceEnded$.next():(this.element.currentTime=o/1e3,i=C(A({},i),{gapEnds:s,jumpTo:o,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",Na(i)))}}};var Mn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Dn=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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);let r=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed=A({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){let r=-this.fadeCorrection*at(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var jy=`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 jy=`#ifdef GL_ES
81
+ `;var Qy=`#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 Cn=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Mn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Dn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Hy,this.gl.VERTEX_SHADER),i=this.createShader(jy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,h=t+r;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as jD,now as Qy,Subscription as QD,filter as GD,combine as Gy,debounce as WD,ValueSubject as nc,isNonNullable as YD}from"@vkontakte/videoplayer-shared/es2015";var oc=class{constructor(){this.isSeeked$=new nc(!1);this.isBuffering$=new nc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new QD;this.severeStallOccurred$=new nc(!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(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(Gy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(WD(this.qualityLimitsOnStall.stallDurationToBeCount),GD(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(Gy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if(jD(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Qy(),d=r&&this.currentStallsCount>=r,h=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,YD(this.lastUniqueVideoTrackSelected.bitrate)&&u>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=Qy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Wy=oc;import{combine as zD,map as KD,observeElementSize as XD,Subscription as JD,ValueSubject as uc,noop as ZD}from"@vkontakte/videoplayer-shared/es2015";var Vn=class{constructor(){this.subscription=new JD;this.pipSize$=new uc(void 0);this.videoSize$=new uc(void 0);this.elementSize$=new uc(void 0);this.pictureInPictureWindowRemoveEventListener=ZD}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(XD(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(zD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(KD(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).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 yi=class{constructor(e){this.subscription=new sC;this.videoState=new _("stopped");this.droppedFramesManager=new mn;this.stallsManager=new Wy;this.elementSizeManager=new Vn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Wr;this.audioTrackSwitchHistory=new Wr;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),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"),R(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"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return tC(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Cn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((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 He(e.source.url),this.params=e,this.video=Ae(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(de(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 $n({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,i=$e(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:Yy.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(zy(l=>!!l.length),Xy()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(lc(l=>l.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$:i.isBuffering$,looped$:i.looped$}),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.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(zy(Ky),Xy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(lc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ue(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(iC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of c.audio){h.push(Hl(p));let m=[];for(let b of p.representations){let g=gy(b);m.push(g),this.audioTracksMap.set(g,{stream:p,representation:b})}this.audioStreamsMap.set(p,m)}this.params.output.availableAudioStreams$.next(h)}let d=[];for(let h of c.video){d.push(jl(h));let p=[];for(let m of h.representations){let b=by(C(A({},m),{streamId:h.id}));b&&(p.push(b),this.videoTracksMap.set(b,{stream:h,representation:m}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(d);for(let h of c.text)for(let p of h.representations){let m=vy(h,p);this.textTracksMap.set(m,{stream:h,representation:p})}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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(On(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$,aC(this.video,"progress")).subscribe(()=>P(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,Jy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[h,p]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===h.id});Ky(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,g)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(qa()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:h}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(jl(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(qa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:h}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Hl(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(lc(({to:l})=>l==="ready"),qa());this.subscription.add(On(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,cc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(On(o,this.player.state$.stateChangeEnded$,cc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=On(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,cc(["init"])).pipe(rC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var V,F,z,w,H,M,j,ee,le,T,L,K,x;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(V=e.videoTrack.getState())==null?void 0:V.id,n=[...this.videoTracksMap.keys()].find(({id:D})=>D===r),o=t.currentVideoTrack$.getValue(),u=((w=(z=e.videoStream.getState())!=null?z:n&&((F=this.videoTracksMap.get(n))==null?void 0:F.stream))!=null?w: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=Ji(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let p=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(h,p||1/0),1),b=(H=e.audioStream.getState())!=null?H:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(M=[...this.audioStreamsMap.keys()].find(({id:D})=>D===(b==null?void 0:b.id)))!=null?M:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!i){let D=cn(n,c,(j=this.audioStreamsMap.get(g))!=null?j:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(ee=D==null?void 0:D.bitrate)!=null?ee:-1/0)}if(o){let D=cn(o,c,(le=this.audioStreamsMap.get(g))!=null?le:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(T=D==null?void 0:D.bitrate)!=null?T:-1/0)}}let S=qt(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),y=i?S!=null?S:n:n!=null?n:S,E=g&&pv(y,c,(L=this.audioStreamsMap.get(g))!=null?L:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=(K=this.videoTracksMap.get(y))==null?void 0:K.representation,$=E&&((x=this.audioTracksMap.get(E))==null?void 0:x.representation);if(I&&$)return[I,$];if(I&&!$&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Yy.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),this.params.output.currentVideoStream$.next(void 0),ke(this.video),this.tracer.end()}};var Ua=class extends yi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as dc,merge as Zy,filter as eT,filterChanged as nC,isNullable as pc,map as tT,ValueSubject as hc,isNonNullable as oC}from"@vkontakte/videoplayer-shared/es2015";var Ha=class extends yi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new hc(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(tT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(dc({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(tT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(eT(o=>oC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(dc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Zy(i.playbackRateState$,new hc(1))}).pipe(eT(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||pc(l)||(e=o-l)})).add(dc({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Zy(i.playbackRateState$,new hc(1))}).pipe(nC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||pc(o)||pc(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=Sy(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var rT=B(Ks(),1);import{assertNever as ja,assertNonNullable as iT,debounce as uC,ErrorCategory as Bn,filter as lC,isNonNullable as cC,isNullable as dC,map as _n,merge as pC,Observable as hC,observableFrom as mC,Subscription as fC,videoSizeToQuality as bC}from"@vkontakte/videoplayer-shared/es2015";var et={};var ur=(a,e)=>new hC(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),Qa=class{constructor(e){this.subscription=new fC;this.videoState=new _("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default: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"),R(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ja(e)}break;default:ja(t)}};this.textTracksManager=new He(e.source.url),this.video=Ae(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(de(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),ke(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Bn.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,rT.default)(import("hls.js").then(r=>{e||(et.Hls=r.default,et.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){iT(et.Hls,"hls.js not loaded"),this.hls=new et.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){iT(et.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Bn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,i)),this.subscription.add(Re(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ue(this.video,e.playbackRate,r.playbackRateState$,i)),s(je(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(_n(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ur(this.hls,et.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Bn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(ur(this.hls,et.Events.MANIFEST_PARSED).pipe(_n(({levels:l})=>l.reduce((c,d)=>{var S,y;let h=d.name||d.height.toString(10),{width:p,height:m}=d,b=(y=_t((S=d.attrs.QUALITY)!=null?S:""))!=null?y:bC({width:p,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:g};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(ur(this.hls,et.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ur(this.hls,et.Events.LEVEL_LOADING).pipe(_n(({url:l})=>de(l))),t.hostname$),s(ur(this.hls,et.Events.FRAG_CHANGED),l=>{var h,p,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Vt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ur(this.hls,et.Events.LEVEL_SWITCHED).pipe(_n(({level:l})=>n(this.hls.levels[l])));o.pipe(lC(cC)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Vt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(dC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=pC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,mC(["init"])).pipe(uC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return P(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bn.DOM,thrown:t})))||(this.videoState.setState("paused"),R(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"),R(this.params.desiredState.playbackState,"stopped",!0)}};var aT="X-Playback-Duration",mc=a=>P(void 0,null,function*(){var r;let e=yield lt(a),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(aT)?parseInt(e.headers.get(aT),10):void 0});import{assertNever as AC,combine as kC,debounce as RC,ErrorCategory as qn,filter as LC,filterChanged as $C,isNonNullable as oT,isNullable as Un,map as uT,merge as MC,observableFrom as DC,Subscription as CC,ValueSubject as gc,VideoQuality as VC}from"@vkontakte/videoplayer-shared/es2015";var bc=B(hu(),1);import{videoSizeToQuality as gC,getExponentialDelay as vC}from"@vkontakte/videoplayer-shared/es2015";var SC=a=>{let e=null;if(a.QUALITY&&(e=_t(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=gC({width:t,height:i})}return e!=null?e:null},yC=(a,e)=>{var s,n;let t=a.split(`
125
- `),i=[],r=[];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,bc.default)(l[1].split(",").map(S=>S.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=SC(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(E=>parseInt(E,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,bc.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,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,m=d.NAME;h&&p&&r.push({type:"internal",id:p,label:m,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},TC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),fc=0,sT=(r,...s)=>P(void 0,[r,...s],function*(a,e=a,t,i){let o=yield(yield lt(a,i)).text();fc+=1;try{let{qualityManifests:u,textTracks:l}=yC(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(fc<=t.manifestRetryMaxCount)return yield TC(vC(fc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),sT(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Nn=sT;import{isNonNullable as IC,Subscription as EC,throttle as xC,ValueSubject as nT,Subject as PC,ErrorCategory as wC}from"@vkontakte/videoplayer-shared/es2015";var Fn=class{constructor(e,t,i,r,s){this.subscription=new EC;this.abortControllers={destroy:new ve,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new nT(null);this.getCurrentTime$=new nT(null);this.error$=new PC;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(xC(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 P(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=yield this.fetchManifestData();yield this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return P(this,null,function*(){try{let i=yield this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}})}parseTextTracks(e,t){return P(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString(),n=yield(yield lt(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}})}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
126
- `),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.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);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(IC(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([C(A({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return P(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ve;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 P(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:wC.WTF,thrown:t,message:e})}};var Ga=class{constructor(e){this.subscription=new CC;this.videoState=new _("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new gc([]);this.liveOffset=new hi;this.manifestStartTime$=new gc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(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((r==null?void 0:r.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":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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(r==null?void 0:r.to)==="paused"&&(R(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return AC(t)}};var i;this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:VC.INVARIANT,url:this.params.source.url};let t=(r,s)=>Nn(r,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 Fn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new He(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:qn.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,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:qn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new gc((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:qn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),s(je(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(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe($C(),uT(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&oT(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(de(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.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)},i)),this.subscription.add(kC({startTime:this.manifestStartTime$.pipe(LC(oT)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(uT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=MC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,DC(["init"])).pipe(RC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}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),ke(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Un(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ge(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),mc(n).then(c=>{var d;if(!Un(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Un(h)||!isFinite(h))&&lt(n).then(p=>p.text()).then(p=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();mc(g).then(v=>{Un(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:qn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ge(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 OC,debounce as BC,ErrorCategory as vc,fromEvent as Sc,isNonNullable as _C,isNullable as NC,map as lT,merge as cT,observableFrom as dT,Subscription as FC,ValueSubject as qC,VideoQuality as UC}from"@vkontakte/videoplayer-shared/es2015";var Wa=class{constructor(e){this.subscription=new FC;this.videoState=new _("stopped");this.manifests$=new qC([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(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((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return OC(t)}};this.textTracksManager=new He(e.source.url),this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:UC.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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Nn(ge(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:vc.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,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:vc.WTF,message:"HlsProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(lT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&_C(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(de(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(lT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!q.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(cT(Sc(o,"addtrack"),Sc(o,"removetrack"),Sc(o,"change"),dT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=cT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,dT(["init"])).pipe(BC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var s,n;let e=this.selectManifest();if(NC(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:vc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var mT=B(_i(),1),yc=B(zi(),1),fT=B(Nt(),1);import{assertNever as HC,assertNonNullable as pT,debounce as jC,ErrorCategory as hT,isHigherOrEqual as QC,isLowerOrEqual as GC,isNonNullable as WC,merge as YC,observableFrom as zC,Subscription as KC,map as XC}from"@vkontakte/videoplayer-shared/es2015";var Ya=class{constructor(e){this.subscription=new KC;this.videoState=new _("stopped");this.trackUrls={};this.textTracksManager=new He;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.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"),R(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);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?R(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),R(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()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return HC(e)}};this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),(0,mT.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,yc.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,i=o=>{e.error$.next({id:"MpegProvider",category:hT.WTF,message:"MpegProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(XC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),s(je(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.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&&WC(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=YC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,zC(["init"])).pipe(jC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ke(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;pT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];pT(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(de(t))}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let h=qt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,yc.default)(this.trackUrls).map(d=>d.track);if(!r||!s||Gr({limits:e,lowestAvailableQuality:(c=(0,fT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?GC(r,e.max):!0,u=e.min?QC(r,e.min):!0;o&&u||i(e)}};import{assertNever as gT,debounce as t0,merge as vT,observableFrom as i0,Subscription as r0,map as ST,ValueSubject as a0,ErrorCategory as Ic,VideoQuality as s0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as JC}from"@vkontakte/videoplayer-shared/es2015";var bT=["stun:videostun.mycdn.me:80"],ZC=1e3,e0=3,Tc=()=>null,Hn=class{constructor(e,t){this.ws=null;this.peerConnection=null;this.serverUrl="";this.streamKey="";this.stream=null;this.signalingType="JOIN";this.retryCount=0;this.externalStartCallback=Tc;this.externalStopCallback=Tc;this.externalErrorCallback=Tc;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return P(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 P(this,null,function*(){try{let e={iceServers:[{urls:bT}]};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 P(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return P(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 P(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 P(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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),ZC)}normalizeOptions(e={}){let t={stunServerList:bT,maxRetryNumber:e0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var za=class{constructor(e){this.videoState=new _("stopped");this.maxSeekBackTime$=new a0(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(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"),R(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()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return gT(e)}};this.subscription=new r0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ae(e.container,e.tuning),this.liveStreamClient=new Hn(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),ke(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ic.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(vT(this.videoState.stateChangeStarted$.pipe(ST(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ST(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),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(je(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Re(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).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 gT(n.to)}},i)).add(vT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,i0(["init"])).pipe(t0(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(de(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:s0.INVARIANT}),this.video.srcObject=e,R(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:Ic.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ic.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ka=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ja,assertNonNullable as Gt,ErrorCategory as jn,filter as PT,isNonNullable as wT,isNullable as p0,map as h0,merge as m0,once as f0,Subject as he,Subscription as AT,ValueSubject as N,flattenObject as kT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as n0,map as yT,Subscription as o0,Subject as u0}from"@vkontakte/videoplayer-shared/es2015";var TT=a=>new n0(e=>{let t=new o0,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(yT(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(yT(({type:l})=>l!==void 0)),n=new u0,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.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 l0,Subscription as c0,combine as d0,filter as ET,once as xT}from"@vkontakte/videoplayer-shared/es2015";function IT(){return new(window.AudioContext||window.webkitAudioContext)}var Xa=class Xa{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ve;this.subscriptions=new c0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(ET(s=>!!s.type),xT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){q.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(d0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(ET(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),xT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return P(this,null,function*(){let{volumeMultiplier:t}=this,i=IT();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!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:Xa.errorId,category:l0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Xa.errorId} exception`,thrown:e})}};Xa.errorId="VolumeMultiplierManager";var lr=Xa;var b0={chunkDuration:5e3,maxParallelRequests:5},Za=class{constructor(e){this.current$=new N({type:void 0});this.providerError$=new he;this.noAvailableProvidersError$=new he;this.volumeMultiplierError$=new he;this.providerOutput={position$:new N(0),duration$:new N(1/0),volume$:new N({muted:!1,volume:1}),availableVideoStreams$:new N([]),currentVideoStream$:new N(void 0),availableVideoTracks$:new N([]),currentVideoTrack$:new N(void 0),availableAudioStreams$:new N([]),currentAudioStream$:new N(void 0),availableAudioTracks$:new N([]),currentVideoSegmentLength$:new N(0),currentAudioSegmentLength$:new N(0),isAudioAvailable$:new N(!0),autoVideoTrackLimitingAvailable$:new N(!1),autoVideoTrackLimits$:new N(void 0),currentBuffer$:new N(void 0),isBuffering$:new N(!0),error$:new he,fetcherError$:new he,fetcherRecoverableError$:new he,warning$:new he,willSeekEvent$:new he,soundProhibitedEvent$:new he,seekedEvent$:new he,loopedEvent$:new he,endedEvent$:new he,firstBytesEvent$:new he,loadedMetadataEvent$:new he,firstFrameEvent$:new he,canplay$:new he,isLive$:new N(void 0),isLiveEnded$:new N(null),isLowLatency$:new N(!1),canChangePlaybackSpeed$:new N(!0),liveTime$:new N(void 0),liveBufferTime$:new N(void 0),liveLatency$:new N(void 0),severeStallOccurred$:new he,availableTextTracks$:new N([]),currentTextTrack$:new N(void 0),hostname$:new N(void 0),httpConnectionType$:new N(void 0),httpConnectionReused$:new N(void 0),inPiP$:new N(!1),inFullscreen$:new N(!1),element$:new N(void 0),elementVisible$:new N(!0),availableSources$:new N(void 0),is3DVideo$:new N(!1),playbackState$:new N(""),getCurrentTime$:new N(null)};this.subscription=new AT;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Oy([..._y(this.params.tuning),...By(this.params.tuning)],this.params.tuning).filter(l=>wT(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,Ec.default)(r,l)),...t.filter(l=>(0,Ec.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",kT(s)),this.screenFormatsIterator=new Ka(s);let n=[...ec(!0),...ec(!1)];this.chromecastFormatsIterator=new Ka(n.filter(l=>wT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&lr.isSupported()&&(this.volumeMultiplierManager=new lr(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(p0(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:jn.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.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,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let 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 Ja(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Gt(u),new Ua(C(A({},o),{source:u,sourceHls:l}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ha(C(A({},o),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Gt(u),q.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Wa(C(A({},o),{source:u})):new Qa(C(A({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ga(C(A({},o),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ya(C(A({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Rv(C(A({},o),{source:u,config:C(A({},b0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Gt(u),new za({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ja(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Gt(o),new Fr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,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 Ja(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ja(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 Ja(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);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 C(A({},e),{url:i(e.url)})}return(0,LT.default)((0,RT.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new AT,t=!1,i=0;return e.add(m0(this.providerOutput.error$.pipe(PT(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),TT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(h0(r=>({id:`ProviderHangup:${r}`,category:jn.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(PT(({to:s})=>s==="playing"),f0()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===jn.NETWORK,u=r.category===jn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=C(A({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}this.tracer.error("providerError",kT(n))})),e}};import{fromEvent as Qn,once as g0,combine as v0,Subscription as $T,ValueSubject as xc,map as S0,filter as y0,isNonNullable as Gn,now as Ne,safeStorage as Pc}from"@vkontakte/videoplayer-shared/es2015";var T0=5e3,MT="one_video_throughput",DT="one_video_rtt",Et=window.navigator.connection,CT=()=>{let a=Et==null?void 0:Et.downlink;if(Gn(a)&&a!==10)return a*1e3},VT=()=>{let a=Et==null?void 0:Et.rtt;if(Gn(a)&&a!==3e3)return a},OT=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},wc=class a{constructor(e){this.subscription=new $T;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(MT)||(e.useBrowserEstimation?CT():void 0)||T0,i=(s=(r=a.load(DT))!=null?r:e.useBrowserEstimation?VT():void 0)!=null?s:0;if(this.throughput$=new xc(t),this.rtt$=new xc(i),this.rttAdjustedThroughput$=new xc(OT(t,i,e.rttPenaltyRequestSize)),this.throughput=vi.getSmoothedValue(t,-1,e),this.rtt=vi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=CT();u&&this.throughput.next(u);let l=VT();Gn(l)&&this.rtt.next(l)};Et&&"onchange"in Et&&this.subscription.add(Qn(Et,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Pc.set(MT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Pc.set(DT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(v0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(S0(({throughput:n,rtt:o})=>OT(n,o,e.rttPenaltyRequestSize)),y0(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,i=Ne(),r=new $T;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Qn(e,"progress").pipe(g0()).subscribe(s=>{t=s.loaded,i=Ne()}));break;case 1:case 0:r.add(Qn(e,"loadstart").subscribe(()=>{t=0,i=Ne()}));break}r.add(Qn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ne(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Ne(),n=0,o=Ne(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>P(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(r,Ne()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ne();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Ne()}else n+=d.byteLength;o=Ne()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ne()-o,this.concurrentDownloads.size),n=0,o=Ne());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=Pc.get(e);if(Gn(t))return(i=parseInt(t,10))!=null?i:void 0}},BT=wc;import{fillWithDefault as I0,VideoQuality as Wn}from"@vkontakte/videoplayer-shared/es2015";var _T={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:Wn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Wn.Q_720P,trafficSavingLimit:Wn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Wn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,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,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,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,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,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,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},NT=a=>{var e;return C(A({},I0(a,_T)),{configName:[...(e=a.configName)!=null?e:[],..._T.configName]})};import{assertNonNullable as Yn,combine as xt,ErrorCategory as zn,filter as O,filterChanged as Y,fromEvent as kc,isNonNullable as R0,isNullable as L0,Logger as $0,map as G,mapTo as HT,merge as Wt,now as Kn,once as U,Subject as X,Subscription as jT,tap as Rc,ValueSubject as k,isHigher as M0,isInvariantQuality as QT,flattenObject as Yt,throttle as Lc,getTraceSubscriptionMethod as GT,Tracer as D0,InternalsExposure as C0}from"@vkontakte/videoplayer-shared/es2015";import{merge as E0,map as x0,filter as FT,isNonNullable as P0}from"@vkontakte/videoplayer-shared/es2015";var Ac=({seekState:a,position$:e})=>E0(a.stateChangeEnded$.pipe(x0(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),FT(P0)),e.pipe(FT(()=>a.getState().state==="none")));import{assertNonNullable as w0}from"@vkontakte/videoplayer-shared/es2015";var qT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return w0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as A0,once as k0}from"@vkontakte/videoplayer-shared/es2015";var UT=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(A0(r=>r.length>0),k0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var Xn=class{constructor(e={configName:[]},t=D0.createRootTracer(!1)){this.subscription=new jT;this.logger=new $0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new k(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new k(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new _("stopped"),seekState:new _({state:"none"}),volume:new _({volume:1,muted:!1}),videoTrack:new _(void 0),videoStream:new _(void 0),audioStream:new _(void 0),autoVideoTrackSwitching:new _(!0),autoVideoTrackLimits:new _({}),isLooped:new _(!1),isLowLatency:new _(!1),playbackRate:new _(1),externalTextTracks:new _([]),internalTextTracks:new _([]),currentTextTrack:new _(void 0),textTrackCuesSettings:new _({}),cameraOrientation:new _({x:0,y:0})};this.info={playbackState$:new k(void 0),position$:new k(0),duration$:new k(1/0),muted$:new k(!1),volume$:new k(1),availableVideoStreams$:new k([]),currentVideoStream$:new k(void 0),availableQualities$:new k([]),availableQualitiesFps$:new k({}),currentQuality$:new k(void 0),isAutoQualityEnabled$:new k(!0),autoQualityLimitingAvailable$:new k(!1),autoQualityLimits$:new k({}),predefinedQualityLimitType$:new k("unknown"),availableAudioStreams$:new k([]),currentAudioStream$:new k(void 0),availableAudioTracks$:new k([]),isAudioAvailable$:new k(!0),currentPlaybackRate$:new k(1),currentBuffer$:new k({start:0,end:0}),isBuffering$:new k(!0),isStalled$:new k(!1),isEnded$:new k(!1),isLooped$:new k(!1),isLive$:new k(void 0),isLiveEnded$:new k(null),canChangePlaybackSpeed$:new k(void 0),atLiveEdge$:new k(void 0),atLiveDurationEdge$:new k(void 0),liveTime$:new k(void 0),liveBufferTime$:new k(void 0),liveLatency$:new k(void 0),currentFormat$:new k(void 0),availableTextTracks$:new k([]),currentTextTrack$:new k(void 0),throughputEstimation$:new k(void 0),rttEstimation$:new k(void 0),videoBitrate$:new k(void 0),hostname$:new k(void 0),httpConnectionType$:new k(void 0),httpConnectionReused$:new k(void 0),surface$:new k("none"),chromecastState$:new k("NOT_AVAILABLE"),chromecastDeviceName$:new k(void 0),intrinsicVideoSize$:new k(void 0),availableSources$:new k(void 0),is3DVideo$:new k(!1),currentVideoSegmentLength$:new k(0),currentAudioSegmentLength$:new k(0)};this.events={inited$:new X,ready$:new X,started$:new X,playing$:new X,paused$:new X,stopped$:new X,willStart$:new X,willResume$:new X,willPause$:new X,willStop$:new X,willDestruct$:new X,watchCoverageRecord$:new X,watchCoverageLive$:new X,managedError$:new X,fatalError$:new X,fetcherRecoverableError$:new X,ended$:new X,looped$:new X,seeked$:new X,willSeek$:new X,autoplaySoundProhibited$:new X,firstBytes$:new X,loadedMetadata$:new X,firstFrame$:new X,canplay$:new X,log$:new X,fetcherError$:new X,severeStallOccured$:new X};this.experimental={element$:new k(void 0),tuningConfigName$:new k([]),enableDebugTelemetry$:new k(!1),dumpTelemetry:Zg,getCurrentTime$:new k(null)};if(this.initLogs(),this.tuning=NT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Is({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new BT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new C0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,m)=>{let b=typeof m;return(0,WT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:zn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var l,c,d;let u=e,{container:n}=u,o=gd(u,["container"]);this.tracer.log("initVideo",Yt(o)),this.domContainer=qT(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new Za({sources:e.sources,meta:(c=e.meta)!=null?c:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],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,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?q.isInited$.pipe(O(n=>!!n),U()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),kc(document,"visibilitychange").pipe(U()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),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(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),U()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),U()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),U()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),U()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),U()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),U()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),s=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:s,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:s,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{Yn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();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(O(i=>i.length>0),U()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Yt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{var i;Yn(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Yt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>A({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{var t;UT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",A({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),U()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(O(t=>!!t),U()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(O(i=>!!i),U()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(O(e=>e),U()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(O(e=>!!e),U()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(L0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return R0(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(dl({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(O(({from:e})=>e==="stopped"),U()).subscribe(()=>{this.initedAt=Kn(),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",Yt(n)),n.state==="requested"?this.desiredState.seekState.setState(C(A({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:zn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(U()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Yt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(xt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>QT(u)?1:QT(l)?-1:M0(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(Y()).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(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).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(G(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.isLiveEnded$.pipe(Rc(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).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(xt({hasLiveOffsetByPaused:Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),Y(),G(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(xt({atLiveEdge:xt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ac({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Y(),Rc(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(xt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Y(),Rc(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),Y()).subscribe(this.info.volume$)).add(Ac({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Wt(e.providerOutput.endedEvent$.pipe(HT(!0)),e.providerOutput.seekedEvent$.pipe(HT(!1))).pipe(Y()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(G(n=>({id:n?`No${n}`:"NoProviders",category:zn.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(U(),G(n=>n!=null?n:Kn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(U(),G(()=>Kn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(U(),G(()=>Kn()-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 k(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new k(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(O(({to:n})=>n==="playing"),U()).subscribe(()=>i.next(!1)));let r=0,s=Wt(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),Y());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Wt(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(Wt(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(G(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 jT;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(O(i=>i.length>0),U()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=qt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,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(Wt(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(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;Yn(this.providerContainer),Yn(e),Jg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Xg(i)),this.providerContainer.current$.subscribe(({type:i})=>Qr("provider",i)),e.duration$.subscribe(i=>Qr("duration",i)),e.availableVideoTracks$.pipe(O(i=>!!i.length),U()).subscribe(i=>Qr("tracks",i)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe(G(i=>i==null?void 0:i.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(i=>this.subscription.add(i)),Qr("codecs",q.video.supportedCodecs)}initTracerSubscription(){let e=GT(this.tracer.log.bind(this.tracer)),t=GT(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(Y()).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(xt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(O(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(O(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(O(i=>i>0),Y()).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(xt({currentBuffer:this.info.currentBuffer$.pipe(O(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe(Lc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(xt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(O(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),Lc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),O(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),O(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),O(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(xt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(O(({throughputEstimation:i,rtt:r})=>!!i&&!!r),Lc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),O(i=>i===!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},i=()=>P(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:zn.DOM,message:String(r)})})});this.subscription.add(Wt(kc(document,"visibilitychange"),kc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Yt({quality:t,availableTracks:Yt(e),track:Yt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Jr()}};import{Subscription as tK,Observable as iK,Subject as rK,ValueSubject as aK,VideoQuality as sK}from"@vkontakte/videoplayer-shared/es2015";var nK=`@vkontakte/videoplayer-core@${vd}`;export{fs as ChromecastState,so as HttpConnectionType,iK as Observable,Ce as PlaybackState,Xn as Player,bs as PredefinedQualityLimits,nK as SDK_VERSION,rK as Subject,tK as Subscription,no as Surface,vd as VERSION,aK as ValueSubject,mt as VideoFormat,sK as VideoQuality,q as clientChecker,Hr as isMobile};
124
+ `;var Cn=class{constructor(e,t,i){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();let r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Mn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Dn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(jy,this.gl.VERTEX_SHADER),i=this.createShader(Qy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1,r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,s=e-i,n=t-r,o=e+i,u=t-r,l=e+i,c=t+r,d=e-i,h=t+r;return[s,n,o,u,l,c,d,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as QD,now as Gy,Subscription as GD,filter as WD,combine as Wy,debounce as YD,ValueSubject as nc,isNonNullable as zD}from"@vkontakte/videoplayer-shared/es2015";var oc=class{constructor(){this.isSeeked$=new nc(!1);this.isBuffering$=new nc(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new GD;this.severeStallOccurred$=new nc(!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(e.looped$.subscribe(t=>this.currentStallsCount=0)),this.subscription.add(Wy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(YD(this.qualityLimitsOnStall.stallDurationToBeCount),WD(({isBuffering:t,isSeeked:i})=>t&&!i)).subscribe(t=>{this.currentStallsCount++})),this.subscription.add(Wy({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{let{stallDurationNoDataBeforeQualityDecrease:i,stallCountBeforeQualityDecrease:r,resetQualityRestrictionTimeout:s,ignoreStallsOnSeek:n}=this.qualityLimitsOnStall;if(QD(this.lastUniqueVideoTrackSelected)||n&&this.isSeeked$.getValue())return;let o=this.rtt$.getValue(),u=this.throughput$.getValue(),l=this.videoLastDataObtainedTimestamp$.getValue(),c=Gy(),d=r&&this.currentStallsCount>=r,h=i&&c-this.lastUniqueVideoTrackSelectedTimestamp>=i+o&&c-l>=i+o&&t>=i;(d||h)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,zD(this.lastUniqueVideoTrackSelected.bitrate)&&u>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=Gy(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Yy=oc;import{combine as KD,map as XD,observeElementSize as JD,Subscription as ZD,ValueSubject as uc,noop as eC}from"@vkontakte/videoplayer-shared/es2015";var Vn=class{constructor(){this.subscription=new ZD;this.pipSize$=new uc(void 0);this.videoSize$=new uc(void 0);this.elementSize$=new uc(void 0);this.pictureInPictureWindowRemoveEventListener=eC}connect({observableVideo:e,video:t}){let i=r=>{let s=r.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(JD(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:r})=>{this.pipSize$.next({width:r.width,height:r.height}),r.addEventListener("resize",i),this.pictureInPictureWindowRemoveEventListener=()=>{r.removeEventListener("resize",i)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(KD({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(XD(({videoSize:r,inPip:s,pipSize:n})=>s?n:r)).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 yi=class{constructor(e){this.subscription=new nC;this.videoState=new _("stopped");this.droppedFramesManager=new mn;this.stallsManager=new Yy;this.elementSizeManager=new Vn;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Wr;this.audioTrackSwitchHistory=new Wr;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(r.state==="requested"&&(i==null?void 0:i.to)!=="paused"&&e!=="stopped"&&t!=="stopped"&&this.seek(r.position,r.forcePrecise),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"),R(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"),R(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="ready"&&R(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):t==="playing"&&this.video.paused?this.playIfAllowed():(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return iC(e)}}};this.init3DScene=e=>{var i,r,s;if(this.scene3D)return;this.scene3D=new Cn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=e.projectionData)==null?void 0:i.pose.yaw)||0,y:((r=e.projectionData)==null?void 0:r.pose.pitch)||0,z:((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 He(e.source.url),this.params=e,this.video=Ae(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(de(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 $n({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,i=$e(this.video);this.subscription.add(()=>i.destroy());let r=this.constructor.name,s=o=>{e.error$.next({id:r,category:zy.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(lc(l=>!!l.length),Xy()).subscribe(l=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks:l})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(cc(l=>l.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$:i.isBuffering$,looped$:i.looped$}),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.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.fetcherRecoverableError$,e.fetcherRecoverableError$),s(this.player.fetcherError$,e.fetcherError$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(lc(Ky),Xy()),e.firstBytesEvent$),s(this.stallsManager.severeStallOccurred$,e.severeStallOccurred$),s(this.videoState.stateChangeEnded$.pipe(cc(l=>l.to)),this.params.output.playbackState$),this.subscription.add(i.loopExpected$.subscribe(l=>{t.seekState.setState({state:"requested",position:0,forcePrecise:!1})})),this.subscription.add(i.looped$.subscribe(()=>this.player.warmUpMediaSourceIfNeeded(),r)),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Re(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ue(this.video,t.playbackRate,i.playbackRateState$,r)),this.elementSizeManager.connect({video:this.video,observableVideo:i}),s(je(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:l})=>{if(l==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let c=this.player.getStreams();if(rC(c,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let p of c.audio){h.push(Hl(p));let m=[];for(let b of p.representations){let g=vy(b);m.push(g),this.audioTracksMap.set(g,{stream:p,representation:b})}this.audioStreamsMap.set(p,m)}this.params.output.availableAudioStreams$.next(h)}let d=[];for(let h of c.video){d.push(jl(h));let p=[];for(let m of h.representations){let b=gy(C(A({},m),{streamId:h.id}));b&&(p.push(b),this.videoTracksMap.set(b,{stream:h,representation:m}))}this.videoStreamsMap.set(h,p)}this.params.output.availableVideoStreams$.next(d);for(let h of c.text)for(let p of h.representations){let m=Sy(h,p);this.textTracksMap.set(m,{stream:h,representation:p})}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 l==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},r)),this.subscription.add(On(this.player.currentStallDuration$,this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSizeManager.getObservable(),this.params.output.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,sC(this.video,"progress")).pipe(lc(()=>this.videoTracksMap.size>0)).subscribe(()=>P(this,null,function*(){let l=this.player.state$.getState(),c=this.player.state$.getTransition();if(!(0,Jy.default)(["manifest_ready","running"],l)||c)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let d=this.selectVideoAudioRepresentations();if(!d)return;let[h,p]=d,m=[...this.videoTracksMap.keys()].find(g=>{var v;return((v=this.videoTracksMap.get(g))==null?void 0:v.representation.id)===h.id});Ky(m)&&(this.stallsManager.lastVideoTrackSelected=m);let b=this.params.desiredState.autoVideoTrackLimits.getTransition();if(b&&this.params.output.autoVideoTrackLimits$.next(b.to),l==="manifest_ready")yield this.player.initRepresentations(h.id,p==null?void 0:p.id,this.params.sourceHls);else if(yield this.player.switchRepresentation("video",h.id),p){let g=!!t.audioStream.getTransition();yield this.player.switchRepresentation("audio",p.id,g)}}),r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:l})=>{this.scene3D&&l&&this.scene3D.pointCameraTo(l.x,l.y)})),this.subscription.add(this.elementSizeManager.subscribe(l=>{this.scene3D&&l&&this.scene3D.setViewportSize(l.width,l.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(qa()).subscribe(l=>{let c=[...this.videoTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[d,{stream:h}]=c,p=this.params.desiredState.videoStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.videoStream.setState(p.to),e.currentVideoTrack$.next(d),e.currentVideoStream$.next(jl(h))},r)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(qa()).subscribe(l=>{let c=[...this.audioTracksMap.entries()].find(([,{representation:m}])=>m.id===l);if(!c){e.currentAudioStream$.next(void 0);return}let[d,{stream:h}]=c,p=this.params.desiredState.audioStream.getTransition();p&&p.to&&p.to.id===h.id&&this.params.desiredState.audioStream.setState(p.to),e.currentAudioStream$.next(Hl(h))},r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(l=>{var c,d;if(l!=null&&l.is3dVideo&&((c=this.params.tuning.spherical)!=null&&c.enabled))try{this.init3DScene(l),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(d=this.params.tuning.spherical)!=null&&d.enabled&&e.is3DVideo$.next(!1)},r)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,r)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,r)),this.textTracksManager.connect(this.video,t,e);let o=t.playbackState.stateChangeStarted$.pipe(cc(({to:l})=>l==="ready"),qa());this.subscription.add(On(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,dc(["init"])).subscribe(()=>{let l=t.autoVideoTrackSwitching.getState(),d=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(d)})),this.subscription.add(On(o,this.player.state$.stateChangeEnded$,dc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let u=On(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,dc(["init"])).pipe(aC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoAudioRepresentations(){var O,F,z,w,H,M,j,ee,le,T,L,K,x;if(this.player.isStreamEnded)return;let{desiredState:e,output:t}=this.params,i=e.autoVideoTrackSwitching.getState(),r=(O=e.videoTrack.getState())==null?void 0:O.id,n=[...this.videoTracksMap.keys()].find(({id:D})=>D===r),o=t.currentVideoTrack$.getValue(),u=((w=(z=e.videoStream.getState())!=null?z:n&&((F=this.videoTracksMap.get(n))==null?void 0:F.stream))!=null?w: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=Ji(this.video.buffered,this.video.currentTime*1e3),h;this.player.isActiveLive$.getValue()?h=this.player.isLowLatency$.getValue()?this.params.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.params.tuning.dashCmafLive.normalizedLiveMinBufferSize:this.player.isLive$.getValue()?h=this.params.tuning.dashCmafLive.normalizedTargetMinBufferSize:h=i?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;let p=(this.video.duration*1e3||1/0)-this.video.currentTime*1e3,m=Math.min(d/Math.min(h,p||1/0),1),b=(H=e.audioStream.getState())!=null?H:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,g=(M=[...this.audioStreamsMap.keys()].find(({id:D})=>D===(b==null?void 0:b.id)))!=null?M:this.audioStreamsMap.keys().next().value,v=0;if(g){if(n&&!i){let D=cn(n,c,(j=this.audioStreamsMap.get(g))!=null?j:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(ee=D==null?void 0:D.bitrate)!=null?ee:-1/0)}if(o){let D=cn(o,c,(le=this.audioStreamsMap.get(g))!=null?le:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);v=Math.max(v,(T=D==null?void 0:D.bitrate)!=null?T:-1/0)}}let S=qt(c,{container:this.elementSizeManager.getValue(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),y=i?S!=null?S:n:n!=null?n:S,E=g&&hv(y,c,(L=this.audioStreamsMap.get(g))!=null?L:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:m,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=(K=this.videoTracksMap.get(y))==null?void 0:K.representation,$=E&&((x=this.audioTracksMap.get(E))==null?void 0:x.representation);if(I&&$)return[I,$];if(I&&!$&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:zy.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),this.params.output.currentVideoStream$.next(void 0),ke(this.video),this.tracer.end()}};var Ua=class extends yi{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as pc,merge as Zy,filter as eT,filterChanged as oC,isNullable as hc,map as tT,ValueSubject as mc,isNonNullable as uC}from"@vkontakte/videoplayer-shared/es2015";var Ha=class extends yi{constructor(e){super(e),this.textTracksManager.destroy()}subscribe(){super.subscribe();let e=-1,{output:t,observableVideo:i,desiredState:r,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),s(i.timeUpdate$,t.liveBufferTime$),s(this.player.liveSeekableDuration$,t.duration$),s(this.player.liveLatency$,t.liveLatency$);let n=new mc(1);s(i.playbackRateState$,n),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(r.isLowLatency.stateChangeEnded$.pipe(tT(o=>o.to)).subscribe(this.player.isLowLatency$)).add(pc({liveBufferTime:t.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(tT(({liveBufferTime:o,liveAvailabilityStartTime:u})=>o&&u?o+u:void 0)).subscribe(t.liveTime$)).add(this.player.liveStreamStatus$.pipe(eT(o=>uC(o))).subscribe(o=>t.isLiveEnded$.next(o!=="active"&&t.position$.getValue()===0))).add(pc({liveDuration:this.player.liveDuration$,liveStreamStatus:this.player.liveStreamStatus$,playbackRate:Zy(i.playbackRateState$,new mc(1))}).pipe(eT(({liveStreamStatus:o,liveDuration:u})=>o==="active"&&!!u)).subscribe(({liveDuration:o,playbackRate:u})=>{let l=t.liveBufferTime$.getValue(),c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;c||u<1-d||this.video.paused||hc(l)||(e=o-l)})).add(pc({time:t.liveBufferTime$,liveDuration:this.player.liveDuration$,playbackRate:Zy(i.playbackRateState$,new mc(1))}).pipe(oC((o,u)=>this.player.liveStreamStatus$.getValue()==="active"?o.liveDuration===u.liveDuration:o.time===u.time)).subscribe(({time:o,liveDuration:u,playbackRate:l})=>{let c=t.position$.getValue(),{playbackCatchupSpeedup:d}=this.params.tuning.dashCmafLive.lowLatency;if(!c&&!this.video.paused&&l>=1-d||hc(o)||hc(u))return;let h=-1*(u-o-e);t.position$.next(Math.min(h,0))})).add(this.player.currentLiveTextRepresentation$.subscribe(o=>{if(o){let u=yy(o);this.params.output.availableTextTracks$.next([u])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=Math.trunc(t/1e3<=Math.abs(this.params.output.duration$.getValue())?t:0);this.player.seekLive(i).then(()=>{this.params.output.position$.next(e/1e3)})}};var rT=B(Ks(),1);import{assertNever as ja,assertNonNullable as iT,debounce as lC,ErrorCategory as Bn,filter as cC,isNonNullable as dC,isNullable as pC,map as _n,merge as hC,Observable as mC,observableFrom as fC,Subscription as bC,videoSizeToQuality as gC}from"@vkontakte/videoplayer-shared/es2015";var et={};var ur=(a,e)=>new mC(t=>{let i=(r,s)=>t.next(s);return a.on(e,i),()=>a.off(e,i)}),Qa=class{constructor(e){this.subscription=new bC;this.videoState=new _("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((i==null?void 0:i.to)!=="paused"&&r.state==="requested"&&this.seek(r.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default: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"),R(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ja(e)}break;default:ja(t)}};this.textTracksManager=new He(e.source.url),this.video=Ae(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(de(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),ke(this.video)}loadHlsJs(){let e=!1,t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Bn.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,rT.default)(import("hls.js").then(r=>{e||(et.Hls=r.default,et.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){iT(et.Hls,"hls.js not loaded"),this.hls=new et.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){iT(et.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,i=l=>{t.error$.next({id:"HlsJsProvider",category:Bn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(l,c)=>this.subscription.add(l.subscribe(c,i));s(r.timeUpdate$,t.position$),s(r.durationChange$,t.duration$),s(r.ended$,t.endedEvent$),s(r.looped$,t.loopedEvent$),s(r.error$,t.error$),s(r.isBuffering$,t.isBuffering$),s(r.currentBuffer$,t.currentBuffer$),s(r.loadStart$,t.firstBytesEvent$),s(r.loadedMetadata$,t.loadedMetadataEvent$),s(r.playing$,t.firstFrameEvent$),s(r.canplay$,t.canplay$),s(r.seeked$,t.seekedEvent$),s(r.inPiP$,t.inPiP$),s(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,i)),this.subscription.add(Re(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ue(this.video,e.playbackRate,r.playbackRateState$,i)),s(je(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(_n(l=>l.to)),this.params.output.playbackState$),this.subscription.add(ur(this.hls,et.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Bn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(e.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(e.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),s(ur(this.hls,et.Events.MANIFEST_PARSED).pipe(_n(({levels:l})=>l.reduce((c,d)=>{var S,y;let h=d.name||d.height.toString(10),{width:p,height:m}=d,b=(y=_t((S=d.attrs.QUALITY)!=null?S:""))!=null?y:gC({width:p,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:h.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:p,height:m},fps:g};return this.trackLevels.set(h,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(ur(this.hls,et.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let h=d.name,p=d.attrs.URI||"",m=d.lang;c.push({id:h,url:p,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(ur(this.hls,et.Events.LEVEL_LOADING).pipe(_n(({url:l})=>de(l))),t.hostname$),s(ur(this.hls,et.Events.FRAG_CHANGED),l=>{var h,p,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((h=c==null?void 0:c.endPTS)!=null?h:0)-((p=c==null?void 0:c.startPTS)!=null?p:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Vt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:i}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=ur(this.hls,et.Events.LEVEL_SWITCHED).pipe(_n(({level:l})=>n(this.hls.levels[l])));o.pipe(cC(dC)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Vt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(pC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),h=this.hls.currentLevel,p=this.hls.levels[h];!p||c.bitrate>p.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:i})),s(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=hC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,fC(["init"])).pipe(lC(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return P(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bn.DOM,thrown:t})))||(this.videoState.setState("paused"),R(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"),R(this.params.desiredState.playbackState,"stopped",!0)}};var aT="X-Playback-Duration",fc=a=>P(void 0,null,function*(){var r;let e=yield lt(a),t=yield e.text(),i=(r=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:r[1];return i?parseInt(i,10):e.headers.has(aT)?parseInt(e.headers.get(aT),10):void 0});import{assertNever as kC,combine as RC,debounce as LC,ErrorCategory as qn,filter as $C,filterChanged as MC,isNonNullable as oT,isNullable as Un,map as uT,merge as DC,observableFrom as CC,Subscription as VC,ValueSubject as vc,VideoQuality as OC}from"@vkontakte/videoplayer-shared/es2015";var gc=B(hu(),1);import{videoSizeToQuality as vC,getExponentialDelay as SC}from"@vkontakte/videoplayer-shared/es2015";var yC=a=>{let e=null;if(a.QUALITY&&(e=_t(a.QUALITY)),!e&&a.RESOLUTION){let[t,i]=a.RESOLUTION.split("x").map(r=>parseInt(r,10));e=vC({width:t,height:i})}return e!=null?e:null},TC=(a,e)=>{var s,n;let t=a.split(`
125
+ `),i=[],r=[];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,gc.default)(l[1].split(",").map(S=>S.split("="))),h=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,p=yC(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(E=>parseInt(E,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();p&&i.push({id:h,quality:p,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,gc.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,"")])),h=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),p=d.LANGUAGE,m=d.NAME;h&&p&&r.push({type:"internal",id:p,label:m,language:p,url:h,isAuto:!1})}}}if(!i.length)throw new Error("Empty manifest");return{qualityManifests:i,textTracks:r}},IC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),bc=0,sT=(r,...s)=>P(void 0,[r,...s],function*(a,e=a,t,i){let o=yield(yield lt(a,i)).text();bc+=1;try{let{qualityManifests:u,textTracks:l}=TC(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(bc<=t.manifestRetryMaxCount)return yield IC(SC(bc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),sT(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Nn=sT;import{isNonNullable as EC,Subscription as xC,throttle as PC,ValueSubject as nT,Subject as wC,ErrorCategory as AC}from"@vkontakte/videoplayer-shared/es2015";var Fn=class{constructor(e,t,i,r,s){this.subscription=new xC;this.abortControllers={destroy:new ve,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new nT(null);this.getCurrentTime$=new nT(null);this.error$=new wC;this.params={fetchManifestData:i,sourceUrl:r,downloadThreshold:s},this.subscription.add(e.pipe(PC(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 P(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:i}=yield this.fetchManifestData();yield this.processTextTracks(i,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return P(this,null,function*(){try{let i=yield this.parseTextTracks(e,t);i&&(this.currentTextTrackData=i)}catch(i){this.error("processTextTracks",i)}})}parseTextTracks(e,t){return P(this,null,function*(){for(let i of e){let r=new URL(i.url,t).toString(),n=yield(yield lt(r,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,r);return{textTrack:i,playlist:o}}})}parsePlaylist(e,t){let i={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},r=e.split(`
126
+ `),s=0;for(let n=0;n<r.length;++n){let o=r[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=r[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(i.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!i.segmentStartTime){let d=new Date(i.vkStartTime).valueOf(),h=new Date(i.programDateTime).valueOf();i.segmentStartTime=h-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):i.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):i.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):i.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);i.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):i.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return i}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(EC(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:i}=t[0].time,{to:r}=t[t.length-1].time;if(e<i||e>r)return;r-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([C(A({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return P(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new ve;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 P(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:AC.WTF,thrown:t,message:e})}};var Ga=class{constructor(e){this.subscription=new VC;this.videoState=new _("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new vc([]);this.liveOffset=new hi;this.manifestStartTime$=new vc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(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((r==null?void 0:r.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":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":if(i==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let 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(r==null?void 0:r.to)==="paused"&&(R(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return kC(t)}};var i;this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:OC.INVARIANT,url:this.params.source.url};let t=(r,s)=>Nn(r,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 Fn(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new He(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:r,textTracks:s})=>{var n;r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:qn.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,...r])}).catch(r=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:qn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new vc((i=e.source.maxSeekBackTime)!=null?i:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&!r&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:qn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.ended$,e.endedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),s(je(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(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(MC(),uT(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&oT(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let h=this.manifests$.getValue().find(p=>p.id===d);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(de(h.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},i)),this.subscription.add(r.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)},i)),this.subscription.add(RC({startTime:this.manifestStartTime$.pipe($C(oT)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(uT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i));let n=DC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,CC(["init"])).pipe(LC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}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),ke(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Un(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:i)!=null?u:{};for(let[h,p]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(h||""));p&&h&&r.searchParams.set(p,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=ge(r.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),fc(n).then(c=>{var d;if(!Un(c))this.maxSeekBackTime$.next(c);else{let h=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Un(h)||!isFinite(h))&&lt(n).then(p=>p.text()).then(p=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();fc(g).then(v=>{Un(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:qn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=ge(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 BC,debounce as _C,ErrorCategory as Sc,fromEvent as yc,isNonNullable as NC,isNullable as FC,map as lT,merge as cT,observableFrom as dT,Subscription as qC,ValueSubject as UC,VideoQuality as HC}from"@vkontakte/videoplayer-shared/es2015";var Wa=class{constructor(e){this.subscription=new qC;this.videoState=new _("stopped");this.manifests$=new UC([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(i==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(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((r==null?void 0:r.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":i==="ready"?R(this.params.desiredState.playbackState,"ready"):i==="paused"?(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused")):i==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":i==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":i==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return BC(t)}};this.textTracksManager=new He(e.source.url),this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:HC.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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Nn(ge(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Sc.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,i=e.getState(),r=t.getTransition(),s=(d=(c=(u=r==null?void 0:r.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=i?"master":s;return i&&(!r||!r.from)&&t.startTransitionTo(this.masterManifest),n.find(h=>h.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:Sc.WTF,message:"HlsProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(lT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{var p;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&NC(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(de(b.url)))}let d=this.params.desiredState.playbackRate.getState(),h=(p=this.params.output.element$.getValue())==null?void 0:p.playbackRate;if(d!==h){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(lT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:h})=>({id:u,quality:l,size:c,fps:h,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,i)),!q.device.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(cT(yc(o,"addtrack"),yc(o,"removetrack"),yc(o,"change"),dT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}let n=cT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,dT(["init"])).pipe(_C(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ke(this.video)}prepare(){var s,n;let e=this.selectManifest();if(FC(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),i=this.params.desiredState.autoVideoTrackLimits.getState(),r=new URL(e.url);if((t||i)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:i)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&r.searchParams.set(c,d)}}this.video.setAttribute("src",r.toString()),this.video.load()}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Sc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var mT=B(_i(),1),Tc=B(zi(),1),fT=B(Nt(),1);import{assertNever as jC,assertNonNullable as pT,debounce as QC,ErrorCategory as hT,isHigherOrEqual as GC,isLowerOrEqual as WC,isNonNullable as YC,merge as zC,observableFrom as KC,Subscription as XC,map as JC}from"@vkontakte/videoplayer-shared/es2015";var Ya=class{constructor(e){this.subscription=new XC;this.videoState=new _("stopped");this.trackUrls={};this.textTracksManager=new He;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.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"),R(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);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:u}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:u*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?R(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),R(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()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return jC(e)}};this.params=e,this.video=Ae(e.container,e.tuning),this.params.output.element$.next(this.video),(0,mT.default)(this.params.source).reverse().forEach(([t,i],r)=>{let s=r.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Tc.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,i=o=>{e.error$.next({id:"MpegProvider",category:hT.WTF,message:"MpegProvider internal logic error",thrown:o})},r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(o,u)=>this.subscription.add(o.subscribe(u,i));s(r.timeUpdate$,e.position$),s(r.durationChange$,e.duration$),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.loadedMetadata$,e.firstBytesEvent$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.seeked$,e.seekedEvent$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(JC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Re(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ue(this.video,t.playbackRate,r.playbackRateState$,i)),s(je(this.video),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),R(t.playbackState,"playing")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),R(t.playbackState,"paused")},i)).add(r.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&&YC(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(c),h.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);let n=zC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,KC(["init"])).pipe(QC(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ke(this.video)}prepare(){var i;let e=(i=this.params.desiredState.videoTrack.getState())==null?void 0:i.id;pT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];pT(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(de(t))}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var l,c;this.params.output.autoVideoTrackLimits$.next(e);let t=d=>{this.params.output.currentVideoTrack$.next(d),this.params.desiredState.videoTrack.startTransitionTo(d)},i=d=>{let h=qt(n,{container:this.video.getBoundingClientRect(),panelSize:this.params.panelSize,estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,limits:d,abrLogger:this.params.dependencies.abrLogger});t(h)},r=(l=this.params.output.currentVideoTrack$.getValue())==null?void 0:l.quality,s=!!(e.max||e.min),n=(0,Tc.default)(this.trackUrls).map(d=>d.track);if(!r||!s||Gr({limits:e,lowestAvailableQuality:(c=(0,fT.default)(n,-1))==null?void 0:c.quality,highestAvailableQuality:n[0].quality})){i();return}let o=e.max?WC(r,e.max):!0,u=e.min?GC(r,e.min):!0;o&&u||i(e)}};import{assertNever as gT,debounce as i0,merge as vT,observableFrom as r0,Subscription as a0,map as ST,ValueSubject as s0,ErrorCategory as Ec,VideoQuality as n0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as ZC}from"@vkontakte/videoplayer-shared/es2015";var bT=["stun:videostun.mycdn.me:80"],e0=1e3,t0=3,Ic=()=>null,Hn=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=Ic;this.externalStopCallback=Ic;this.externalErrorCallback=Ic;this.options=this.normalizeOptions(t);let i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return P(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 P(this,null,function*(){try{let e={iceServers:[{urls:bT}]};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 P(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return P(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:ZC.WTF,message:e.message})}onPeerConnectionStream(e){return P(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 P(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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),e0)}normalizeOptions(e={}){let t={stunServerList:bT,maxRetryNumber:t0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var za=class{constructor(e){this.videoState=new _("stopped");this.maxSeekBackTime$=new s0(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),R(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"),R(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()):(i==null?void 0:i.to)==="playing"&&R(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&R(this.params.desiredState.playbackState,"paused");return;default:return gT(e)}};this.subscription=new a0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ae(e.container,e.tuning),this.liveStreamClient=new Hn(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),ke(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:Ec.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};this.subscription.add(vT(this.videoState.stateChangeStarted$.pipe(ST(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(ST(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})}));let r=$e(this.video);this.subscription.add(()=>r.destroy());let s=(n,o)=>this.subscription.add(n.subscribe(o,i));s(r.timeUpdate$,e.liveTime$),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(je(this.video),this.params.output.elementVisible$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},i)).add(r.playing$.subscribe(()=>{this.videoState.setState("playing")},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Re(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).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 gT(n.to)}},i)).add(vT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r0(["init"])).pipe(i0(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(de(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:n0.INVARIANT}),this.video.srcObject=e,R(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:Ec.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Me(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),R(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Ec.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ka=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Ja,assertNonNullable as Gt,ErrorCategory as jn,filter as PT,isNonNullable as wT,isNullable as h0,map as m0,merge as f0,once as b0,Subject as he,Subscription as AT,ValueSubject as N,flattenObject as kT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as o0,map as yT,Subscription as u0,Subject as l0}from"@vkontakte/videoplayer-shared/es2015";var TT=a=>new o0(e=>{let t=new u0,i=a.desiredPlaybackState$.stateChangeStarted$.pipe(yT(({from:l,to:c})=>`${l}-${c}`)),r=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(yT(({type:l})=>l!==void 0)),n=new l0,o=0,u="unknown";return t.add(i.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(r.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 c0,Subscription as d0,combine as p0,filter as ET,once as xT}from"@vkontakte/videoplayer-shared/es2015";function IT(){return new(window.AudioContext||window.webkitAudioContext)}var Xa=class Xa{constructor(e,t,i,r){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=i;this.volumeMultiplier=r;this.destroyController=new ve;this.subscriptions=new d0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(ET(s=>!!s.type),xT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){q.browser.isSafari&&e!=="MPEG"||this.subscriptions.add(p0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(ET(({playbackState:t,video:i,volume:{muted:r,volume:s}})=>t==="playing"&&!!i&&!r&&!!s),xT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(i=>{i||this.destroy()}).catch(i=>{this.handleError(i),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return P(this,null,function*(){let{volumeMultiplier:t}=this,i=IT();this.audioContext=i;let r=i.createGain();if(this.gainNode=r,r.gain.value=t,r.connect(i.destination),i.state==="suspended"&&(yield i.resume(),this.destroyController.signal.aborted))return!1;let s=i.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(r),!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:Xa.errorId,category:c0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Xa.errorId} exception`,thrown:e})}};Xa.errorId="VolumeMultiplierManager";var lr=Xa;var g0={chunkDuration:5e3,maxParallelRequests:5},Za=class{constructor(e){this.current$=new N({type:void 0});this.providerError$=new he;this.noAvailableProvidersError$=new he;this.volumeMultiplierError$=new he;this.providerOutput={position$:new N(0),duration$:new N(1/0),volume$:new N({muted:!1,volume:1}),availableVideoStreams$:new N([]),currentVideoStream$:new N(void 0),availableVideoTracks$:new N([]),currentVideoTrack$:new N(void 0),availableAudioStreams$:new N([]),currentAudioStream$:new N(void 0),availableAudioTracks$:new N([]),currentVideoSegmentLength$:new N(0),currentAudioSegmentLength$:new N(0),isAudioAvailable$:new N(!0),autoVideoTrackLimitingAvailable$:new N(!1),autoVideoTrackLimits$:new N(void 0),currentBuffer$:new N(void 0),isBuffering$:new N(!0),error$:new he,fetcherError$:new he,fetcherRecoverableError$:new he,warning$:new he,willSeekEvent$:new he,soundProhibitedEvent$:new he,seekedEvent$:new he,loopedEvent$:new he,endedEvent$:new he,firstBytesEvent$:new he,loadedMetadataEvent$:new he,firstFrameEvent$:new he,canplay$:new he,isLive$:new N(void 0),isLiveEnded$:new N(null),isLowLatency$:new N(!1),canChangePlaybackSpeed$:new N(!0),liveTime$:new N(void 0),liveBufferTime$:new N(void 0),liveLatency$:new N(void 0),severeStallOccurred$:new he,availableTextTracks$:new N([]),currentTextTrack$:new N(void 0),hostname$:new N(void 0),httpConnectionType$:new N(void 0),httpConnectionReused$:new N(void 0),inPiP$:new N(!1),inFullscreen$:new N(!1),element$:new N(void 0),elementVisible$:new N(!0),availableSources$:new N(void 0),is3DVideo$:new N(!1),playbackState$:new N(""),getCurrentTime$:new N(null)};this.subscription=new AT;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=By([...Ny(this.params.tuning),..._y(this.params.tuning)],this.params.tuning).filter(l=>wT(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning,s=[];i?s=[i]:r.length?s=[...t.filter(l=>!(0,xc.default)(r,l)),...t.filter(l=>(0,xc.default)(r,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",kT(s)),this.screenFormatsIterator=new Ka(s);let n=[...ec(!0),...ec(!1)];this.chromecastFormatsIterator=new Ka(n.filter(l=>wT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&lr.isSupported()&&(this.volumeMultiplierManager=new lr(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(h0(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:jn.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.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,i=this.params.desiredState.seekState.getState(),r=i.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){let 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 Ja(e)}}createScreenProvider(e){let{sources:t,container:i,desiredState:r,panelSize:s}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning,panelSize:s};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let u=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Gt(u),new Ua(C(A({},o),{source:u,sourceHls:l}))}case"DASH_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ha(C(A({},o),{source:u}))}case"HLS":case"HLS_ONDEMAND":{let u=this.applyFailoverHost(t[e]);return Gt(u),q.video.nativeHlsSupported||!this.params.tuning.useHlsJs?new Wa(C(A({},o),{source:u})):new Qa(C(A({},o),{source:u}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ga(C(A({},o),{source:u,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Ya(C(A({},o),{source:u}))}case"DASH_LIVE":{let u=this.applyFailoverHost(t[e]);return Gt(u),new Lv(C(A({},o),{source:u,config:C(A({},g0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let u=this.applyFailoverHost(t[e]);return Gt(u),new za({container:i,source:u,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ja(e)}}createChromecastProvider(e){let{sources:t,container:i,desiredState:r,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Gt(o),new Fr({connection:o,meta:s,container:i,source:t,format:e,desiredState:r,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 Ja(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Ja(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 Ja(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let i=r=>{let s=new URL(r);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 C(A({},e),{url:i(e.url)})}return(0,LT.default)((0,RT.default)(e).map(([r,s])=>[r,i(s)]))}initProviderErrorHandling(){let e=new AT,t=!1,i=0;return e.add(f0(this.providerOutput.error$.pipe(PT(r=>!this.params.tuning.ignoreAudioRendererError||!r.message||!/AUDIO_RENDERER_ERROR/ig.test(r.message))),TT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(m0(r=>({id:`ProviderHangup:${r}`,category:jn.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.providerOutput.fetcherError$.subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let r=this.params.desiredState.playbackState.transitionEnded$.pipe(PT(({to:s})=>s==="playing"),b0()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{let s=this.current$.getValue().destination,n={error:r,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=r.category===jn.NETWORK,u=r.category===jn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=i<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=C(A({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(i++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):(i=0,this.switchToNextProvider(s!=null?s:"SCREEN"))}this.tracer.error("providerError",kT(n))})),e}};import{fromEvent as Qn,once as v0,combine as S0,Subscription as $T,ValueSubject as Pc,map as y0,filter as T0,isNonNullable as Gn,now as Ne,safeStorage as wc}from"@vkontakte/videoplayer-shared/es2015";var I0=5e3,MT="one_video_throughput",DT="one_video_rtt",Et=window.navigator.connection,CT=()=>{let a=Et==null?void 0:Et.downlink;if(Gn(a)&&a!==10)return a*1e3},VT=()=>{let a=Et==null?void 0:Et.rtt;if(Gn(a)&&a!==3e3)return a},OT=(a,e,t)=>{let i=t*8,r=i/a;return i/(r+e)},Ac=class a{constructor(e){this.subscription=new $T;this.concurrentDownloads=new Set;var r,s;this.tuningConfig=e;let t=a.load(MT)||(e.useBrowserEstimation?CT():void 0)||I0,i=(s=(r=a.load(DT))!=null?r:e.useBrowserEstimation?VT():void 0)!=null?s:0;if(this.throughput$=new Pc(t),this.rtt$=new Pc(i),this.rttAdjustedThroughput$=new Pc(OT(t,i,e.rttPenaltyRequestSize)),this.throughput=vi.getSmoothedValue(t,-1,e),this.rtt=vi.getSmoothedValue(i,1,e),e.useBrowserEstimation){let n=()=>{let u=CT();u&&this.throughput.next(u);let l=VT();Gn(l)&&this.rtt.next(l)};Et&&"onchange"in Et&&this.subscription.add(Qn(Et,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{wc.set(MT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{wc.set(DT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(S0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(y0(({throughput:n,rtt:o})=>OT(n,o,e.rttPenaltyRequestSize)),T0(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,i=Ne(),r=new $T;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(Qn(e,"progress").pipe(v0()).subscribe(s=>{t=s.loaded,i=Ne()}));break;case 1:case 0:r.add(Qn(e,"loadstart").subscribe(()=>{t=0,i=Ne()}));break}r.add(Qn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Ne(),u=n-t,l=o-i;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){let i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,s=Ne(),n=0,o=Ne(),u=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=h=>P(this,[h],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(r,Ne()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let p=Ne();if(p-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||p-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Ne()}else n+=d.byteLength;o=Ne()}else r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Ne()-o,this.concurrentDownloads.size),n=0,o=Ne());yield i==null?void 0:i.read().then(l,u)}});this.concurrentDownloads.add(e),i==null||i.read().then(l,u)}addRawSpeed(e,t,i=1,r=!1){if(a.sanityCheck(e,t,r)){let s=e*8/t;this.throughput.next(s*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){let r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var i;let t=wc.get(e);if(Gn(t))return(i=parseInt(t,10))!=null?i:void 0}},BT=Ac;import{fillWithDefault as E0,VideoQuality as Wn}from"@vkontakte/videoplayer-shared/es2015";var _T={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:Wn.Q_4320P,activeVideoAreaThreshold:.1,highQualityLimit:Wn.Q_720P,trafficSavingLimit:Wn.Q_480P},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Wn.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,seekBiasInTheEnd:2e3,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,stallDurationToBeCount:100,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4,ignoreStallsOnSeek:!1},enableBaseUrlSupport:!0,maxSegmentRetryCount:5,sourceOpenTimeout:1e3,rejectOnSourceOpenTimeout:!1},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:7200,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,seekNearDurationBias:1,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!1,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,disableYandexPiP:!1,asyncResolveClientChecker:!1,autostartOnlyIfVisible:!1},NT=a=>{var e;return C(A({},E0(a,_T)),{configName:[...(e=a.configName)!=null?e:[],..._T.configName]})};import{assertNonNullable as Yn,combine as xt,ErrorCategory as zn,filter as V,filterChanged as Y,fromEvent as Rc,isNonNullable as HT,isNullable as L0,Logger as $0,map as G,mapTo as jT,merge as Wt,now as Kn,once as U,Subject as X,Subscription as QT,tap as Lc,ValueSubject as k,isHigher as M0,isInvariantQuality as GT,flattenObject as Yt,throttle as $c,getTraceSubscriptionMethod as WT,Tracer as D0,InternalsExposure as C0}from"@vkontakte/videoplayer-shared/es2015";import{merge as x0,map as P0,filter as FT,isNonNullable as w0}from"@vkontakte/videoplayer-shared/es2015";var kc=({seekState:a,position$:e})=>x0(a.stateChangeEnded$.pipe(P0(({to:t})=>{var i;return t.state==="none"?void 0:((i=t.position)!=null?i:NaN)/1e3}),FT(w0)),e.pipe(FT(()=>a.getState().state==="none")));import{assertNonNullable as A0}from"@vkontakte/videoplayer-shared/es2015";var qT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return A0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as k0,once as R0}from"@vkontakte/videoplayer-shared/es2015";var UT=(a,e,t,i)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(k0(r=>r.length>0),R0()).subscribe(r=>{r.find(i)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(a)};var Xn=class{constructor(e={configName:[]},t=D0.createRootTracer(!1)){this.subscription=new QT;this.logger=new $0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new k(!1);this.hasLiveOffsetByPausedTimer=0;this.playerInitRequest=0;this.playerInited=new k(!1);this.wasSetStartedQuality=!1;this.desiredState={playbackState:new _("stopped"),seekState:new _({state:"none"}),volume:new _({volume:1,muted:!1}),videoTrack:new _(void 0),videoStream:new _(void 0),audioStream:new _(void 0),autoVideoTrackSwitching:new _(!0),autoVideoTrackLimits:new _({}),isLooped:new _(!1),isLowLatency:new _(!1),playbackRate:new _(1),externalTextTracks:new _([]),internalTextTracks:new _([]),currentTextTrack:new _(void 0),textTrackCuesSettings:new _({}),cameraOrientation:new _({x:0,y:0})};this.info={playbackState$:new k(void 0),position$:new k(0),duration$:new k(1/0),muted$:new k(!1),volume$:new k(1),availableVideoStreams$:new k([]),currentVideoStream$:new k(void 0),availableQualities$:new k([]),availableQualitiesFps$:new k({}),currentQuality$:new k(void 0),isAutoQualityEnabled$:new k(!0),autoQualityLimitingAvailable$:new k(!1),autoQualityLimits$:new k({}),predefinedQualityLimitType$:new k("unknown"),availableAudioStreams$:new k([]),currentAudioStream$:new k(void 0),availableAudioTracks$:new k([]),isAudioAvailable$:new k(!0),currentPlaybackRate$:new k(1),currentBuffer$:new k({start:0,end:0}),isBuffering$:new k(!0),isStalled$:new k(!1),isEnded$:new k(!1),isLooped$:new k(!1),isLive$:new k(void 0),isLiveEnded$:new k(null),canChangePlaybackSpeed$:new k(void 0),atLiveEdge$:new k(void 0),atLiveDurationEdge$:new k(void 0),liveTime$:new k(void 0),liveBufferTime$:new k(void 0),liveLatency$:new k(void 0),currentFormat$:new k(void 0),availableTextTracks$:new k([]),currentTextTrack$:new k(void 0),throughputEstimation$:new k(void 0),rttEstimation$:new k(void 0),videoBitrate$:new k(void 0),hostname$:new k(void 0),httpConnectionType$:new k(void 0),httpConnectionReused$:new k(void 0),surface$:new k("none"),chromecastState$:new k("NOT_AVAILABLE"),chromecastDeviceName$:new k(void 0),intrinsicVideoSize$:new k(void 0),availableSources$:new k(void 0),is3DVideo$:new k(!1),currentVideoSegmentLength$:new k(0),currentAudioSegmentLength$:new k(0)};this.events={inited$:new X,ready$:new X,started$:new X,playing$:new X,paused$:new X,stopped$:new X,willStart$:new X,willResume$:new X,willPause$:new X,willStop$:new X,willDestruct$:new X,watchCoverageRecord$:new X,watchCoverageLive$:new X,managedError$:new X,fatalError$:new X,fetcherRecoverableError$:new X,ended$:new X,looped$:new X,seeked$:new X,willSeek$:new X,autoplaySoundProhibited$:new X,firstBytes$:new X,loadedMetadata$:new X,firstFrame$:new X,canplay$:new X,log$:new X,fetcherError$:new X,severeStallOccured$:new X};this.experimental={element$:new k(void 0),tuningConfigName$:new k([]),enableDebugTelemetry$:new k(!1),dumpTelemetry:ev,getCurrentTime$:new k(null)};if(this.initLogs(),this.tuning=NT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Is({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new BT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new C0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(i,r,s)=>{let n=Reflect.get(i,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(i,o)}catch(u){let l=o.map(h=>JSON.stringify(h,(p,m)=>{let b=typeof m;return(0,YT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(r)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:zn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s;this.config=e,(s=this.internalsExposure)==null||s.expose({config:e,logger:this.logger,tuning:this.tuning});let t=()=>{var l,c,d;let u=e,{container:n}=u,o=vd(u,["container"]);this.tracer.log("initVideo",Yt(o)),this.domContainer=qT(e),this.chromecastInitializer.contentId=(l=e.meta)==null?void 0:l.videoId,this.providerContainer=new Za({sources:e.sources,meta:(c=e.meta)!=null?c:{},failoverHosts:(d=e.failoverHosts)!=null?d:[],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,panelSize:e.panelSize}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this.playerInited.next(!0)},i=()=>{this.tuning.autostartOnlyIfVisible&&window.requestAnimationFrame?this.playerInitRequest=window.requestAnimationFrame(()=>t()):t()},r=()=>{this.tuning.asyncResolveClientChecker?q.isInited$.pipe(V(n=>!!n),U()).subscribe(()=>{console.log("Core SDK async start"),i()}):i()};return this.isNotActiveTabCase()?(this.tracer.log("request play from hidden tab"),Rc(document,"visibilitychange").pipe(U()).subscribe(r)):r(),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.playerInitRequest&&window.cancelAnimationFrame(this.playerInitRequest),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(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),U()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready")})),this}play(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),U()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:e.getState()}),e.getState()!=="playing"&&e.startTransitionTo("playing")})),this}pause(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),U()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused")})),this}stop(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),U()).subscribe(()=>{let e=this.desiredState.playbackState;this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped")})),this}seekTime(e,t=!0){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),U()).subscribe(()=>{let i=this.info.duration$.getValue(),r=this.info.isLive$.getValue(),s=e;e>=i&&!r&&(s=i-this.tuning.seekNearDurationBias),this.tracer.log("seekTime",{duration:i,isLive:r,time:e,calculatedTime:s,forcePrecise:t}),Number.isFinite(s)&&(this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}))})),this}seekPercent(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{let t=this.info.duration$.getValue();this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1)})),this}setVolume(e,t){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),U()).subscribe(()=>{var o;let i=this.desiredState.volume,r=i.getTransition(),s=(o=r==null?void 0:r.to.muted)!=null?o:this.info.muted$.getValue(),n=t!=null?t:this.tuning.isAudioDisabled||s;this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:n}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):i.startTransitionTo({volume:e,muted:n})})),this}setMuted(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{var n;let t=this.desiredState.volume,i=this.tuning.isAudioDisabled||e,r=t.getTransition(),s=(n=r==null?void 0:r.to.volume)!=null?n:this.info.volume$.getValue();this.tracer.log("setMuted",{isMuted:e,nextMuted:i,volume:s,isAudioDisabled:this.tuning.isAudioDisabled,chromecastState:this.chromecastInitializer.castState$.getValue()}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(i):t.startTransitionTo({volume:s,muted:i})})),this}setVideoStream(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{this.desiredState.videoStream.startTransitionTo(e)})),this}setAudioStream(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{this.desiredState.audioStream.startTransitionTo(e)})),this}setQuality(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{Yn(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();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(V(i=>i.length>0),U()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e)})),this}setAutoQuality(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e)})),this}setAutoQualityLimits(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{this.tracer.log("setAutoQualityLimits",Yt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e)})),this}setPredefinedQualityLimits(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection,r;switch(e){case"high_quality":r={min:t,max:void 0};break;case"traffic_saving":r={max:i,min:void 0};break;default:r={max:void 0,min:void 0}}this.setAutoQualityLimits(r)})),this}setPlaybackRate(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{var i;Yn(this.providerContainer);let t=(i=this.providerContainer)==null?void 0:i.providerOutput.element$.getValue();this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e)})),this}setExternalTextTracks(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{e.length&&this.tracer.log("setExternalTextTracks",Yt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>A({type:"external"},t)))})),this}selectTextTrack(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{var t;UT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this.tracer.log("selectTextTrack",{textTrackId:e})})),this}setTextTrackCueSettings(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{this.tracer.log("setTextTrackCueSettings",A({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e)})),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),i=this.desiredState.isLowLatency.getState();return!t||i===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e)})),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),U()).subscribe(()=>{let i=this.getScene3D();this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!i,mx:e,my:t}),i&&i.startCameraManualRotation(e,t)})),this}stopCameraManualRotation(e=!1){return this.subscription.add(this.playerInited.pipe(V(t=>!!t),U()).subscribe(()=>{let t=this.getScene3D();this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e)})),this}moveCameraFocusPX(e,t){return this.subscription.add(this.playerInited.pipe(V(i=>!!i),U()).subscribe(()=>{let i=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!i,dxpx:e,dypx:t}),i){let r=i.getCameraRotation(),s=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+s.x,y:r.y+s.y})}})),this}holdCamera(){return this.subscription.add(this.playerInited.pipe(V(e=>e),U()).subscribe(()=>{let e=this.getScene3D();e&&e.holdCamera()})),this}releaseCamera(){return this.subscription.add(this.playerInited.pipe(V(e=>!!e),U()).subscribe(()=>{let e=this.getScene3D();e&&e.releaseCamera()})),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(L0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),i=t.state==="none"?void 0:t.position;return HT(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,i;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((i=e==null?void 0:e.provider)!=null&&i.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(G(e=>e.to)).subscribe(e=>{this.info.autoQualityLimits$.next(e);let{highQualityLimit:t,trafficSavingLimit:i}=this.tuning.autoTrackSelection;this.info.predefinedQualityLimitType$.next(dl({limits:e,highQualityLimit:t,trafficSavingLimit:i}))})),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(V(({from:e})=>e==="stopped"),U()).subscribe(()=>{this.initedAt=Kn(),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",Yt(n)),n.state==="requested"?this.desiredState.seekState.setState(C(A({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:zn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(U()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.severeStallOccurred$.subscribe(this.events.severeStallOccured$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Yt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(G(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(G(n=>n.destination),Y()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(xt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(G(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>GT(u)?1:GT(l)?-1:M0(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(Y()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.pipe(V(n=>HT(n))).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(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(Y((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(Y()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(Y()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(Y()).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(G(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.isLiveEnded$.pipe(Lc(n=>n&&this.stop())).subscribe(this.info.isLiveEnded$)).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(xt({hasLiveOffsetByPaused:Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(G(n=>n.to),Y(),G(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(xt({atLiveEdge:xt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:kc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(G(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),Y(),Lc(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(G(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(xt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(G(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),Y(),Lc(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(G(n=>n.muted),Y()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(G(n=>n.volume),Y()).subscribe(this.info.volume$)).add(kc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Wt(e.providerOutput.endedEvent$.pipe(jT(!0)),e.providerOutput.seekedEvent$.pipe(jT(!1))).pipe(Y()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.providerOutput.fetcherRecoverableError$.subscribe(this.events.fetcherRecoverableError$)).add(e.providerOutput.fetcherError$.subscribe(this.events.fatalError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(G(n=>({id:n?`No${n}`:"NoProviders",category:zn.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(U(),G(n=>n!=null?n:Kn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(U(),G(()=>Kn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(U(),G(()=>Kn()-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 k(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let i=new k(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(V(({to:n})=>n==="playing"),U()).subscribe(()=>i.next(!1)));let r=0,s=Wt(e.providerOutput.isBuffering$,t,i).pipe(G(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),Y());this.subscription.add(s.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(Wt(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(Wt(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(G(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 QT;this.subscription.add(t),this.subscription.add(e.current$.pipe(Y((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(V(i=>i.length>0),U()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var r;let t;this.wasSetStartedQuality=!0;let i=(r=this.explicitInitialQuality)!=null?r:this.info.currentQuality$.getValue();i&&(t=e.find(({quality:s})=>s===i),t||this.setAutoQuality(!0)),t||(t=qt(e,{container:this.domContainer.getBoundingClientRect(),panelSize:this.config.panelSize,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(Wt(this.desiredState.videoTrack.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(G(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(G(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(G(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;Yn(this.providerContainer),Yn(e),Zg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Jg(i)),this.providerContainer.current$.subscribe(({type:i})=>Qr("provider",i)),e.duration$.subscribe(i=>Qr("duration",i)),e.availableVideoTracks$.pipe(V(i=>!!i.length),U()).subscribe(i=>Qr("tracks",i)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),e.position$.subscribe(new Ie("position")),e.currentVideoTrack$.pipe(G(i=>i==null?void 0:i.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),e.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(i=>this.subscription.add(i)),Qr("codecs",q.video.supportedCodecs)}initTracerSubscription(){let e=WT(this.tracer.log.bind(this.tracer)),t=WT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(Y()).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(xt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(V(({currentQuality:i,videoBitrate:r})=>!!i&&!!r),Y((i,r)=>i.currentQuality===r.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(V(i=>i>0),Y()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(V(i=>i>0),Y()).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(xt({currentBuffer:this.info.currentBuffer$.pipe(V(i=>i.end>0),Y((i,r)=>i.end===r.end&&i.start===r.start)),position:this.info.position$.pipe(Y())}).pipe($c(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(Y()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(Y()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(Y()).subscribe(e("canChangePlaybackSpeed"))).add(xt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(V(({liveTime:i,liveBufferTime:r})=>!!i&&!!r),$c(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(Y(),V(i=>i===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(Y(),V(i=>i===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(Y()).subscribe(e("muted"))).add(this.info.volume$.pipe(Y()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(Y(),V(i=>i===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(xt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(V(({throughputEstimation:i,rtt:r})=>!!i&&!!r),$c(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(Y(),V(i=>i===!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},i=()=>P(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:zn.DOM,message:String(r)})})});this.subscription.add(Wt(Rc(document,"visibilitychange"),Rc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let r=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);r&&s?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let i=e.find(r=>r.quality===t);this.tracer.log("setVideoTrackIdByQuality",Yt({quality:t,availableTracks:Yt(e),track:Yt(i),isAutoQuality:!i})),i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}isNotActiveTabCase(){return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Jr()}};import{Subscription as t6,Observable as i6,Subject as r6,ValueSubject as a6,VideoQuality as s6}from"@vkontakte/videoplayer-shared/es2015";var n6=`@vkontakte/videoplayer-core@${Sd}`;export{fs as ChromecastState,so as HttpConnectionType,i6 as Observable,Ce as PlaybackState,Xn as Player,bs as PredefinedQualityLimits,n6 as SDK_VERSION,r6 as Subject,t6 as Subscription,no as Surface,Sd as VERSION,a6 as ValueSubject,mt as VideoFormat,s6 as VideoQuality,q as clientChecker,Hr as isMobile};