@vkontakte/videoplayer-core 2.0.123-dev.428b52a4.0 → 2.0.123-dev.43da90c8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.esm.js CHANGED
@@ -1,52 +1,52 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.123-dev.428b52a4.0
3
- * Mon, 23 Dec 2024 12:04:06 GMT
2
+ * @vkontakte/videoplayer-core v2.0.123-dev.43da90c8.0
3
+ * Tue, 14 Jan 2025 08:21:37 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-123/doc/
5
5
  */
6
- var HT=Object.create;var Jn=Object.defineProperty,jT=Object.defineProperties,GT=Object.getOwnPropertyDescriptor,QT=Object.getOwnPropertyDescriptors,WT=Object.getOwnPropertyNames,hs=Object.getOwnPropertySymbols,YT=Object.getPrototypeOf,Xn=Object.prototype.hasOwnProperty,Jc=Object.prototype.propertyIsEnumerable;var zT=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var it=Math.pow,Kc=(a,e,t)=>e in a?Jn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,x=(a,e)=>{for(var t in e||(e={}))Xn.call(e,t)&&Kc(a,t,e[t]);if(hs)for(var t of hs(e))Jc.call(e,t)&&Kc(a,t,e[t]);return a},C=(a,e)=>jT(a,QT(e));var Xc=(a,e)=>{var t={};for(var r in a)Xn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&hs)for(var r of hs(a))e.indexOf(r)<0&&Jc.call(a,r)&&(t[r]=a[r]);return t};var m=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var KT=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of WT(e))!Xn.call(a,i)&&i!==t&&Jn(a,i,{get:()=>e[i],enumerable:!(r=GT(e,i))||r.enumerable});return a};var _=(a,e,t)=>(t=a!=null?HT(YT(a)):{},KT(e||!a||!a.__esModule?Jn(t,"default",{value:a,enumerable:!0}):t,a));var k=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Zn=function(a,e){this[0]=a,this[1]=e},ae=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Zn,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[zT("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var te=m((ro,ed)=>{"use strict";var yi=function(a){return a&&a.Math===Math&&a};ed.exports=yi(typeof globalThis=="object"&&globalThis)||yi(typeof window=="object"&&window)||yi(typeof self=="object"&&self)||yi(typeof global=="object"&&global)||yi(typeof ro=="object"&&ro)||function(){return this}()||Function("return this")()});var pe=m((yD,td)=>{"use strict";td.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ti=m((TD,rd)=>{"use strict";var JT=pe();rd.exports=!JT(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var io=m((ID,nd)=>{"use strict";var XT=Ti(),sd=Function.prototype,id=sd.apply,ad=sd.call;nd.exports=typeof Reflect=="object"&&Reflect.apply||(XT?ad.bind(id):function(){return ad.apply(id,arguments)})});var ne=m((ED,ld)=>{"use strict";var od=Ti(),ud=Function.prototype,ao=ud.call,ZT=od&&ud.bind.bind(ao,ao);ld.exports=od?ZT:function(a){return function(){return ao.apply(a,arguments)}}});var rr=m((xD,dd)=>{"use strict";var cd=ne(),eI=cd({}.toString),tI=cd("".slice);dd.exports=function(a){return tI(eI(a),8,-1)}});var so=m((PD,pd)=>{"use strict";var rI=rr(),iI=ne();pd.exports=function(a){if(rI(a)==="Function")return iI(a)}});var Z=m((wD,hd)=>{"use strict";var no=typeof document=="object"&&document.all;hd.exports=typeof no=="undefined"&&no!==void 0?function(a){return typeof a=="function"||a===no}:function(a){return typeof a=="function"}});var $e=m((AD,fd)=>{"use strict";var aI=pe();fd.exports=!aI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Le=m((kD,md)=>{"use strict";var sI=Ti(),ms=Function.prototype.call;md.exports=sI?ms.bind(ms):function(){return ms.apply(ms,arguments)}});var oo=m(vd=>{"use strict";var bd={}.propertyIsEnumerable,gd=Object.getOwnPropertyDescriptor,nI=gd&&!bd.call({1:2},1);vd.f=nI?function(e){var t=gd(this,e);return!!t&&t.enumerable}:bd});var Ii=m(($D,Sd)=>{"use strict";Sd.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Td=m((LD,yd)=>{"use strict";var oI=ne(),uI=pe(),lI=rr(),uo=Object,cI=oI("".split);yd.exports=uI(function(){return!uo("z").propertyIsEnumerable(0)})?function(a){return lI(a)==="String"?cI(a,""):uo(a)}:uo});var Cr=m((MD,Id)=>{"use strict";Id.exports=function(a){return a==null}});var Mt=m((CD,Ed)=>{"use strict";var dI=Cr(),pI=TypeError;Ed.exports=function(a){if(dI(a))throw new pI("Can't call method on "+a);return a}});var ir=m((DD,xd)=>{"use strict";var hI=Td(),fI=Mt();xd.exports=function(a){return hI(fI(a))}});var Me=m((OD,Pd)=>{"use strict";var mI=Z();Pd.exports=function(a){return typeof a=="object"?a!==null:mI(a)}});var Dr=m((BD,wd)=>{"use strict";wd.exports={}});var dt=m((VD,kd)=>{"use strict";var lo=Dr(),co=te(),bI=Z(),Ad=function(a){return bI(a)?a:void 0};kd.exports=function(a,e){return arguments.length<2?Ad(lo[a])||Ad(co[a]):lo[a]&&lo[a][e]||co[a]&&co[a][e]}});var Ei=m((_D,Rd)=>{"use strict";var gI=ne();Rd.exports=gI({}.isPrototypeOf)});var ar=m((ND,Md)=>{"use strict";var vI=te(),$d=vI.navigator,Ld=$d&&$d.userAgent;Md.exports=Ld?String(Ld):""});var ho=m((FD,_d)=>{"use strict";var Vd=te(),po=ar(),Cd=Vd.process,Dd=Vd.Deno,Od=Cd&&Cd.versions||Dd&&Dd.version,Bd=Od&&Od.v8,Ye,bs;Bd&&(Ye=Bd.split("."),bs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!bs&&po&&(Ye=po.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=po.match(/Chrome\/(\d+)/),Ye&&(bs=+Ye[1])));_d.exports=bs});var fo=m((qD,Fd)=>{"use strict";var Nd=ho(),SI=pe(),yI=te(),TI=yI.String;Fd.exports=!!Object.getOwnPropertySymbols&&!SI(function(){var a=Symbol("symbol detection");return!TI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Nd&&Nd<41})});var mo=m((UD,qd)=>{"use strict";var II=fo();qd.exports=II&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var bo=m((HD,Ud)=>{"use strict";var EI=dt(),xI=Z(),PI=Ei(),wI=mo(),AI=Object;Ud.exports=wI?function(a){return typeof a=="symbol"}:function(a){var e=EI("Symbol");return xI(e)&&PI(e.prototype,AI(a))}});var xi=m((jD,Hd)=>{"use strict";var kI=String;Hd.exports=function(a){try{return kI(a)}catch(e){return"Object"}}});var at=m((GD,jd)=>{"use strict";var RI=Z(),$I=xi(),LI=TypeError;jd.exports=function(a){if(RI(a))return a;throw new LI($I(a)+" is not a function")}});var Pi=m((QD,Gd)=>{"use strict";var MI=at(),CI=Cr();Gd.exports=function(a,e){var t=a[e];return CI(t)?void 0:MI(t)}});var Wd=m((WD,Qd)=>{"use strict";var go=Le(),vo=Z(),So=Me(),DI=TypeError;Qd.exports=function(a,e){var t,r;if(e==="string"&&vo(t=a.toString)&&!So(r=go(t,a))||vo(t=a.valueOf)&&!So(r=go(t,a))||e!=="string"&&vo(t=a.toString)&&!So(r=go(t,a)))return r;throw new DI("Can't convert object to primitive value")}});var ze=m((YD,Yd)=>{"use strict";Yd.exports=!0});var Jd=m((zD,Kd)=>{"use strict";var zd=te(),OI=Object.defineProperty;Kd.exports=function(a,e){try{OI(zd,a,{value:e,configurable:!0,writable:!0})}catch(t){zd[a]=e}return e}});var wi=m((KD,ep)=>{"use strict";var BI=ze(),VI=te(),_I=Jd(),Xd="__core-js_shared__",Zd=ep.exports=VI[Xd]||_I(Xd,{});(Zd.versions||(Zd.versions=[])).push({version:"3.38.0",mode:BI?"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 yo=m((JD,rp)=>{"use strict";var tp=wi();rp.exports=function(a,e){return tp[a]||(tp[a]=e||{})}});var Or=m((XD,ip)=>{"use strict";var NI=Mt(),FI=Object;ip.exports=function(a){return FI(NI(a))}});var Ke=m((ZD,ap)=>{"use strict";var qI=ne(),UI=Or(),HI=qI({}.hasOwnProperty);ap.exports=Object.hasOwn||function(e,t){return HI(UI(e),t)}});var To=m((eO,sp)=>{"use strict";var jI=ne(),GI=0,QI=Math.random(),WI=jI(1 .toString);sp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+WI(++GI+QI,36)}});var he=m((tO,op)=>{"use strict";var YI=te(),zI=yo(),np=Ke(),KI=To(),JI=fo(),XI=mo(),Br=YI.Symbol,Io=zI("wks"),ZI=XI?Br.for||Br:Br&&Br.withoutSetter||KI;op.exports=function(a){return np(Io,a)||(Io[a]=JI&&np(Br,a)?Br[a]:ZI("Symbol."+a)),Io[a]}});var dp=m((rO,cp)=>{"use strict";var eE=Le(),up=Me(),lp=bo(),tE=Pi(),rE=Wd(),iE=he(),aE=TypeError,sE=iE("toPrimitive");cp.exports=function(a,e){if(!up(a)||lp(a))return a;var t=tE(a,sE),r;if(t){if(e===void 0&&(e="default"),r=eE(t,a,e),!up(r)||lp(r))return r;throw new aE("Can't convert object to primitive value")}return e===void 0&&(e="number"),rE(a,e)}});var Eo=m((iO,pp)=>{"use strict";var nE=dp(),oE=bo();pp.exports=function(a){var e=nE(a,"string");return oE(e)?e:e+""}});var gs=m((aO,fp)=>{"use strict";var uE=te(),hp=Me(),xo=uE.document,lE=hp(xo)&&hp(xo.createElement);fp.exports=function(a){return lE?xo.createElement(a):{}}});var Po=m((sO,mp)=>{"use strict";var cE=$e(),dE=pe(),pE=gs();mp.exports=!cE&&!dE(function(){return Object.defineProperty(pE("div"),"a",{get:function(){return 7}}).a!==7})});var vp=m(gp=>{"use strict";var hE=$e(),fE=Le(),mE=oo(),bE=Ii(),gE=ir(),vE=Eo(),SE=Ke(),yE=Po(),bp=Object.getOwnPropertyDescriptor;gp.f=hE?bp:function(e,t){if(e=gE(e),t=vE(t),yE)try{return bp(e,t)}catch(r){}if(SE(e,t))return bE(!fE(mE.f,e,t),e[t])}});var wo=m((oO,Sp)=>{"use strict";var TE=pe(),IE=Z(),EE=/#|\.prototype\./,Ai=function(a,e){var t=PE[xE(a)];return t===AE?!0:t===wE?!1:IE(e)?TE(e):!!e},xE=Ai.normalize=function(a){return String(a).replace(EE,".").toLowerCase()},PE=Ai.data={},wE=Ai.NATIVE="N",AE=Ai.POLYFILL="P";Sp.exports=Ai});var Vr=m((uO,Tp)=>{"use strict";var yp=so(),kE=at(),RE=Ti(),$E=yp(yp.bind);Tp.exports=function(a,e){return kE(a),e===void 0?a:RE?$E(a,e):function(){return a.apply(e,arguments)}}});var Ao=m((lO,Ip)=>{"use strict";var LE=$e(),ME=pe();Ip.exports=LE&&ME(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var st=m((cO,Ep)=>{"use strict";var CE=Me(),DE=String,OE=TypeError;Ep.exports=function(a){if(CE(a))return a;throw new OE(DE(a)+" is not an object")}});var sr=m(Pp=>{"use strict";var BE=$e(),VE=Po(),_E=Ao(),vs=st(),xp=Eo(),NE=TypeError,ko=Object.defineProperty,FE=Object.getOwnPropertyDescriptor,Ro="enumerable",$o="configurable",Lo="writable";Pp.f=BE?_E?function(e,t,r){if(vs(e),t=xp(t),vs(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Lo in r&&!r[Lo]){var i=FE(e,t);i&&i[Lo]&&(e[t]=r.value,r={configurable:$o in r?r[$o]:i[$o],enumerable:Ro in r?r[Ro]:i[Ro],writable:!1})}return ko(e,t,r)}:ko:function(e,t,r){if(vs(e),t=xp(t),vs(r),VE)try{return ko(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new NE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var _r=m((pO,wp)=>{"use strict";var qE=$e(),UE=sr(),HE=Ii();wp.exports=qE?function(a,e,t){return UE.f(a,e,HE(1,t))}:function(a,e,t){return a[e]=t,a}});var ie=m((hO,kp)=>{"use strict";var ki=te(),jE=io(),GE=so(),QE=Z(),WE=vp().f,YE=wo(),Nr=Dr(),zE=Vr(),Fr=_r(),Ap=Ke();wi();var KE=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return jE(a,this,arguments)};return e.prototype=a.prototype,e};kp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ki:i?ki[t]:ki[t]&&ki[t].prototype,o=r?Nr:Nr[t]||Fr(Nr,t,{})[t],u=o.prototype,l,c,d,p,h,f,b,g,S;for(p in e)l=YE(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Ap(n,p),f=o[p],c&&(a.dontCallGetSet?(S=WE(n,p),b=S&&S.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof f==typeof h)&&(a.bind&&c?g=zE(h,ki):a.wrap&&c?g=KE(h):s&&QE(h)?g=GE(h):g=h,(a.sham||h&&h.sham||f&&f.sham)&&Fr(g,"sham",!0),Fr(o,p,g),s&&(d=t+"Prototype",Ap(Nr,d)||Fr(Nr,d,{}),Fr(Nr[d],p,h),a.real&&u&&(l||!u[p])&&Fr(u,p,h)))}});var $p=m((fO,Rp)=>{"use strict";var JE=Math.ceil,XE=Math.floor;Rp.exports=Math.trunc||function(e){var t=+e;return(t>0?XE:JE)(t)}});var Ri=m((mO,Lp)=>{"use strict";var ZE=$p();Lp.exports=function(a){var e=+a;return e!==e||e===0?0:ZE(e)}});var Cp=m((bO,Mp)=>{"use strict";var ex=Ri(),tx=Math.max,rx=Math.min;Mp.exports=function(a,e){var t=ex(a);return t<0?tx(t+e,0):rx(t,e)}});var Mo=m((gO,Dp)=>{"use strict";var ix=Ri(),ax=Math.min;Dp.exports=function(a){var e=ix(a);return e>0?ax(e,9007199254740991):0}});var qr=m((vO,Op)=>{"use strict";var sx=Mo();Op.exports=function(a){return sx(a.length)}});var Co=m((SO,Vp)=>{"use strict";var nx=ir(),ox=Cp(),ux=qr(),Bp=function(a){return function(e,t,r){var i=nx(e),s=ux(i);if(s===0)return!a&&-1;var n=ox(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Vp.exports={includes:Bp(!0),indexOf:Bp(!1)}});var $i=m((yO,_p)=>{"use strict";_p.exports=function(){}});var Np=m(()=>{"use strict";var lx=ie(),cx=Co().includes,dx=pe(),px=$i(),hx=dx(function(){return!Array(1).includes()});lx({target:"Array",proto:!0,forced:hx},{includes:function(e){return cx(this,e,arguments.length>1?arguments[1]:void 0)}});px("includes")});var Ct=m((EO,Fp)=>{"use strict";var fx=dt();Fp.exports=fx});var Up=m((xO,qp)=>{"use strict";Np();var mx=Ct();qp.exports=mx("Array","includes")});var jp=m((PO,Hp)=>{"use strict";var bx=Up();Hp.exports=bx});var Je=m((wO,Gp)=>{"use strict";var gx=jp();Gp.exports=gx});var Ts=m((_O,Zp)=>{"use strict";var Px=yo(),wx=To(),Xp=Px("keys");Zp.exports=function(a){return Xp[a]||(Xp[a]=wx(a))}});var th=m((NO,eh)=>{"use strict";var Ax=pe();eh.exports=!Ax(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Is=m((FO,ih)=>{"use strict";var kx=Ke(),Rx=Z(),$x=Or(),Lx=Ts(),Mx=th(),rh=Lx("IE_PROTO"),Bo=Object,Cx=Bo.prototype;ih.exports=Mx?Bo.getPrototypeOf:function(a){var e=$x(a);if(kx(e,rh))return e[rh];var t=e.constructor;return Rx(t)&&e instanceof t?t.prototype:e instanceof Bo?Cx:null}});var Es=m((qO,ah)=>{"use strict";ah.exports={}});var oh=m((UO,nh)=>{"use strict";var Dx=ne(),Vo=Ke(),Ox=ir(),Bx=Co().indexOf,Vx=Es(),sh=Dx([].push);nh.exports=function(a,e){var t=Ox(a),r=0,i=[],s;for(s in t)!Vo(Vx,s)&&Vo(t,s)&&sh(i,s);for(;e.length>r;)Vo(t,s=e[r++])&&(~Bx(i,s)||sh(i,s));return i}});var _o=m((HO,uh)=>{"use strict";uh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var No=m((jO,lh)=>{"use strict";var _x=oh(),Nx=_o();lh.exports=Object.keys||function(e){return _x(e,Nx)}});var Fo=m((GO,fh)=>{"use strict";var dh=$e(),Fx=pe(),ph=ne(),qx=Is(),Ux=No(),Hx=ir(),jx=oo().f,hh=ph(jx),Gx=ph([].push),Qx=dh&&Fx(function(){var a=Object.create(null);return a[2]=2,!hh(a,2)}),ch=function(a){return function(e){for(var t=Hx(e),r=Ux(t),i=Qx&&qx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!dh||(i?u in t:hh(t,u)))&&Gx(o,a?[u,t[u]]:t[u]);return o}};fh.exports={entries:ch(!0),values:ch(!1)}});var mh=m(()=>{"use strict";var Wx=ie(),Yx=Fo().entries;Wx({target:"Object",stat:!0},{entries:function(e){return Yx(e)}})});var gh=m((YO,bh)=>{"use strict";mh();var zx=Dr();bh.exports=zx.Object.entries});var Sh=m((zO,vh)=>{"use strict";var Kx=gh();vh.exports=Kx});var Ur=m((KO,yh)=>{"use strict";var Jx=Sh();yh.exports=Jx});var nr=m((JO,Th)=>{"use strict";Th.exports={}});var xh=m((XO,Eh)=>{"use strict";var Xx=te(),Zx=Z(),Ih=Xx.WeakMap;Eh.exports=Zx(Ih)&&/native code/.test(String(Ih))});var jo=m((ZO,Ah)=>{"use strict";var eP=xh(),wh=te(),tP=Me(),rP=_r(),qo=Ke(),Uo=wi(),iP=Ts(),aP=Es(),Ph="Object already initialized",Ho=wh.TypeError,sP=wh.WeakMap,xs,Li,Ps,nP=function(a){return Ps(a)?Li(a):xs(a,{})},oP=function(a){return function(e){var t;if(!tP(e)||(t=Li(e)).type!==a)throw new Ho("Incompatible receiver, "+a+" required");return t}};eP||Uo.state?(Xe=Uo.state||(Uo.state=new sP),Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,xs=function(a,e){if(Xe.has(a))throw new Ho(Ph);return e.facade=a,Xe.set(a,e),e},Li=function(a){return Xe.get(a)||{}},Ps=function(a){return Xe.has(a)}):(or=iP("state"),aP[or]=!0,xs=function(a,e){if(qo(a,or))throw new Ho(Ph);return e.facade=a,rP(a,or,e),e},Li=function(a){return qo(a,or)?a[or]:{}},Ps=function(a){return qo(a,or)});var Xe,or;Ah.exports={set:xs,get:Li,has:Ps,enforce:nP,getterFor:oP}});var Wo=m((eB,Rh)=>{"use strict";var Go=$e(),uP=Ke(),kh=Function.prototype,lP=Go&&Object.getOwnPropertyDescriptor,Qo=uP(kh,"name"),cP=Qo&&function(){}.name==="something",dP=Qo&&(!Go||Go&&lP(kh,"name").configurable);Rh.exports={EXISTS:Qo,PROPER:cP,CONFIGURABLE:dP}});var Lh=m($h=>{"use strict";var pP=$e(),hP=Ao(),fP=sr(),mP=st(),bP=ir(),gP=No();$h.f=pP&&!hP?Object.defineProperties:function(e,t){mP(e);for(var r=bP(t),i=gP(t),s=i.length,n=0,o;s>n;)fP.f(e,o=i[n++],r[o]);return e}});var Yo=m((rB,Mh)=>{"use strict";var vP=dt();Mh.exports=vP("document","documentElement")});var Xo=m((iB,Nh)=>{"use strict";var SP=st(),yP=Lh(),Ch=_o(),TP=Es(),IP=Yo(),EP=gs(),xP=Ts(),Dh=">",Oh="<",Ko="prototype",Jo="script",Vh=xP("IE_PROTO"),zo=function(){},_h=function(a){return Oh+Jo+Dh+a+Oh+"/"+Jo+Dh},Bh=function(a){a.write(_h("")),a.close();var e=a.parentWindow.Object;return a=null,e},PP=function(){var a=EP("iframe"),e="java"+Jo+":",t;return a.style.display="none",IP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(_h("document.F=Object")),t.close(),t.F},ws,As=function(){try{ws=new ActiveXObject("htmlfile")}catch(e){}As=typeof document!="undefined"?document.domain&&ws?Bh(ws):PP():Bh(ws);for(var a=Ch.length;a--;)delete As[Ko][Ch[a]];return As()};TP[Vh]=!0;Nh.exports=Object.create||function(e,t){var r;return e!==null?(zo[Ko]=SP(e),r=new zo,zo[Ko]=null,r[Vh]=e):r=As(),t===void 0?r:yP.f(r,t)}});var Hr=m((aB,Fh)=>{"use strict";var wP=_r();Fh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:wP(a,e,t),a}});var ru=m((sB,Hh)=>{"use strict";var AP=pe(),kP=Z(),RP=Me(),$P=Xo(),qh=Is(),LP=Hr(),MP=he(),CP=ze(),tu=MP("iterator"),Uh=!1,pt,Zo,eu;[].keys&&(eu=[].keys(),"next"in eu?(Zo=qh(qh(eu)),Zo!==Object.prototype&&(pt=Zo)):Uh=!0);var DP=!RP(pt)||AP(function(){var a={};return pt[tu].call(a)!==a});DP?pt={}:CP&&(pt=$P(pt));kP(pt[tu])||LP(pt,tu,function(){return this});Hh.exports={IteratorPrototype:pt,BUGGY_SAFARI_ITERATORS:Uh}});var ks=m((nB,Gh)=>{"use strict";var OP=he(),BP=OP("toStringTag"),jh={};jh[BP]="z";Gh.exports=String(jh)==="[object z]"});var Mi=m((oB,Qh)=>{"use strict";var VP=ks(),_P=Z(),Rs=rr(),NP=he(),FP=NP("toStringTag"),qP=Object,UP=Rs(function(){return arguments}())==="Arguments",HP=function(a,e){try{return a[e]}catch(t){}};Qh.exports=VP?Rs:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=HP(e=qP(a),FP))=="string"?t:UP?Rs(e):(r=Rs(e))==="Object"&&_P(e.callee)?"Arguments":r}});var Yh=m((uB,Wh)=>{"use strict";var jP=ks(),GP=Mi();Wh.exports=jP?{}.toString:function(){return"[object "+GP(this)+"]"}});var Ci=m((lB,Kh)=>{"use strict";var QP=ks(),WP=sr().f,YP=_r(),zP=Ke(),KP=Yh(),JP=he(),zh=JP("toStringTag");Kh.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(zP(i,zh)||WP(i,zh,{configurable:!0,value:e}),r&&!QP&&YP(i,"toString",KP))}});var Xh=m((cB,Jh)=>{"use strict";var XP=ru().IteratorPrototype,ZP=Xo(),ew=Ii(),tw=Ci(),rw=nr(),iw=function(){return this};Jh.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=ZP(XP,{next:ew(+!r,t)}),tw(a,i,!1,!0),rw[i]=iw,a}});var ef=m((dB,Zh)=>{"use strict";var aw=ne(),sw=at();Zh.exports=function(a,e,t){try{return aw(sw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var rf=m((pB,tf)=>{"use strict";var nw=Me();tf.exports=function(a){return nw(a)||a===null}});var sf=m((hB,af)=>{"use strict";var ow=rf(),uw=String,lw=TypeError;af.exports=function(a){if(ow(a))return a;throw new lw("Can't set "+uw(a)+" as a prototype")}});var iu=m((fB,nf)=>{"use strict";var cw=ef(),dw=Me(),pw=Mt(),hw=sf();nf.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=cw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return pw(i),hw(s),dw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var gf=m((mB,bf)=>{"use strict";var fw=ie(),mw=Le(),$s=ze(),ff=Wo(),bw=Z(),gw=Xh(),of=Is(),uf=iu(),vw=Ci(),Sw=_r(),au=Hr(),yw=he(),lf=nr(),mf=ru(),Tw=ff.PROPER,Iw=ff.CONFIGURABLE,cf=mf.IteratorPrototype,Ls=mf.BUGGY_SAFARI_ITERATORS,Di=yw("iterator"),df="keys",Oi="values",pf="entries",hf=function(){return this};bf.exports=function(a,e,t,r,i,s,n){gw(t,e,r);var o=function(S){if(S===i&&p)return p;if(!Ls&&S&&S in c)return c[S];switch(S){case df:return function(){return new t(this,S)};case Oi:return function(){return new t(this,S)};case pf:return function(){return new t(this,S)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Di]||c["@@iterator"]||i&&c[i],p=!Ls&&d||o(i),h=e==="Array"&&c.entries||d,f,b,g;if(h&&(f=of(h.call(new a)),f!==Object.prototype&&f.next&&(!$s&&of(f)!==cf&&(uf?uf(f,cf):bw(f[Di])||au(f,Di,hf)),vw(f,u,!0,!0),$s&&(lf[u]=hf))),Tw&&i===Oi&&d&&d.name!==Oi&&(!$s&&Iw?Sw(c,"name",Oi):(l=!0,p=function(){return mw(d,this)})),i)if(b={values:o(Oi),keys:s?p:o(df),entries:o(pf)},n)for(g in b)(Ls||l||!(g in c))&&au(c,g,b[g]);else fw({target:e,proto:!0,forced:Ls||l},b);return(!$s||n)&&c[Di]!==p&&au(c,Di,p,{name:i}),lf[e]=p,b}});var Sf=m((bB,vf)=>{"use strict";vf.exports=function(a,e){return{value:a,done:e}}});var nu=m((gB,xf)=>{"use strict";var Ew=ir(),su=$i(),yf=nr(),If=jo(),xw=sr().f,Pw=gf(),Ms=Sf(),ww=ze(),Aw=$e(),Ef="Array Iterator",kw=If.set,Rw=If.getterFor(Ef);xf.exports=Pw(Array,"Array",function(a,e){kw(this,{type:Ef,target:Ew(a),index:0,kind:e})},function(){var a=Rw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ms(void 0,!0);switch(a.kind){case"keys":return Ms(t,!1);case"values":return Ms(e[t],!1)}return Ms([t,e[t]],!1)},"values");var Tf=yf.Arguments=yf.Array;su("keys");su("values");su("entries");if(!ww&&Aw&&Tf.name!=="values")try{xw(Tf,"name",{value:"values"})}catch(a){}});var wf=m((vB,Pf)=>{"use strict";var $w=he(),Lw=nr(),Mw=$w("iterator"),Cw=Array.prototype;Pf.exports=function(a){return a!==void 0&&(Lw.Array===a||Cw[Mw]===a)}});var ou=m((SB,kf)=>{"use strict";var Dw=Mi(),Af=Pi(),Ow=Cr(),Bw=nr(),Vw=he(),_w=Vw("iterator");kf.exports=function(a){if(!Ow(a))return Af(a,_w)||Af(a,"@@iterator")||Bw[Dw(a)]}});var $f=m((yB,Rf)=>{"use strict";var Nw=Le(),Fw=at(),qw=st(),Uw=xi(),Hw=ou(),jw=TypeError;Rf.exports=function(a,e){var t=arguments.length<2?Hw(a):e;if(Fw(t))return qw(Nw(t,a));throw new jw(Uw(a)+" is not iterable")}});var Cf=m((TB,Mf)=>{"use strict";var Gw=Le(),Lf=st(),Qw=Pi();Mf.exports=function(a,e,t){var r,i;Lf(a);try{if(r=Qw(a,"return"),!r){if(e==="throw")throw t;return t}r=Gw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return Lf(r),t}});var Ds=m((IB,Vf)=>{"use strict";var Ww=Vr(),Yw=Le(),zw=st(),Kw=xi(),Jw=wf(),Xw=qr(),Df=Ei(),Zw=$f(),eA=ou(),Of=Cf(),tA=TypeError,Cs=function(a,e){this.stopped=a,this.result=e},Bf=Cs.prototype;Vf.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Ww(e,r),l,c,d,p,h,f,b,g=function(v){return l&&Of(l,"normal",v),new Cs(!0,v)},S=function(v){return i?(zw(v),o?u(v[0],v[1],g):u(v[0],v[1])):o?u(v,g):u(v)};if(s)l=a.iterator;else if(n)l=a;else{if(c=eA(a),!c)throw new tA(Kw(a)+" is not iterable");if(Jw(c)){for(d=0,p=Xw(a);p>d;d++)if(h=S(a[d]),h&&Df(Bf,h))return h;return new Cs(!1)}l=Zw(a,c)}for(f=s?a.next:l.next;!(b=Yw(f,l)).done;){try{h=S(b.value)}catch(v){Of(l,"throw",v)}if(typeof h=="object"&&h&&Df(Bf,h))return h}return new Cs(!1)}});var Nf=m((EB,_f)=>{"use strict";var rA=$e(),iA=sr(),aA=Ii();_f.exports=function(a,e,t){rA?iA.f(a,e,aA(0,t)):a[e]=t}});var Ff=m(()=>{"use strict";var sA=ie(),nA=Ds(),oA=Nf();sA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return nA(e,function(r,i){oA(t,r,i)},{AS_ENTRIES:!0}),t}})});var Uf=m((wB,qf)=>{"use strict";nu();Ff();var uA=Dr();qf.exports=uA.Object.fromEntries});var jf=m((AB,Hf)=>{"use strict";Hf.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 Qf=m(()=>{"use strict";nu();var lA=jf(),cA=te(),dA=Ci(),Gf=nr();for(Os in lA)dA(cA[Os],Os),Gf[Os]=Gf.Array;var Os});var Yf=m(($B,Wf)=>{"use strict";var pA=Uf();Qf();Wf.exports=pA});var uu=m((LB,zf)=>{"use strict";var hA=Yf();zf.exports=hA});var Kf=m(()=>{"use strict"});var lu=m((DB,Jf)=>{"use strict";var Bi=te(),fA=ar(),mA=rr(),Bs=function(a){return fA.slice(0,a.length)===a};Jf.exports=function(){return Bs("Bun/")?"BUN":Bs("Cloudflare-Workers")?"CLOUDFLARE":Bs("Deno/")?"DENO":Bs("Node.js/")?"NODE":Bi.Bun&&typeof Bun.version=="string"?"BUN":Bi.Deno&&typeof Deno.version=="object"?"DENO":mA(Bi.process)==="process"?"NODE":Bi.window&&Bi.document?"BROWSER":"REST"}()});var Vs=m((OB,Xf)=>{"use strict";var bA=lu();Xf.exports=bA==="NODE"});var em=m((BB,Zf)=>{"use strict";var gA=sr();Zf.exports=function(a,e,t){return gA.f(a,e,t)}});var im=m((VB,rm)=>{"use strict";var vA=dt(),SA=em(),yA=he(),TA=$e(),tm=yA("species");rm.exports=function(a){var e=vA(a);TA&&e&&!e[tm]&&SA(e,tm,{configurable:!0,get:function(){return this}})}});var sm=m((_B,am)=>{"use strict";var IA=Ei(),EA=TypeError;am.exports=function(a,e){if(IA(e,a))return a;throw new EA("Incorrect invocation")}});var du=m((NB,nm)=>{"use strict";var xA=ne(),PA=Z(),cu=wi(),wA=xA(Function.toString);PA(cu.inspectSource)||(cu.inspectSource=function(a){return wA(a)});nm.exports=cu.inspectSource});var hu=m((FB,dm)=>{"use strict";var AA=ne(),kA=pe(),om=Z(),RA=Mi(),$A=dt(),LA=du(),um=function(){},lm=$A("Reflect","construct"),pu=/^\s*(?:class|function)\b/,MA=AA(pu.exec),CA=!pu.test(um),Vi=function(e){if(!om(e))return!1;try{return lm(um,[],e),!0}catch(t){return!1}},cm=function(e){if(!om(e))return!1;switch(RA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return CA||!!MA(pu,LA(e))}catch(t){return!0}};cm.sham=!0;dm.exports=!lm||kA(function(){var a;return Vi(Vi.call)||!Vi(Object)||!Vi(function(){a=!0})||a})?cm:Vi});var hm=m((qB,pm)=>{"use strict";var DA=hu(),OA=xi(),BA=TypeError;pm.exports=function(a){if(DA(a))return a;throw new BA(OA(a)+" is not a constructor")}});var fu=m((UB,mm)=>{"use strict";var fm=st(),VA=hm(),_A=Cr(),NA=he(),FA=NA("species");mm.exports=function(a,e){var t=fm(a).constructor,r;return t===void 0||_A(r=fm(t)[FA])?e:VA(r)}});var gm=m((HB,bm)=>{"use strict";var qA=ne();bm.exports=qA([].slice)});var Sm=m((jB,vm)=>{"use strict";var UA=TypeError;vm.exports=function(a,e){if(a<e)throw new UA("Not enough arguments");return a}});var mu=m((GB,ym)=>{"use strict";var HA=ar();ym.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(HA)});var xu=m((QB,Rm)=>{"use strict";var Ce=te(),jA=io(),GA=Vr(),Tm=Z(),QA=Ke(),km=pe(),Im=Yo(),WA=gm(),Em=gs(),YA=Sm(),zA=mu(),KA=Vs(),Tu=Ce.setImmediate,Iu=Ce.clearImmediate,JA=Ce.process,bu=Ce.Dispatch,XA=Ce.Function,xm=Ce.MessageChannel,ZA=Ce.String,gu=0,_i={},Pm="onreadystatechange",Ni,ur,vu,Su;km(function(){Ni=Ce.location});var Eu=function(a){if(QA(_i,a)){var e=_i[a];delete _i[a],e()}},yu=function(a){return function(){Eu(a)}},wm=function(a){Eu(a.data)},Am=function(a){Ce.postMessage(ZA(a),Ni.protocol+"//"+Ni.host)};(!Tu||!Iu)&&(Tu=function(e){YA(arguments.length,1);var t=Tm(e)?e:XA(e),r=WA(arguments,1);return _i[++gu]=function(){jA(t,void 0,r)},ur(gu),gu},Iu=function(e){delete _i[e]},KA?ur=function(a){JA.nextTick(yu(a))}:bu&&bu.now?ur=function(a){bu.now(yu(a))}:xm&&!zA?(vu=new xm,Su=vu.port2,vu.port1.onmessage=wm,ur=GA(Su.postMessage,Su)):Ce.addEventListener&&Tm(Ce.postMessage)&&!Ce.importScripts&&Ni&&Ni.protocol!=="file:"&&!km(Am)?(ur=Am,Ce.addEventListener("message",wm,!1)):Pm in Em("script")?ur=function(a){Im.appendChild(Em("script"))[Pm]=function(){Im.removeChild(this),Eu(a)}}:ur=function(a){setTimeout(yu(a),0)});Rm.exports={set:Tu,clear:Iu}});var Mm=m((WB,Lm)=>{"use strict";var $m=te(),ek=$e(),tk=Object.getOwnPropertyDescriptor;Lm.exports=function(a){if(!ek)return $m[a];var e=tk($m,a);return e&&e.value}});var Pu=m((YB,Dm)=>{"use strict";var Cm=function(){this.head=null,this.tail=null};Cm.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}}};Dm.exports=Cm});var Bm=m((zB,Om)=>{"use strict";var rk=ar();Om.exports=/ipad|iphone|ipod/i.test(rk)&&typeof Pebble!="undefined"});var _m=m((KB,Vm)=>{"use strict";var ik=ar();Vm.exports=/web0s(?!.*chrome)/i.test(ik)});var Gm=m((JB,jm)=>{"use strict";var Gr=te(),ak=Mm(),Nm=Vr(),wu=xu().set,sk=Pu(),nk=mu(),ok=Bm(),uk=_m(),Au=Vs(),Fm=Gr.MutationObserver||Gr.WebKitMutationObserver,qm=Gr.document,Um=Gr.process,_s=Gr.Promise,$u=ak("queueMicrotask"),jr,ku,Ru,Ns,Hm;$u||(Fi=new sk,qi=function(){var a,e;for(Au&&(a=Um.domain)&&a.exit();e=Fi.get();)try{e()}catch(t){throw Fi.head&&jr(),t}a&&a.enter()},!nk&&!Au&&!uk&&Fm&&qm?(ku=!0,Ru=qm.createTextNode(""),new Fm(qi).observe(Ru,{characterData:!0}),jr=function(){Ru.data=ku=!ku}):!ok&&_s&&_s.resolve?(Ns=_s.resolve(void 0),Ns.constructor=_s,Hm=Nm(Ns.then,Ns),jr=function(){Hm(qi)}):Au?jr=function(){Um.nextTick(qi)}:(wu=Nm(wu,Gr),jr=function(){wu(qi)}),$u=function(a){Fi.head||jr(),Fi.add(a)});var Fi,qi;jm.exports=$u});var Wm=m((XB,Qm)=>{"use strict";Qm.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Fs=m((ZB,Ym)=>{"use strict";Ym.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var lr=m((eV,zm)=>{"use strict";var lk=te();zm.exports=lk.Promise});var Qr=m((tV,Zm)=>{"use strict";var ck=te(),Ui=lr(),dk=Z(),pk=wo(),hk=du(),fk=he(),Km=lu(),mk=ze(),Lu=ho(),Jm=Ui&&Ui.prototype,bk=fk("species"),Mu=!1,Xm=dk(ck.PromiseRejectionEvent),gk=pk("Promise",function(){var a=hk(Ui),e=a!==String(Ui);if(!e&&Lu===66||mk&&!(Jm.catch&&Jm.finally))return!0;if(!Lu||Lu<51||!/native code/.test(a)){var t=new Ui(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[bk]=r,Mu=t.then(function(){})instanceof r,!Mu)return!0}return!e&&(Km==="BROWSER"||Km==="DENO")&&!Xm});Zm.exports={CONSTRUCTOR:gk,REJECTION_EVENT:Xm,SUBCLASSING:Mu}});var Wr=m((rV,tb)=>{"use strict";var eb=at(),vk=TypeError,Sk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new vk("Bad Promise constructor");e=r,t=i}),this.resolve=eb(e),this.reject=eb(t)};tb.exports.f=function(a){return new Sk(a)}});var yb=m(()=>{"use strict";var yk=ie(),Tk=ze(),js=Vs(),Dt=te(),Jr=Le(),rb=Hr(),ib=iu(),Ik=Ci(),Ek=im(),xk=at(),Hs=Z(),Pk=Me(),wk=sm(),Ak=fu(),ub=xu().set,Vu=Gm(),kk=Wm(),Rk=Fs(),$k=Pu(),lb=jo(),Gs=lr(),_u=Qr(),cb=Wr(),Qs="Promise",db=_u.CONSTRUCTOR,Lk=_u.REJECTION_EVENT,Mk=_u.SUBCLASSING,Cu=lb.getterFor(Qs),Ck=lb.set,Yr=Gs&&Gs.prototype,cr=Gs,qs=Yr,pb=Dt.TypeError,Du=Dt.document,Nu=Dt.process,Ou=cb.f,Dk=Ou,Ok=!!(Du&&Du.createEvent&&Dt.dispatchEvent),hb="unhandledrejection",Bk="rejectionhandled",ab=0,fb=1,Vk=2,Fu=1,mb=2,Us,sb,_k,nb,bb=function(a){var e;return Pk(a)&&Hs(e=a.then)?e:!1},gb=function(a,e){var t=e.value,r=e.state===fb,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===mb&&Fk(e),e.rejection=Fu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new pb("Promise-chain cycle")):(l=bb(u))?Jr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},vb=function(a,e){a.notified||(a.notified=!0,Vu(function(){for(var t=a.reactions,r;r=t.get();)gb(r,a);a.notified=!1,e&&!a.rejection&&Nk(a)}))},Sb=function(a,e,t){var r,i;Ok?(r=Du.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Dt.dispatchEvent(r)):r={promise:e,reason:t},!Lk&&(i=Dt["on"+a])?i(r):a===hb&&kk("Unhandled promise rejection",t)},Nk=function(a){Jr(ub,Dt,function(){var e=a.facade,t=a.value,r=ob(a),i;if(r&&(i=Rk(function(){js?Nu.emit("unhandledRejection",t,e):Sb(hb,e,t)}),a.rejection=js||ob(a)?mb:Fu,i.error))throw i.value})},ob=function(a){return a.rejection!==Fu&&!a.parent},Fk=function(a){Jr(ub,Dt,function(){var e=a.facade;js?Nu.emit("rejectionHandled",e):Sb(Bk,e,a.value)})},zr=function(a,e,t){return function(r){a(e,r,t)}},Kr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Vk,vb(a,!0))},Bu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new pb("Promise can't be resolved itself");var r=bb(e);r?Vu(function(){var i={done:!1};try{Jr(r,e,zr(Bu,i,a),zr(Kr,i,a))}catch(s){Kr(i,s,a)}}):(a.value=e,a.state=fb,vb(a,!1))}catch(i){Kr({done:!1},i,a)}}};if(db&&(cr=function(e){wk(this,qs),xk(e),Jr(Us,this);var t=Cu(this);try{e(zr(Bu,t),zr(Kr,t))}catch(r){Kr(t,r)}},qs=cr.prototype,Us=function(e){Ck(this,{type:Qs,done:!1,notified:!1,parent:!1,reactions:new $k,rejection:!1,state:ab,value:void 0})},Us.prototype=rb(qs,"then",function(e,t){var r=Cu(this),i=Ou(Ak(this,cr));return r.parent=!0,i.ok=Hs(e)?e:!0,i.fail=Hs(t)&&t,i.domain=js?Nu.domain:void 0,r.state===ab?r.reactions.add(i):Vu(function(){gb(i,r)}),i.promise}),sb=function(){var a=new Us,e=Cu(a);this.promise=a,this.resolve=zr(Bu,e),this.reject=zr(Kr,e)},cb.f=Ou=function(a){return a===cr||a===_k?new sb(a):Dk(a)},!Tk&&Hs(Gs)&&Yr!==Object.prototype)){nb=Yr.then,Mk||rb(Yr,"then",function(e,t){var r=this;return new cr(function(i,s){Jr(nb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Yr.constructor}catch(a){}ib&&ib(Yr,qs)}yk({global:!0,constructor:!0,wrap:!0,forced:db},{Promise:cr});Ik(cr,Qs,!1,!0);Ek(Qs)});var Pb=m((sV,xb)=>{"use strict";var qk=he(),Ib=qk("iterator"),Eb=!1;try{Tb=0,qu={next:function(){return{done:!!Tb++}},return:function(){Eb=!0}},qu[Ib]=function(){return this},Array.from(qu,function(){throw 2})}catch(a){}var Tb,qu;xb.exports=function(a,e){try{if(!e&&!Eb)return!1}catch(i){return!1}var t=!1;try{var r={};r[Ib]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Uu=m((nV,wb)=>{"use strict";var Uk=lr(),Hk=Pb(),jk=Qr().CONSTRUCTOR;wb.exports=jk||!Hk(function(a){Uk.all(a).then(void 0,function(){})})});var Ab=m(()=>{"use strict";var Gk=ie(),Qk=Le(),Wk=at(),Yk=Wr(),zk=Fs(),Kk=Ds(),Jk=Uu();Gk({target:"Promise",stat:!0,forced:Jk},{all:function(e){var t=this,r=Yk.f(t),i=r.resolve,s=r.reject,n=zk(function(){var o=Wk(t.resolve),u=[],l=0,c=1;Kk(e,function(d){var p=l++,h=!1;c++,Qk(o,t,d).then(function(f){h||(h=!0,u[p]=f,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Rb=m(()=>{"use strict";var Xk=ie(),Zk=ze(),eR=Qr().CONSTRUCTOR,ju=lr(),tR=dt(),rR=Z(),iR=Hr(),kb=ju&&ju.prototype;Xk({target:"Promise",proto:!0,forced:eR,real:!0},{catch:function(a){return this.then(void 0,a)}});!Zk&&rR(ju)&&(Hu=tR("Promise").prototype.catch,kb.catch!==Hu&&iR(kb,"catch",Hu,{unsafe:!0}));var Hu});var $b=m(()=>{"use strict";var aR=ie(),sR=Le(),nR=at(),oR=Wr(),uR=Fs(),lR=Ds(),cR=Uu();aR({target:"Promise",stat:!0,forced:cR},{race:function(e){var t=this,r=oR.f(t),i=r.reject,s=uR(function(){var n=nR(t.resolve);lR(e,function(o){sR(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Lb=m(()=>{"use strict";var dR=ie(),pR=Wr(),hR=Qr().CONSTRUCTOR;dR({target:"Promise",stat:!0,forced:hR},{reject:function(e){var t=pR.f(this),r=t.reject;return r(e),t.promise}})});var Gu=m((mV,Mb)=>{"use strict";var fR=st(),mR=Me(),bR=Wr();Mb.exports=function(a,e){if(fR(a),mR(e)&&e.constructor===a)return e;var t=bR.f(a),r=t.resolve;return r(e),t.promise}});var Ob=m(()=>{"use strict";var gR=ie(),vR=dt(),Cb=ze(),SR=lr(),Db=Qr().CONSTRUCTOR,yR=Gu(),TR=vR("Promise"),IR=Cb&&!Db;gR({target:"Promise",stat:!0,forced:Cb||Db},{resolve:function(e){return yR(IR&&this===TR?SR:this,e)}})});var Bb=m(()=>{"use strict";yb();Ab();Rb();$b();Lb();Ob()});var Fb=m(()=>{"use strict";var ER=ie(),xR=ze(),Ws=lr(),PR=pe(),_b=dt(),Nb=Z(),wR=fu(),Vb=Gu(),AR=Hr(),Wu=Ws&&Ws.prototype,kR=!!Ws&&PR(function(){Wu.finally.call({then:function(){}},function(){})});ER({target:"Promise",proto:!0,real:!0,forced:kR},{finally:function(a){var e=wR(this,_b("Promise")),t=Nb(a);return this.then(t?function(r){return Vb(e,a()).then(function(){return r})}:a,t?function(r){return Vb(e,a()).then(function(){throw r})}:a)}});!xR&&Nb(Ws)&&(Qu=_b("Promise").prototype.finally,Wu.finally!==Qu&&AR(Wu,"finally",Qu,{unsafe:!0}));var Qu});var Ub=m((IV,qb)=>{"use strict";Kf();Bb();Fb();var RR=Ct();qb.exports=RR("Promise","finally")});var jb=m((EV,Hb)=>{"use strict";var $R=Ub();Hb.exports=$R});var Ys=m((xV,Gb)=>{"use strict";var LR=jb();Gb.exports=LR});var ag=m(()=>{"use strict";var GR=ie(),QR=Fo().values;GR({target:"Object",stat:!0},{values:function(e){return QR(e)}})});var ng=m((u_,sg)=>{"use strict";ag();var WR=Dr();sg.exports=WR.Object.values});var ug=m((l_,og)=>{"use strict";var YR=ng();og.exports=YR});var Zr=m((c_,lg)=>{"use strict";var zR=ug();lg.exports=zR});var Ig=m(()=>{"use strict";var d$=ie(),p$=Or(),h$=qr(),f$=Ri(),m$=$i();d$({target:"Array",proto:!0},{at:function(e){var t=p$(this),r=h$(t),i=f$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});m$("at")});var xg=m((__,Eg)=>{"use strict";Ig();var b$=Ct();Eg.exports=b$("Array","at")});var wg=m((N_,Pg)=>{"use strict";var g$=xg();Pg.exports=g$});var ti=m((F_,Ag)=>{"use strict";var v$=wg();Ag.exports=v$});var bl=m((mF,iv)=>{"use strict";var Z$=rr();iv.exports=Array.isArray||function(e){return Z$(e)==="Array"}});var sv=m((bF,av)=>{"use strict";var eL=TypeError,tL=9007199254740991;av.exports=function(a){if(a>tL)throw eL("Maximum allowed index exceeded");return a}});var uv=m((gF,ov)=>{"use strict";var rL=bl(),iL=qr(),aL=sv(),sL=Vr(),nv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?sL(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&rL(d)?(p=iL(d),u=nv(a,e,d,p,u,s-1)-1):(aL(u+1),a[u]=d),u++),l++;return u};ov.exports=nv});var pv=m((vF,dv)=>{"use strict";var lv=bl(),nL=hu(),oL=Me(),uL=he(),lL=uL("species"),cv=Array;dv.exports=function(a){var e;return lv(a)&&(e=a.constructor,nL(e)&&(e===cv||lv(e.prototype))?e=void 0:oL(e)&&(e=e[lL],e===null&&(e=void 0))),e===void 0?cv:e}});var fv=m((SF,hv)=>{"use strict";var cL=pv();hv.exports=function(a,e){return new(cL(a))(e===0?0:e)}});var mv=m(()=>{"use strict";var dL=ie(),pL=uv(),hL=at(),fL=Or(),mL=qr(),bL=fv();dL({target:"Array",proto:!0},{flatMap:function(e){var t=fL(this),r=mL(t),i;return hL(e),i=bL(t,0),i.length=pL(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var bv=m(()=>{"use strict";var gL=$i();gL("flatMap")});var vv=m((xF,gv)=>{"use strict";mv();bv();var vL=Ct();gv.exports=vL("Array","flatMap")});var yv=m((PF,Sv)=>{"use strict";var SL=vv();Sv.exports=SL});var gl=m((wF,Tv)=>{"use strict";var yL=yv();Tv.exports=yL});var ia=m((VF,qv)=>{"use strict";var kL=Mi(),RL=String;qv.exports=function(a){if(kL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return RL(a)}});var Sl=m((_F,Uv)=>{"use strict";Uv.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 Gv=m((NF,jv)=>{"use strict";var $L=ne(),LL=Mt(),ML=ia(),Tl=Sl(),Hv=$L("".replace),CL=RegExp("^["+Tl+"]+"),DL=RegExp("(^|[^"+Tl+"])["+Tl+"]+$"),yl=function(a){return function(e){var t=ML(LL(e));return a&1&&(t=Hv(t,CL,"")),a&2&&(t=Hv(t,DL,"$1")),t}};jv.exports={start:yl(1),end:yl(2),trim:yl(3)}});var zv=m((FF,Yv)=>{"use strict";var OL=Wo().PROPER,BL=pe(),Qv=Sl(),Wv="\u200B\x85\u180E";Yv.exports=function(a){return BL(function(){return!!Qv[a]()||Wv[a]()!==Wv||OL&&Qv[a].name!==a})}});var Il=m((qF,Kv)=>{"use strict";var VL=Gv().start,_L=zv();Kv.exports=_L("trimStart")?function(){return VL(this)}:"".trimStart});var Xv=m(()=>{"use strict";var NL=ie(),Jv=Il();NL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==Jv},{trimLeft:Jv})});var eS=m(()=>{"use strict";Xv();var FL=ie(),Zv=Il();FL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==Zv},{trimStart:Zv})});var rS=m((QF,tS)=>{"use strict";eS();var qL=Ct();tS.exports=qL("String","trimLeft")});var aS=m((WF,iS)=>{"use strict";var UL=rS();iS.exports=UL});var nS=m((YF,sS)=>{"use strict";var HL=aS();sS.exports=HL});var IS=m(()=>{"use strict"});var ES=m(()=>{"use strict"});var PS=m((T1,xS)=>{"use strict";var pM=Me(),hM=rr(),fM=he(),mM=fM("match");xS.exports=function(a){var e;return pM(a)&&((e=a[mM])!==void 0?!!e:hM(a)==="RegExp")}});var AS=m((I1,wS)=>{"use strict";var bM=st();wS.exports=function(){var a=bM(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 $S=m((E1,RS)=>{"use strict";var gM=Le(),vM=Ke(),SM=Ei(),yM=AS(),kS=RegExp.prototype;RS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in kS)&&!vM(a,"flags")&&SM(kS,a)?gM(yM,a):e}});var MS=m((x1,LS)=>{"use strict";var Ll=ne(),TM=Or(),IM=Math.floor,Rl=Ll("".charAt),EM=Ll("".replace),$l=Ll("".slice),xM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,PM=/\$([$&'`]|\d{1,2})/g;LS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=PM;return i!==void 0&&(i=TM(i),u=xM),EM(s,u,function(l,c){var d;switch(Rl(c,0)){case"$":return"$";case"&":return a;case"`":return $l(e,0,t);case"'":return $l(e,n);case"<":d=i[$l(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=IM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Rl(c,1):r[h-1]+Rl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var OS=m(()=>{"use strict";var wM=ie(),AM=Le(),Cl=ne(),CS=Mt(),kM=Z(),RM=Cr(),$M=PS(),oi=ia(),LM=Pi(),MM=$S(),CM=MS(),DM=he(),OM=ze(),BM=DM("replace"),VM=TypeError,Ml=Cl("".indexOf),_M=Cl("".replace),DS=Cl("".slice),NM=Math.max;wM({target:"String",proto:!0},{replaceAll:function(e,t){var r=CS(this),i,s,n,o,u,l,c,d,p,h,f=0,b="";if(!RM(e)){if(i=$M(e),i&&(s=oi(CS(MM(e))),!~Ml(s,"g")))throw new VM("`.replaceAll` does not allow non-global regexes");if(n=LM(e,BM),n)return AM(n,e,r,t);if(OM&&i)return _M(oi(r),e,t)}for(o=oi(r),u=oi(e),l=kM(t),l||(t=oi(t)),c=u.length,d=NM(1,c),p=Ml(o,u);p!==-1;)h=l?oi(t(u,p,o)):CM(u,o,p,[],void 0,t),b+=DS(o,f,p)+h,f=p+c,p=p+d>o.length?-1:Ml(o,u,p+d);return f<o.length&&(b+=DS(o,f)),b}})});var VS=m((A1,BS)=>{"use strict";IS();ES();OS();var FM=Ct();BS.exports=FM("String","replaceAll")});var NS=m((k1,_S)=>{"use strict";var qM=VS();_S.exports=qM});var qS=m((R1,FS)=>{"use strict";var UM=NS();FS.exports=UM});var HS=m(($1,US)=>{"use strict";var HM=Ri(),jM=ia(),GM=Mt(),QM=RangeError;US.exports=function(e){var t=jM(GM(this)),r="",i=HM(e);if(i<0||i===1/0)throw new QM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var YS=m((L1,WS)=>{"use strict";var QS=ne(),WM=Mo(),jS=ia(),YM=HS(),zM=Mt(),KM=QS(YM),JM=QS("".slice),XM=Math.ceil,GS=function(a){return function(e,t,r){var i=jS(zM(e)),s=WM(t),n=i.length,o=r===void 0?" ":jS(r),u,l;return s<=n||o===""?i:(u=s-n,l=KM(o,XM(u/o.length)),l.length>u&&(l=JM(l,0,u)),a?i+l:l+i)}};WS.exports={start:GS(!1),end:GS(!0)}});var KS=m((M1,zS)=>{"use strict";var ZM=ar();zS.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(ZM)});var JS=m(()=>{"use strict";var eC=ie(),tC=YS().start,rC=KS();eC({target:"String",proto:!0,forced:rC},{padStart:function(e){return tC(this,e,arguments.length>1?arguments[1]:void 0)}})});var ZS=m((O1,XS)=>{"use strict";JS();var iC=Ct();XS.exports=iC("String","padStart")});var ty=m((B1,ey)=>{"use strict";var aC=ZS();ey.exports=aC});var iy=m((V1,ry)=>{"use strict";var sC=ty();ry.exports=sC});var Zc="2.0.123-dev.428b52a4.0";var Se=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(Se||{}),Lt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(Lt||{});var fs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(fs||{}),eo=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(eo||{});var to=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(to||{});var DT=_(Je(),1);import{assertNever as Jp,assertNonNullable as vx,isNonNullable as Ss,ValueSubject as Do,Subject as Sx,Subscription as yx,merge as Tx,observableFrom as Ix,fromEvent as Wp,map as Yp,tap as zp,filterChanged as Ex,isNullable as Oo,ErrorCategory as Kp}from"@vkontakte/videoplayer-shared/es2015";var Qp=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var ys=class{constructor(e){this.connection$=new Do(void 0);this.castState$=new Do("NOT_AVAILABLE");this.errorEvent$=new Sx;this.realCastState$=new Do("NOT_AVAILABLE");this.subscription=new yx;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=Ss((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||Qp("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:Kp.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){Ss(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Oo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Oo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(Wp(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return Jp(i.sessionState)}})).add(Tx(Wp(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(zp(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),Yp(i=>i.castState)),Ix([r.getCastState()])).pipe(Ex(),Yp(xx),zp(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=Ss(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();vx(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Oo(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?Ss(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:Kp.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},xx=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return Jp(a)}};var cc=_(Je(),1),fT=_(Ur(),1),mT=_(uu(),1);var tg=_(Ys(),1);import{assertNever as Qb}from"@vkontakte/videoplayer-shared/es2015";var fe=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:Qb(t)}return a},zs=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:Qb(e)}};var P=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as MR,Subject as Ks,merge as Wb}from"@vkontakte/videoplayer-shared/es2015";var O=class{constructor(e){this.transitionStarted$=new Ks;this.transitionEnded$=new Ks;this.transitionUpdated$=new Ks;this.forceChanged$=new Ks;this.stateChangeStarted$=Wb(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=Wb(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||MR(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as CR}from"@vkontakte/videoplayer-shared/es2015";var Yb=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 CR(a)}};import{assertNever as Xr,assertNonNullable as dr,debounce as zb,ErrorCategory as Kb,fromEvent as pr,isNonNullable as Jb,map as Xb,merge as Zb,observableFrom as DR,Subject as OR,Subscription as Yu,timeout as BR,getHighestQuality as VR}from"@vkontakte/videoplayer-shared/es2015";var _R=5,NR=5,FR=500,eg=7e3,Hi=class{constructor(e){this.subscription=new Yu;this.loadMediaTimeoutSubscription=new Yu;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Xr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Xr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Xr(e)}break}default:Xr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Yb(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 Yu;this.subscription.add(e),this.subscription.add(Zb(this.videoState.stateChangeStarted$.pipe(Xb(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(Xb(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new OR;e.add(i.pipe(zb(FR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(pr(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)>_R)&&i.next(o),s=o})),e.add(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<NR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Xr(n)}}),t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=Zb(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,DR(["init"])).pipe(zb(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),P(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&P(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];dr(c);let d=VR(Object.keys(c));dr(d);let p=c[d];dr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];dr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];dr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];dr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];dr(c),r=fe(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:Kb.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Xr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return Jb(o)&&(n.metadata.title=o),Jb(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(BR(eg).subscribe(()=>s(`timeout(${eg})`)))});(0,tg.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:Kb.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var fl=_(Je(),1);import{clearVideoElement as ig}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as qR}from"@vkontakte/videoplayer-shared/es2015";var rg=a=>{try{a.pause(),a.playbackRate=0,qR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as UR,Subscription as HR}from"@vkontakte/videoplayer-shared/es2015";var zu=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Ku=window.WeakMap?new WeakMap:new zu,Ju=window.WeakMap?new WeakMap:new Map,jR=(a,e=20)=>{let t=0;return UR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},ye=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?ig(t):(t=document.createElement("video"),a.appendChild(t)),Ku.set(t,r);let i=new HR;return i.add(jR(t,e)),Ju.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Te=a=>{let e=Ju.get(a);e==null||e.unsubscribe(),Ju.delete(a);let t=Ku.get(a);Ku.delete(a),t?ig(a):rg(a)};var Zu=_(Zr(),1);import{assertNonNullable as ji,isNonNullable as ot,isNullable as XR,fromEvent as ei,merge as cg,observableFrom as dg,filterChanged as pg,map as Gi,Subject as hg,Subscription as ZR,ValueSubject as e$,ErrorCategory as t$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Xu,isNullable as KR,Subscription as JR}from"@vkontakte/videoplayer-shared/es2015";var Js=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=KR(i),l=new JR;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},nt=(a,e,t)=>Js(e,()=>a.loop,r=>{Xu(r)&&(a.loop=r)},{onError:t}),Ie=(a,e,t,r)=>Js(e,()=>({muted:a.muted,volume:a.volume}),i=>{Xu(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Ne=(a,e,t,r)=>Js(e,()=>a.playbackRate,i=>{Xu(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ot=Js;var r$=a=>["__",a.language,a.label].join("|"),i$=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},el=class a{constructor(){this.available$=new hg;this.current$=new e$(void 0);this.error$=new hg;this.subscription=new ZR;this.externalTracks=new Map;this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:t$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ot(t.internalTextTracks,()=>(0,Zu.default)(this.internalTracks),s=>{ot(s)&&this.setInternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Gi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Ot(t.externalTextTracks,()=>(0,Zu.default)(this.externalTracks),s=>{ot(s)&&this.setExternal(s)},{equal:(s,n)=>ot(s)&&ot(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Gi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Ot(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Ot(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ji(this.video);let{textTracks:e}=this.video;this.subscription.add(ei(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(cg(ei(e,"addtrack"),ei(e,"removetrack"),dg(["init"])).pipe(Gi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),pg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(cg(ei(e,"change"),dg(["init"])).pipe(Gi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Gi(r=>r&&this.htmlTextTrackToITextTrack(r).id),pg()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(ei(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(ei(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;ot(t.align)&&(i.align=t.align),ot(t.position)&&(i.position=t.position),ot(t.size)&&(i.size=t.size),ot(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){ji(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:r$(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){ji(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(XR(e)||!i$(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){ji(this.video);let t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){ji(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Fe=el;var ft=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var fg=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},tl=a=>{let e=fg(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},mg=a=>{let e=fg(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as qe,map as Bt,merge as gg,filterChanged as s$,isNonNullable as vg,Subject as n$,filter as Sg,mapTo as yg,combine as o$,once as u$,ErrorCategory as l$,ValueSubject as Tg,clientChecker as c$}from"@vkontakte/videoplayer-shared/es2015";var a$=3,bg=(a,e,t=a$)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var Ee=a=>{let e=y=>qe(a,y).pipe(yg(void 0)),r=gg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>qe(a,y))).pipe(Bt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),s$()),i=gg(qe(a,"progress"),qe(a,"timeupdate")).pipe(Bt(()=>bg(a.buffered,a.currentTime))),s=c$.isSafari?o$({play:e("play").pipe(u$()),playing:e("playing")}).pipe(yg(void 0)):e("playing"),n=qe(a,"volumechange").pipe(Bt(()=>({muted:a.muted,volume:a.volume}))),o=qe(a,"ratechange").pipe(Bt(()=>a.playbackRate)),u=qe(a,"error").pipe(Sg(()=>!!(a.error||a.played.length)),Bt(()=>{var I;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:l$.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=qe(a,"timeupdate").pipe(Bt(()=>a.currentTime)),c=new n$,d=.3,p;l.subscribe(y=>{a.loop&&vg(p)&&vg(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(Sg(()=>!a.error&&p!==a.duration)),f=qe(a,"enterpictureinpicture"),b=qe(a,"leavepictureinpicture"),g=new Tg(mg(a));f.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let S=new Tg(tl(a));return qe(a,"fullscreenchange").pipe(Bt(()=>tl(a))).subscribe(S),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:qe(a,"durationchange").pipe(Bt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:S,enterPip$:f,leavePip$:b}};import{VideoQuality as Vt}from"@vkontakte/videoplayer-shared/es2015";var _t=a=>{switch(a){case"mobile":return Vt.Q_144P;case"lowest":return Vt.Q_240P;case"low":return Vt.Q_360P;case"sd":case"medium":return Vt.Q_480P;case"hd":case"high":return Vt.Q_720P;case"fullhd":case"full":return Vt.Q_1080P;case"quadhd":case"quad":return Vt.Q_1440P;case"ultrahd":case"ultra":return Vt.Q_2160P}};var Nt=_(ti(),1),Dg=_(Je(),1),Xs=_(Ur(),1);import{isNonNullable as oe,isNullable as il,now as Og,isHigher as al,isHigherOrEqual as sl,isInvariantQuality as Lg,isLower as Mg,isLowerOrEqual as nl,videoSizeToQuality as S$,assertNotEmptyArray as Bg,assertNonNullable as y$}from"@vkontakte/videoplayer-shared/es2015";var rl=!1,mt={},kg=a=>{rl=a},Rg=()=>{mt={}},$g=a=>{a(mt)},Qi=(a,e)=>{var t;rl&&(mt.meta=(t=mt.meta)!=null?t:{},mt.meta[a]=e)},be=class{constructor(e){this.name=e}next(e){var r,i;if(!rl)return;mt.series=(r=mt.series)!=null?r:{};let t=(i=mt.series[this.name])!=null?i:[];t.push([Date.now(),e]),mt.series[this.name]=t}};var T$=new be("best_bitrate"),Vg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var ol=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Wi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Og()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},_g='Assertion "ABR Tracks is empty array" failed',Zs=(a,e,t,r)=>{var u;let i=[...e].sort(ol(1)),s=[...t].sort(ol(1)),n=s.filter(l=>oe(l.bitrate)&&oe(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,Dg.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},Cg=a=>"quality"in a,Ng=(a,e,t,r)=>{var n;let i=oe((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&oe(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Og()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=Cg(o)?"video":"audio",l=Cg(o)?o.quality:o.bitrate;return e({message:`
6
+ var YT=Object.create;var Xn=Object.defineProperty,zT=Object.defineProperties,KT=Object.getOwnPropertyDescriptor,XT=Object.getOwnPropertyDescriptors,JT=Object.getOwnPropertyNames,ps=Object.getOwnPropertySymbols,ZT=Object.getPrototypeOf,Jn=Object.prototype.hasOwnProperty,sd=Object.prototype.propertyIsEnumerable;var eI=(a,e)=>(e=Symbol[a])?e:Symbol.for("Symbol."+a);var at=Math.pow,ad=(a,e,t)=>e in a?Xn(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,E=(a,e)=>{for(var t in e||(e={}))Jn.call(e,t)&&ad(a,t,e[t]);if(ps)for(var t of ps(e))sd.call(e,t)&&ad(a,t,e[t]);return a},$=(a,e)=>zT(a,XT(e));var nd=(a,e)=>{var t={};for(var r in a)Jn.call(a,r)&&e.indexOf(r)<0&&(t[r]=a[r]);if(a!=null&&ps)for(var r of ps(a))e.indexOf(r)<0&&sd.call(a,r)&&(t[r]=a[r]);return t};var f=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var tI=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of JT(e))!Jn.call(a,i)&&i!==t&&Xn(a,i,{get:()=>e[i],enumerable:!(r=KT(e,i))||r.enumerable});return a};var _=(a,e,t)=>(t=a!=null?YT(ZT(a)):{},tI(e||!a||!a.__esModule?Xn(t,"default",{value:a,enumerable:!0}):t,a));var A=(a,e,t)=>new Promise((r,i)=>{var s=u=>{try{o(t.next(u))}catch(l){i(l)}},n=u=>{try{o(t.throw(u))}catch(l){i(l)}},o=u=>u.done?r(u.value):Promise.resolve(u.value).then(s,n);o((t=t.apply(a,e)).next())}),Zn=function(a,e){this[0]=a,this[1]=e},ae=(a,e,t)=>{var r=(n,o,u,l)=>{try{var c=t[n](o),d=(o=c.value)instanceof Zn,p=c.done;Promise.resolve(d?o[0]:o).then(h=>d?r(n==="return"?n:"next",o[1]?{done:h.done,value:h.value}:h,u,l):u({value:h,done:p})).catch(h=>r("throw",h,u,l))}catch(h){l(h)}},i=n=>s[n]=o=>new Promise((u,l)=>r(n,o,u,l)),s={};return t=t.apply(a,e),s[eI("asyncIterator")]=()=>s,i("next"),i("throw"),i("return"),s};var re=f((ro,ud)=>{"use strict";var yi=function(a){return a&&a.Math===Math&&a};ud.exports=yi(typeof globalThis=="object"&&globalThis)||yi(typeof window=="object"&&window)||yi(typeof self=="object"&&self)||yi(typeof global=="object"&&global)||yi(typeof ro=="object"&&ro)||function(){return this}()||Function("return this")()});var pe=f((L0,ld)=>{"use strict";ld.exports=function(a){try{return!!a()}catch(e){return!0}}});var Ti=f((M0,cd)=>{"use strict";var rI=pe();cd.exports=!rI(function(){var a=function(){}.bind();return typeof a!="function"||a.hasOwnProperty("prototype")})});var io=f((D0,md)=>{"use strict";var iI=Ti(),hd=Function.prototype,dd=hd.apply,pd=hd.call;md.exports=typeof Reflect=="object"&&Reflect.apply||(iI?pd.bind(dd):function(){return pd.apply(dd,arguments)})});var ne=f((C0,gd)=>{"use strict";var fd=Ti(),bd=Function.prototype,ao=bd.call,aI=fd&&bd.bind.bind(ao,ao);gd.exports=fd?aI:function(a){return function(){return ao.apply(a,arguments)}}});var rr=f((O0,Sd)=>{"use strict";var vd=ne(),sI=vd({}.toString),nI=vd("".slice);Sd.exports=function(a){return nI(sI(a),8,-1)}});var so=f((V0,yd)=>{"use strict";var oI=rr(),uI=ne();yd.exports=function(a){if(oI(a)==="Function")return uI(a)}});var Z=f((B0,Td)=>{"use strict";var no=typeof document=="object"&&document.all;Td.exports=typeof no=="undefined"&&no!==void 0?function(a){return typeof a=="function"||a===no}:function(a){return typeof a=="function"}});var Le=f((_0,Id)=>{"use strict";var lI=pe();Id.exports=!lI(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7})});var Me=f((N0,Ed)=>{"use strict";var cI=Ti(),ms=Function.prototype.call;Ed.exports=cI?ms.bind(ms):function(){return ms.apply(ms,arguments)}});var oo=f(wd=>{"use strict";var xd={}.propertyIsEnumerable,Pd=Object.getOwnPropertyDescriptor,dI=Pd&&!xd.call({1:2},1);wd.f=dI?function(e){var t=Pd(this,e);return!!t&&t.enumerable}:xd});var Ii=f((q0,Ad)=>{"use strict";Ad.exports=function(a,e){return{enumerable:!(a&1),configurable:!(a&2),writable:!(a&4),value:e}}});var Rd=f((U0,kd)=>{"use strict";var pI=ne(),hI=pe(),mI=rr(),uo=Object,fI=pI("".split);kd.exports=hI(function(){return!uo("z").propertyIsEnumerable(0)})?function(a){return mI(a)==="String"?fI(a,""):uo(a)}:uo});var Mr=f((H0,$d)=>{"use strict";$d.exports=function(a){return a==null}});var Mt=f((j0,Ld)=>{"use strict";var bI=Mr(),gI=TypeError;Ld.exports=function(a){if(bI(a))throw new gI("Can't call method on "+a);return a}});var ir=f((G0,Md)=>{"use strict";var vI=Rd(),SI=Mt();Md.exports=function(a){return vI(SI(a))}});var De=f((Q0,Dd)=>{"use strict";var yI=Z();Dd.exports=function(a){return typeof a=="object"?a!==null:yI(a)}});var Dr=f((W0,Cd)=>{"use strict";Cd.exports={}});var pt=f((Y0,Vd)=>{"use strict";var lo=Dr(),co=re(),TI=Z(),Od=function(a){return TI(a)?a:void 0};Vd.exports=function(a,e){return arguments.length<2?Od(lo[a])||Od(co[a]):lo[a]&&lo[a][e]||co[a]&&co[a][e]}});var Ei=f((z0,Bd)=>{"use strict";var II=ne();Bd.exports=II({}.isPrototypeOf)});var ar=f((K0,Fd)=>{"use strict";var EI=re(),_d=EI.navigator,Nd=_d&&_d.userAgent;Fd.exports=Nd?String(Nd):""});var ho=f((X0,Qd)=>{"use strict";var Gd=re(),po=ar(),qd=Gd.process,Ud=Gd.Deno,Hd=qd&&qd.versions||Ud&&Ud.version,jd=Hd&&Hd.v8,Ye,fs;jd&&(Ye=jd.split("."),fs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!fs&&po&&(Ye=po.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=po.match(/Chrome\/(\d+)/),Ye&&(fs=+Ye[1])));Qd.exports=fs});var mo=f((J0,Yd)=>{"use strict";var Wd=ho(),xI=pe(),PI=re(),wI=PI.String;Yd.exports=!!Object.getOwnPropertySymbols&&!xI(function(){var a=Symbol("symbol detection");return!wI(a)||!(Object(a)instanceof Symbol)||!Symbol.sham&&Wd&&Wd<41})});var fo=f((Z0,zd)=>{"use strict";var AI=mo();zd.exports=AI&&!Symbol.sham&&typeof Symbol.iterator=="symbol"});var bo=f((eO,Kd)=>{"use strict";var kI=pt(),RI=Z(),$I=Ei(),LI=fo(),MI=Object;Kd.exports=LI?function(a){return typeof a=="symbol"}:function(a){var e=kI("Symbol");return RI(e)&&$I(e.prototype,MI(a))}});var xi=f((tO,Xd)=>{"use strict";var DI=String;Xd.exports=function(a){try{return DI(a)}catch(e){return"Object"}}});var st=f((rO,Jd)=>{"use strict";var CI=Z(),OI=xi(),VI=TypeError;Jd.exports=function(a){if(CI(a))return a;throw new VI(OI(a)+" is not a function")}});var Pi=f((iO,Zd)=>{"use strict";var BI=st(),_I=Mr();Zd.exports=function(a,e){var t=a[e];return _I(t)?void 0:BI(t)}});var tp=f((aO,ep)=>{"use strict";var go=Me(),vo=Z(),So=De(),NI=TypeError;ep.exports=function(a,e){var t,r;if(e==="string"&&vo(t=a.toString)&&!So(r=go(t,a))||vo(t=a.valueOf)&&!So(r=go(t,a))||e!=="string"&&vo(t=a.toString)&&!So(r=go(t,a)))return r;throw new NI("Can't convert object to primitive value")}});var ze=f((sO,rp)=>{"use strict";rp.exports=!0});var sp=f((nO,ap)=>{"use strict";var ip=re(),FI=Object.defineProperty;ap.exports=function(a,e){try{FI(ip,a,{value:e,configurable:!0,writable:!0})}catch(t){ip[a]=e}return e}});var wi=f((oO,up)=>{"use strict";var qI=ze(),UI=re(),HI=sp(),np="__core-js_shared__",op=up.exports=UI[np]||HI(np,{});(op.versions||(op.versions=[])).push({version:"3.38.0",mode:qI?"pure":"global",copyright:"\xA9 2014-2024 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.38.0/LICENSE",source:"https://github.com/zloirock/core-js"})});var yo=f((uO,cp)=>{"use strict";var lp=wi();cp.exports=function(a,e){return lp[a]||(lp[a]=e||{})}});var Cr=f((lO,dp)=>{"use strict";var jI=Mt(),GI=Object;dp.exports=function(a){return GI(jI(a))}});var Ke=f((cO,pp)=>{"use strict";var QI=ne(),WI=Cr(),YI=QI({}.hasOwnProperty);pp.exports=Object.hasOwn||function(e,t){return YI(WI(e),t)}});var To=f((dO,hp)=>{"use strict";var zI=ne(),KI=0,XI=Math.random(),JI=zI(1 .toString);hp.exports=function(a){return"Symbol("+(a===void 0?"":a)+")_"+JI(++KI+XI,36)}});var he=f((pO,fp)=>{"use strict";var ZI=re(),eE=yo(),mp=Ke(),tE=To(),rE=mo(),iE=fo(),Or=ZI.Symbol,Io=eE("wks"),aE=iE?Or.for||Or:Or&&Or.withoutSetter||tE;fp.exports=function(a){return mp(Io,a)||(Io[a]=rE&&mp(Or,a)?Or[a]:aE("Symbol."+a)),Io[a]}});var Sp=f((hO,vp)=>{"use strict";var sE=Me(),bp=De(),gp=bo(),nE=Pi(),oE=tp(),uE=he(),lE=TypeError,cE=uE("toPrimitive");vp.exports=function(a,e){if(!bp(a)||gp(a))return a;var t=nE(a,cE),r;if(t){if(e===void 0&&(e="default"),r=sE(t,a,e),!bp(r)||gp(r))return r;throw new lE("Can't convert object to primitive value")}return e===void 0&&(e="number"),oE(a,e)}});var Eo=f((mO,yp)=>{"use strict";var dE=Sp(),pE=bo();yp.exports=function(a){var e=dE(a,"string");return pE(e)?e:e+""}});var bs=f((fO,Ip)=>{"use strict";var hE=re(),Tp=De(),xo=hE.document,mE=Tp(xo)&&Tp(xo.createElement);Ip.exports=function(a){return mE?xo.createElement(a):{}}});var Po=f((bO,Ep)=>{"use strict";var fE=Le(),bE=pe(),gE=bs();Ep.exports=!fE&&!bE(function(){return Object.defineProperty(gE("div"),"a",{get:function(){return 7}}).a!==7})});var wp=f(Pp=>{"use strict";var vE=Le(),SE=Me(),yE=oo(),TE=Ii(),IE=ir(),EE=Eo(),xE=Ke(),PE=Po(),xp=Object.getOwnPropertyDescriptor;Pp.f=vE?xp:function(e,t){if(e=IE(e),t=EE(t),PE)try{return xp(e,t)}catch(r){}if(xE(e,t))return TE(!SE(yE.f,e,t),e[t])}});var wo=f((vO,Ap)=>{"use strict";var wE=pe(),AE=Z(),kE=/#|\.prototype\./,Ai=function(a,e){var t=$E[RE(a)];return t===ME?!0:t===LE?!1:AE(e)?wE(e):!!e},RE=Ai.normalize=function(a){return String(a).replace(kE,".").toLowerCase()},$E=Ai.data={},LE=Ai.NATIVE="N",ME=Ai.POLYFILL="P";Ap.exports=Ai});var Vr=f((SO,Rp)=>{"use strict";var kp=so(),DE=st(),CE=Ti(),OE=kp(kp.bind);Rp.exports=function(a,e){return DE(a),e===void 0?a:CE?OE(a,e):function(){return a.apply(e,arguments)}}});var Ao=f((yO,$p)=>{"use strict";var VE=Le(),BE=pe();$p.exports=VE&&BE(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42})});var nt=f((TO,Lp)=>{"use strict";var _E=De(),NE=String,FE=TypeError;Lp.exports=function(a){if(_E(a))return a;throw new FE(NE(a)+" is not an object")}});var sr=f(Dp=>{"use strict";var qE=Le(),UE=Po(),HE=Ao(),gs=nt(),Mp=Eo(),jE=TypeError,ko=Object.defineProperty,GE=Object.getOwnPropertyDescriptor,Ro="enumerable",$o="configurable",Lo="writable";Dp.f=qE?HE?function(e,t,r){if(gs(e),t=Mp(t),gs(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Lo in r&&!r[Lo]){var i=GE(e,t);i&&i[Lo]&&(e[t]=r.value,r={configurable:$o in r?r[$o]:i[$o],enumerable:Ro in r?r[Ro]:i[Ro],writable:!1})}return ko(e,t,r)}:ko:function(e,t,r){if(gs(e),t=Mp(t),gs(r),UE)try{return ko(e,t,r)}catch(i){}if("get"in r||"set"in r)throw new jE("Accessors not supported");return"value"in r&&(e[t]=r.value),e}});var Br=f((EO,Cp)=>{"use strict";var QE=Le(),WE=sr(),YE=Ii();Cp.exports=QE?function(a,e,t){return WE.f(a,e,YE(1,t))}:function(a,e,t){return a[e]=t,a}});var ie=f((xO,Vp)=>{"use strict";var ki=re(),zE=io(),KE=so(),XE=Z(),JE=wp().f,ZE=wo(),_r=Dr(),ex=Vr(),Nr=Br(),Op=Ke();wi();var tx=function(a){var e=function(t,r,i){if(this instanceof e){switch(arguments.length){case 0:return new a;case 1:return new a(t);case 2:return new a(t,r)}return new a(t,r,i)}return zE(a,this,arguments)};return e.prototype=a.prototype,e};Vp.exports=function(a,e){var t=a.target,r=a.global,i=a.stat,s=a.proto,n=r?ki:i?ki[t]:ki[t]&&ki[t].prototype,o=r?_r:_r[t]||Nr(_r,t,{})[t],u=o.prototype,l,c,d,p,h,m,b,g,v;for(p in e)l=ZE(r?p:t+(i?".":"#")+p,a.forced),c=!l&&n&&Op(n,p),m=o[p],c&&(a.dontCallGetSet?(v=JE(n,p),b=v&&v.value):b=n[p]),h=c&&b?b:e[p],!(!l&&!s&&typeof m==typeof h)&&(a.bind&&c?g=ex(h,ki):a.wrap&&c?g=tx(h):s&&XE(h)?g=KE(h):g=h,(a.sham||h&&h.sham||m&&m.sham)&&Nr(g,"sham",!0),Nr(o,p,g),s&&(d=t+"Prototype",Op(_r,d)||Nr(_r,d,{}),Nr(_r[d],p,h),a.real&&u&&(l||!u[p])&&Nr(u,p,h)))}});var _p=f((PO,Bp)=>{"use strict";var rx=Math.ceil,ix=Math.floor;Bp.exports=Math.trunc||function(e){var t=+e;return(t>0?ix:rx)(t)}});var Ri=f((wO,Np)=>{"use strict";var ax=_p();Np.exports=function(a){var e=+a;return e!==e||e===0?0:ax(e)}});var qp=f((AO,Fp)=>{"use strict";var sx=Ri(),nx=Math.max,ox=Math.min;Fp.exports=function(a,e){var t=sx(a);return t<0?nx(t+e,0):ox(t,e)}});var Mo=f((kO,Up)=>{"use strict";var ux=Ri(),lx=Math.min;Up.exports=function(a){var e=ux(a);return e>0?lx(e,9007199254740991):0}});var Fr=f((RO,Hp)=>{"use strict";var cx=Mo();Hp.exports=function(a){return cx(a.length)}});var Do=f(($O,Gp)=>{"use strict";var dx=ir(),px=qp(),hx=Fr(),jp=function(a){return function(e,t,r){var i=dx(e),s=hx(i);if(s===0)return!a&&-1;var n=px(r,s),o;if(a&&t!==t){for(;s>n;)if(o=i[n++],o!==o)return!0}else for(;s>n;n++)if((a||n in i)&&i[n]===t)return a||n||0;return!a&&-1}};Gp.exports={includes:jp(!0),indexOf:jp(!1)}});var $i=f((LO,Qp)=>{"use strict";Qp.exports=function(){}});var Wp=f(()=>{"use strict";var mx=ie(),fx=Do().includes,bx=pe(),gx=$i(),vx=bx(function(){return!Array(1).includes()});mx({target:"Array",proto:!0,forced:vx},{includes:function(e){return fx(this,e,arguments.length>1?arguments[1]:void 0)}});gx("includes")});var Dt=f((CO,Yp)=>{"use strict";var Sx=pt();Yp.exports=Sx});var Kp=f((OO,zp)=>{"use strict";Wp();var yx=Dt();zp.exports=yx("Array","includes")});var Jp=f((VO,Xp)=>{"use strict";var Tx=Kp();Xp.exports=Tx});var Xe=f((BO,Zp)=>{"use strict";var Ix=Jp();Zp.exports=Ix});var ys=f((zO,oh)=>{"use strict";var $x=yo(),Lx=To(),nh=$x("keys");oh.exports=function(a){return nh[a]||(nh[a]=Lx(a))}});var lh=f((KO,uh)=>{"use strict";var Mx=pe();uh.exports=!Mx(function(){function a(){}return a.prototype.constructor=null,Object.getPrototypeOf(new a)!==a.prototype})});var Ts=f((XO,dh)=>{"use strict";var Dx=Ke(),Cx=Z(),Ox=Cr(),Vx=ys(),Bx=lh(),ch=Vx("IE_PROTO"),Vo=Object,_x=Vo.prototype;dh.exports=Bx?Vo.getPrototypeOf:function(a){var e=Ox(a);if(Dx(e,ch))return e[ch];var t=e.constructor;return Cx(t)&&e instanceof t?t.prototype:e instanceof Vo?_x:null}});var Is=f((JO,ph)=>{"use strict";ph.exports={}});var fh=f((ZO,mh)=>{"use strict";var Nx=ne(),Bo=Ke(),Fx=ir(),qx=Do().indexOf,Ux=Is(),hh=Nx([].push);mh.exports=function(a,e){var t=Fx(a),r=0,i=[],s;for(s in t)!Bo(Ux,s)&&Bo(t,s)&&hh(i,s);for(;e.length>r;)Bo(t,s=e[r++])&&(~qx(i,s)||hh(i,s));return i}});var _o=f((eV,bh)=>{"use strict";bh.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]});var No=f((tV,gh)=>{"use strict";var Hx=fh(),jx=_o();gh.exports=Object.keys||function(e){return Hx(e,jx)}});var Fo=f((rV,Ih)=>{"use strict";var Sh=Le(),Gx=pe(),yh=ne(),Qx=Ts(),Wx=No(),Yx=ir(),zx=oo().f,Th=yh(zx),Kx=yh([].push),Xx=Sh&&Gx(function(){var a=Object.create(null);return a[2]=2,!Th(a,2)}),vh=function(a){return function(e){for(var t=Yx(e),r=Wx(t),i=Xx&&Qx(t)===null,s=r.length,n=0,o=[],u;s>n;)u=r[n++],(!Sh||(i?u in t:Th(t,u)))&&Kx(o,a?[u,t[u]]:t[u]);return o}};Ih.exports={entries:vh(!0),values:vh(!1)}});var Eh=f(()=>{"use strict";var Jx=ie(),Zx=Fo().entries;Jx({target:"Object",stat:!0},{entries:function(e){return Zx(e)}})});var Ph=f((sV,xh)=>{"use strict";Eh();var eP=Dr();xh.exports=eP.Object.entries});var Ah=f((nV,wh)=>{"use strict";var tP=Ph();wh.exports=tP});var qr=f((oV,kh)=>{"use strict";var rP=Ah();kh.exports=rP});var nr=f((uV,Rh)=>{"use strict";Rh.exports={}});var Mh=f((lV,Lh)=>{"use strict";var iP=re(),aP=Z(),$h=iP.WeakMap;Lh.exports=aP($h)&&/native code/.test(String($h))});var jo=f((cV,Oh)=>{"use strict";var sP=Mh(),Ch=re(),nP=De(),oP=Br(),qo=Ke(),Uo=wi(),uP=ys(),lP=Is(),Dh="Object already initialized",Ho=Ch.TypeError,cP=Ch.WeakMap,Es,Li,xs,dP=function(a){return xs(a)?Li(a):Es(a,{})},pP=function(a){return function(e){var t;if(!nP(e)||(t=Li(e)).type!==a)throw new Ho("Incompatible receiver, "+a+" required");return t}};sP||Uo.state?(Je=Uo.state||(Uo.state=new cP),Je.get=Je.get,Je.has=Je.has,Je.set=Je.set,Es=function(a,e){if(Je.has(a))throw new Ho(Dh);return e.facade=a,Je.set(a,e),e},Li=function(a){return Je.get(a)||{}},xs=function(a){return Je.has(a)}):(or=uP("state"),lP[or]=!0,Es=function(a,e){if(qo(a,or))throw new Ho(Dh);return e.facade=a,oP(a,or,e),e},Li=function(a){return qo(a,or)?a[or]:{}},xs=function(a){return qo(a,or)});var Je,or;Oh.exports={set:Es,get:Li,has:xs,enforce:dP,getterFor:pP}});var Wo=f((dV,Bh)=>{"use strict";var Go=Le(),hP=Ke(),Vh=Function.prototype,mP=Go&&Object.getOwnPropertyDescriptor,Qo=hP(Vh,"name"),fP=Qo&&function(){}.name==="something",bP=Qo&&(!Go||Go&&mP(Vh,"name").configurable);Bh.exports={EXISTS:Qo,PROPER:fP,CONFIGURABLE:bP}});var Nh=f(_h=>{"use strict";var gP=Le(),vP=Ao(),SP=sr(),yP=nt(),TP=ir(),IP=No();_h.f=gP&&!vP?Object.defineProperties:function(e,t){yP(e);for(var r=TP(t),i=IP(t),s=i.length,n=0,o;s>n;)SP.f(e,o=i[n++],r[o]);return e}});var Yo=f((hV,Fh)=>{"use strict";var EP=pt();Fh.exports=EP("document","documentElement")});var Jo=f((mV,Wh)=>{"use strict";var xP=nt(),PP=Nh(),qh=_o(),wP=Is(),AP=Yo(),kP=bs(),RP=ys(),Uh=">",Hh="<",Ko="prototype",Xo="script",Gh=RP("IE_PROTO"),zo=function(){},Qh=function(a){return Hh+Xo+Uh+a+Hh+"/"+Xo+Uh},jh=function(a){a.write(Qh("")),a.close();var e=a.parentWindow.Object;return a=null,e},$P=function(){var a=kP("iframe"),e="java"+Xo+":",t;return a.style.display="none",AP.appendChild(a),a.src=String(e),t=a.contentWindow.document,t.open(),t.write(Qh("document.F=Object")),t.close(),t.F},Ps,ws=function(){try{Ps=new ActiveXObject("htmlfile")}catch(e){}ws=typeof document!="undefined"?document.domain&&Ps?jh(Ps):$P():jh(Ps);for(var a=qh.length;a--;)delete ws[Ko][qh[a]];return ws()};wP[Gh]=!0;Wh.exports=Object.create||function(e,t){var r;return e!==null?(zo[Ko]=xP(e),r=new zo,zo[Ko]=null,r[Gh]=e):r=ws(),t===void 0?r:PP.f(r,t)}});var Ur=f((fV,Yh)=>{"use strict";var LP=Br();Yh.exports=function(a,e,t,r){return r&&r.enumerable?a[e]=t:LP(a,e,t),a}});var ru=f((bV,Xh)=>{"use strict";var MP=pe(),DP=Z(),CP=De(),OP=Jo(),zh=Ts(),VP=Ur(),BP=he(),_P=ze(),tu=BP("iterator"),Kh=!1,ht,Zo,eu;[].keys&&(eu=[].keys(),"next"in eu?(Zo=zh(zh(eu)),Zo!==Object.prototype&&(ht=Zo)):Kh=!0);var NP=!CP(ht)||MP(function(){var a={};return ht[tu].call(a)!==a});NP?ht={}:_P&&(ht=OP(ht));DP(ht[tu])||VP(ht,tu,function(){return this});Xh.exports={IteratorPrototype:ht,BUGGY_SAFARI_ITERATORS:Kh}});var As=f((gV,Zh)=>{"use strict";var FP=he(),qP=FP("toStringTag"),Jh={};Jh[qP]="z";Zh.exports=String(Jh)==="[object z]"});var Mi=f((vV,em)=>{"use strict";var UP=As(),HP=Z(),ks=rr(),jP=he(),GP=jP("toStringTag"),QP=Object,WP=ks(function(){return arguments}())==="Arguments",YP=function(a,e){try{return a[e]}catch(t){}};em.exports=UP?ks:function(a){var e,t,r;return a===void 0?"Undefined":a===null?"Null":typeof(t=YP(e=QP(a),GP))=="string"?t:WP?ks(e):(r=ks(e))==="Object"&&HP(e.callee)?"Arguments":r}});var rm=f((SV,tm)=>{"use strict";var zP=As(),KP=Mi();tm.exports=zP?{}.toString:function(){return"[object "+KP(this)+"]"}});var Di=f((yV,am)=>{"use strict";var XP=As(),JP=sr().f,ZP=Br(),ew=Ke(),tw=rm(),rw=he(),im=rw("toStringTag");am.exports=function(a,e,t,r){var i=t?a:a&&a.prototype;i&&(ew(i,im)||JP(i,im,{configurable:!0,value:e}),r&&!XP&&ZP(i,"toString",tw))}});var nm=f((TV,sm)=>{"use strict";var iw=ru().IteratorPrototype,aw=Jo(),sw=Ii(),nw=Di(),ow=nr(),uw=function(){return this};sm.exports=function(a,e,t,r){var i=e+" Iterator";return a.prototype=aw(iw,{next:sw(+!r,t)}),nw(a,i,!1,!0),ow[i]=uw,a}});var um=f((IV,om)=>{"use strict";var lw=ne(),cw=st();om.exports=function(a,e,t){try{return lw(cw(Object.getOwnPropertyDescriptor(a,e)[t]))}catch(r){}}});var cm=f((EV,lm)=>{"use strict";var dw=De();lm.exports=function(a){return dw(a)||a===null}});var pm=f((xV,dm)=>{"use strict";var pw=cm(),hw=String,mw=TypeError;dm.exports=function(a){if(pw(a))return a;throw new mw("Can't set "+hw(a)+" as a prototype")}});var iu=f((PV,hm)=>{"use strict";var fw=um(),bw=De(),gw=Mt(),vw=pm();hm.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var a=!1,e={},t;try{t=fw(Object.prototype,"__proto__","set"),t(e,[]),a=e instanceof Array}catch(r){}return function(i,s){return gw(i),vw(s),bw(i)&&(a?t(i,s):i.__proto__=s),i}}():void 0)});var xm=f((wV,Em)=>{"use strict";var Sw=ie(),yw=Me(),Rs=ze(),Tm=Wo(),Tw=Z(),Iw=nm(),mm=Ts(),fm=iu(),Ew=Di(),xw=Br(),au=Ur(),Pw=he(),bm=nr(),Im=ru(),ww=Tm.PROPER,Aw=Tm.CONFIGURABLE,gm=Im.IteratorPrototype,$s=Im.BUGGY_SAFARI_ITERATORS,Ci=Pw("iterator"),vm="keys",Oi="values",Sm="entries",ym=function(){return this};Em.exports=function(a,e,t,r,i,s,n){Iw(t,e,r);var o=function(v){if(v===i&&p)return p;if(!$s&&v&&v in c)return c[v];switch(v){case vm:return function(){return new t(this,v)};case Oi:return function(){return new t(this,v)};case Sm:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",l=!1,c=a.prototype,d=c[Ci]||c["@@iterator"]||i&&c[i],p=!$s&&d||o(i),h=e==="Array"&&c.entries||d,m,b,g;if(h&&(m=mm(h.call(new a)),m!==Object.prototype&&m.next&&(!Rs&&mm(m)!==gm&&(fm?fm(m,gm):Tw(m[Ci])||au(m,Ci,ym)),Ew(m,u,!0,!0),Rs&&(bm[u]=ym))),ww&&i===Oi&&d&&d.name!==Oi&&(!Rs&&Aw?xw(c,"name",Oi):(l=!0,p=function(){return yw(d,this)})),i)if(b={values:o(Oi),keys:s?p:o(vm),entries:o(Sm)},n)for(g in b)($s||l||!(g in c))&&au(c,g,b[g]);else Sw({target:e,proto:!0,forced:$s||l},b);return(!Rs||n)&&c[Ci]!==p&&au(c,Ci,p,{name:i}),bm[e]=p,b}});var wm=f((AV,Pm)=>{"use strict";Pm.exports=function(a,e){return{value:a,done:e}}});var nu=f((kV,Lm)=>{"use strict";var kw=ir(),su=$i(),Am=nr(),Rm=jo(),Rw=sr().f,$w=xm(),Ls=wm(),Lw=ze(),Mw=Le(),$m="Array Iterator",Dw=Rm.set,Cw=Rm.getterFor($m);Lm.exports=$w(Array,"Array",function(a,e){Dw(this,{type:$m,target:kw(a),index:0,kind:e})},function(){var a=Cw(this),e=a.target,t=a.index++;if(!e||t>=e.length)return a.target=void 0,Ls(void 0,!0);switch(a.kind){case"keys":return Ls(t,!1);case"values":return Ls(e[t],!1)}return Ls([t,e[t]],!1)},"values");var km=Am.Arguments=Am.Array;su("keys");su("values");su("entries");if(!Lw&&Mw&&km.name!=="values")try{Rw(km,"name",{value:"values"})}catch(a){}});var Dm=f((RV,Mm)=>{"use strict";var Ow=he(),Vw=nr(),Bw=Ow("iterator"),_w=Array.prototype;Mm.exports=function(a){return a!==void 0&&(Vw.Array===a||_w[Bw]===a)}});var ou=f(($V,Om)=>{"use strict";var Nw=Mi(),Cm=Pi(),Fw=Mr(),qw=nr(),Uw=he(),Hw=Uw("iterator");Om.exports=function(a){if(!Fw(a))return Cm(a,Hw)||Cm(a,"@@iterator")||qw[Nw(a)]}});var Bm=f((LV,Vm)=>{"use strict";var jw=Me(),Gw=st(),Qw=nt(),Ww=xi(),Yw=ou(),zw=TypeError;Vm.exports=function(a,e){var t=arguments.length<2?Yw(a):e;if(Gw(t))return Qw(jw(t,a));throw new zw(Ww(a)+" is not iterable")}});var Fm=f((MV,Nm)=>{"use strict";var Kw=Me(),_m=nt(),Xw=Pi();Nm.exports=function(a,e,t){var r,i;_m(a);try{if(r=Xw(a,"return"),!r){if(e==="throw")throw t;return t}r=Kw(r,a)}catch(s){i=!0,r=s}if(e==="throw")throw t;if(i)throw r;return _m(r),t}});var Ds=f((DV,jm)=>{"use strict";var Jw=Vr(),Zw=Me(),eA=nt(),tA=xi(),rA=Dm(),iA=Fr(),qm=Ei(),aA=Bm(),sA=ou(),Um=Fm(),nA=TypeError,Ms=function(a,e){this.stopped=a,this.result=e},Hm=Ms.prototype;jm.exports=function(a,e,t){var r=t&&t.that,i=!!(t&&t.AS_ENTRIES),s=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Jw(e,r),l,c,d,p,h,m,b,g=function(S){return l&&Um(l,"normal",S),new Ms(!0,S)},v=function(S){return i?(eA(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(s)l=a.iterator;else if(n)l=a;else{if(c=sA(a),!c)throw new nA(tA(a)+" is not iterable");if(rA(c)){for(d=0,p=iA(a);p>d;d++)if(h=v(a[d]),h&&qm(Hm,h))return h;return new Ms(!1)}l=aA(a,c)}for(m=s?a.next:l.next;!(b=Zw(m,l)).done;){try{h=v(b.value)}catch(S){Um(l,"throw",S)}if(typeof h=="object"&&h&&qm(Hm,h))return h}return new Ms(!1)}});var Qm=f((CV,Gm)=>{"use strict";var oA=Le(),uA=sr(),lA=Ii();Gm.exports=function(a,e,t){oA?uA.f(a,e,lA(0,t)):a[e]=t}});var Wm=f(()=>{"use strict";var cA=ie(),dA=Ds(),pA=Qm();cA({target:"Object",stat:!0},{fromEntries:function(e){var t={};return dA(e,function(r,i){pA(t,r,i)},{AS_ENTRIES:!0}),t}})});var zm=f((BV,Ym)=>{"use strict";nu();Wm();var hA=Dr();Ym.exports=hA.Object.fromEntries});var Xm=f((_V,Km)=>{"use strict";Km.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 Zm=f(()=>{"use strict";nu();var mA=Xm(),fA=re(),bA=Di(),Jm=nr();for(Cs in mA)bA(fA[Cs],Cs),Jm[Cs]=Jm.Array;var Cs});var tf=f((qV,ef)=>{"use strict";var gA=zm();Zm();ef.exports=gA});var uu=f((UV,rf)=>{"use strict";var vA=tf();rf.exports=vA});var af=f(()=>{"use strict"});var lu=f((GV,sf)=>{"use strict";var Vi=re(),SA=ar(),yA=rr(),Os=function(a){return SA.slice(0,a.length)===a};sf.exports=function(){return Os("Bun/")?"BUN":Os("Cloudflare-Workers")?"CLOUDFLARE":Os("Deno/")?"DENO":Os("Node.js/")?"NODE":Vi.Bun&&typeof Bun.version=="string"?"BUN":Vi.Deno&&typeof Deno.version=="object"?"DENO":yA(Vi.process)==="process"?"NODE":Vi.window&&Vi.document?"BROWSER":"REST"}()});var Vs=f((QV,nf)=>{"use strict";var TA=lu();nf.exports=TA==="NODE"});var uf=f((WV,of)=>{"use strict";var IA=sr();of.exports=function(a,e,t){return IA.f(a,e,t)}});var df=f((YV,cf)=>{"use strict";var EA=pt(),xA=uf(),PA=he(),wA=Le(),lf=PA("species");cf.exports=function(a){var e=EA(a);wA&&e&&!e[lf]&&xA(e,lf,{configurable:!0,get:function(){return this}})}});var hf=f((zV,pf)=>{"use strict";var AA=Ei(),kA=TypeError;pf.exports=function(a,e){if(AA(e,a))return a;throw new kA("Incorrect invocation")}});var du=f((KV,mf)=>{"use strict";var RA=ne(),$A=Z(),cu=wi(),LA=RA(Function.toString);$A(cu.inspectSource)||(cu.inspectSource=function(a){return LA(a)});mf.exports=cu.inspectSource});var hu=f((XV,Sf)=>{"use strict";var MA=ne(),DA=pe(),ff=Z(),CA=Mi(),OA=pt(),VA=du(),bf=function(){},gf=OA("Reflect","construct"),pu=/^\s*(?:class|function)\b/,BA=MA(pu.exec),_A=!pu.test(bf),Bi=function(e){if(!ff(e))return!1;try{return gf(bf,[],e),!0}catch(t){return!1}},vf=function(e){if(!ff(e))return!1;switch(CA(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return _A||!!BA(pu,VA(e))}catch(t){return!0}};vf.sham=!0;Sf.exports=!gf||DA(function(){var a;return Bi(Bi.call)||!Bi(Object)||!Bi(function(){a=!0})||a})?vf:Bi});var Tf=f((JV,yf)=>{"use strict";var NA=hu(),FA=xi(),qA=TypeError;yf.exports=function(a){if(NA(a))return a;throw new qA(FA(a)+" is not a constructor")}});var mu=f((ZV,Ef)=>{"use strict";var If=nt(),UA=Tf(),HA=Mr(),jA=he(),GA=jA("species");Ef.exports=function(a,e){var t=If(a).constructor,r;return t===void 0||HA(r=If(t)[GA])?e:UA(r)}});var Pf=f((eB,xf)=>{"use strict";var QA=ne();xf.exports=QA([].slice)});var Af=f((tB,wf)=>{"use strict";var WA=TypeError;wf.exports=function(a,e){if(a<e)throw new WA("Not enough arguments");return a}});var fu=f((rB,kf)=>{"use strict";var YA=ar();kf.exports=/(?:ipad|iphone|ipod).*applewebkit/i.test(YA)});var xu=f((iB,Bf)=>{"use strict";var Ce=re(),zA=io(),KA=Vr(),Rf=Z(),XA=Ke(),Vf=pe(),$f=Yo(),JA=Pf(),Lf=bs(),ZA=Af(),ek=fu(),tk=Vs(),Tu=Ce.setImmediate,Iu=Ce.clearImmediate,rk=Ce.process,bu=Ce.Dispatch,ik=Ce.Function,Mf=Ce.MessageChannel,ak=Ce.String,gu=0,_i={},Df="onreadystatechange",Ni,ur,vu,Su;Vf(function(){Ni=Ce.location});var Eu=function(a){if(XA(_i,a)){var e=_i[a];delete _i[a],e()}},yu=function(a){return function(){Eu(a)}},Cf=function(a){Eu(a.data)},Of=function(a){Ce.postMessage(ak(a),Ni.protocol+"//"+Ni.host)};(!Tu||!Iu)&&(Tu=function(e){ZA(arguments.length,1);var t=Rf(e)?e:ik(e),r=JA(arguments,1);return _i[++gu]=function(){zA(t,void 0,r)},ur(gu),gu},Iu=function(e){delete _i[e]},tk?ur=function(a){rk.nextTick(yu(a))}:bu&&bu.now?ur=function(a){bu.now(yu(a))}:Mf&&!ek?(vu=new Mf,Su=vu.port2,vu.port1.onmessage=Cf,ur=KA(Su.postMessage,Su)):Ce.addEventListener&&Rf(Ce.postMessage)&&!Ce.importScripts&&Ni&&Ni.protocol!=="file:"&&!Vf(Of)?(ur=Of,Ce.addEventListener("message",Cf,!1)):Df in Lf("script")?ur=function(a){$f.appendChild(Lf("script"))[Df]=function(){$f.removeChild(this),Eu(a)}}:ur=function(a){setTimeout(yu(a),0)});Bf.exports={set:Tu,clear:Iu}});var Ff=f((aB,Nf)=>{"use strict";var _f=re(),sk=Le(),nk=Object.getOwnPropertyDescriptor;Nf.exports=function(a){if(!sk)return _f[a];var e=nk(_f,a);return e&&e.value}});var Pu=f((sB,Uf)=>{"use strict";var qf=function(){this.head=null,this.tail=null};qf.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}}};Uf.exports=qf});var jf=f((nB,Hf)=>{"use strict";var ok=ar();Hf.exports=/ipad|iphone|ipod/i.test(ok)&&typeof Pebble!="undefined"});var Qf=f((oB,Gf)=>{"use strict";var uk=ar();Gf.exports=/web0s(?!.*chrome)/i.test(uk)});var Zf=f((uB,Jf)=>{"use strict";var jr=re(),lk=Ff(),Wf=Vr(),wu=xu().set,ck=Pu(),dk=fu(),pk=jf(),hk=Qf(),Au=Vs(),Yf=jr.MutationObserver||jr.WebKitMutationObserver,zf=jr.document,Kf=jr.process,Bs=jr.Promise,$u=lk("queueMicrotask"),Hr,ku,Ru,_s,Xf;$u||(Fi=new ck,qi=function(){var a,e;for(Au&&(a=Kf.domain)&&a.exit();e=Fi.get();)try{e()}catch(t){throw Fi.head&&Hr(),t}a&&a.enter()},!dk&&!Au&&!hk&&Yf&&zf?(ku=!0,Ru=zf.createTextNode(""),new Yf(qi).observe(Ru,{characterData:!0}),Hr=function(){Ru.data=ku=!ku}):!pk&&Bs&&Bs.resolve?(_s=Bs.resolve(void 0),_s.constructor=Bs,Xf=Wf(_s.then,_s),Hr=function(){Xf(qi)}):Au?Hr=function(){Kf.nextTick(qi)}:(wu=Wf(wu,jr),Hr=function(){wu(qi)}),$u=function(a){Fi.head||Hr(),Fi.add(a)});var Fi,qi;Jf.exports=$u});var tb=f((lB,eb)=>{"use strict";eb.exports=function(a,e){try{arguments.length===1?console.error(a):console.error(a,e)}catch(t){}}});var Ns=f((cB,rb)=>{"use strict";rb.exports=function(a){try{return{error:!1,value:a()}}catch(e){return{error:!0,value:e}}}});var lr=f((dB,ib)=>{"use strict";var mk=re();ib.exports=mk.Promise});var Gr=f((pB,ob)=>{"use strict";var fk=re(),Ui=lr(),bk=Z(),gk=wo(),vk=du(),Sk=he(),ab=lu(),yk=ze(),Lu=ho(),sb=Ui&&Ui.prototype,Tk=Sk("species"),Mu=!1,nb=bk(fk.PromiseRejectionEvent),Ik=gk("Promise",function(){var a=vk(Ui),e=a!==String(Ui);if(!e&&Lu===66||yk&&!(sb.catch&&sb.finally))return!0;if(!Lu||Lu<51||!/native code/.test(a)){var t=new Ui(function(s){s(1)}),r=function(s){s(function(){},function(){})},i=t.constructor={};if(i[Tk]=r,Mu=t.then(function(){})instanceof r,!Mu)return!0}return!e&&(ab==="BROWSER"||ab==="DENO")&&!nb});ob.exports={CONSTRUCTOR:Ik,REJECTION_EVENT:nb,SUBCLASSING:Mu}});var Qr=f((hB,lb)=>{"use strict";var ub=st(),Ek=TypeError,xk=function(a){var e,t;this.promise=new a(function(r,i){if(e!==void 0||t!==void 0)throw new Ek("Bad Promise constructor");e=r,t=i}),this.resolve=ub(e),this.reject=ub(t)};lb.exports.f=function(a){return new xk(a)}});var kb=f(()=>{"use strict";var Pk=ie(),wk=ze(),Hs=Vs(),Ct=re(),Kr=Me(),cb=Ur(),db=iu(),Ak=Di(),kk=df(),Rk=st(),Us=Z(),$k=De(),Lk=hf(),Mk=mu(),bb=xu().set,Bu=Zf(),Dk=tb(),Ck=Ns(),Ok=Pu(),gb=jo(),js=lr(),_u=Gr(),vb=Qr(),Gs="Promise",Sb=_u.CONSTRUCTOR,Vk=_u.REJECTION_EVENT,Bk=_u.SUBCLASSING,Du=gb.getterFor(Gs),_k=gb.set,Wr=js&&js.prototype,cr=js,Fs=Wr,yb=Ct.TypeError,Cu=Ct.document,Nu=Ct.process,Ou=vb.f,Nk=Ou,Fk=!!(Cu&&Cu.createEvent&&Ct.dispatchEvent),Tb="unhandledrejection",qk="rejectionhandled",pb=0,Ib=1,Uk=2,Fu=1,Eb=2,qs,hb,Hk,mb,xb=function(a){var e;return $k(a)&&Us(e=a.then)?e:!1},Pb=function(a,e){var t=e.value,r=e.state===Ib,i=r?a.ok:a.fail,s=a.resolve,n=a.reject,o=a.domain,u,l,c;try{i?(r||(e.rejection===Eb&&Gk(e),e.rejection=Fu),i===!0?u=t:(o&&o.enter(),u=i(t),o&&(o.exit(),c=!0)),u===a.promise?n(new yb("Promise-chain cycle")):(l=xb(u))?Kr(l,u,s,n):s(u)):n(t)}catch(d){o&&!c&&o.exit(),n(d)}},wb=function(a,e){a.notified||(a.notified=!0,Bu(function(){for(var t=a.reactions,r;r=t.get();)Pb(r,a);a.notified=!1,e&&!a.rejection&&jk(a)}))},Ab=function(a,e,t){var r,i;Fk?(r=Cu.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(a,!1,!0),Ct.dispatchEvent(r)):r={promise:e,reason:t},!Vk&&(i=Ct["on"+a])?i(r):a===Tb&&Dk("Unhandled promise rejection",t)},jk=function(a){Kr(bb,Ct,function(){var e=a.facade,t=a.value,r=fb(a),i;if(r&&(i=Ck(function(){Hs?Nu.emit("unhandledRejection",t,e):Ab(Tb,e,t)}),a.rejection=Hs||fb(a)?Eb:Fu,i.error))throw i.value})},fb=function(a){return a.rejection!==Fu&&!a.parent},Gk=function(a){Kr(bb,Ct,function(){var e=a.facade;Hs?Nu.emit("rejectionHandled",e):Ab(qk,e,a.value)})},Yr=function(a,e,t){return function(r){a(e,r,t)}},zr=function(a,e,t){a.done||(a.done=!0,t&&(a=t),a.value=e,a.state=Uk,wb(a,!0))},Vu=function(a,e,t){if(!a.done){a.done=!0,t&&(a=t);try{if(a.facade===e)throw new yb("Promise can't be resolved itself");var r=xb(e);r?Bu(function(){var i={done:!1};try{Kr(r,e,Yr(Vu,i,a),Yr(zr,i,a))}catch(s){zr(i,s,a)}}):(a.value=e,a.state=Ib,wb(a,!1))}catch(i){zr({done:!1},i,a)}}};if(Sb&&(cr=function(e){Lk(this,Fs),Rk(e),Kr(qs,this);var t=Du(this);try{e(Yr(Vu,t),Yr(zr,t))}catch(r){zr(t,r)}},Fs=cr.prototype,qs=function(e){_k(this,{type:Gs,done:!1,notified:!1,parent:!1,reactions:new Ok,rejection:!1,state:pb,value:void 0})},qs.prototype=cb(Fs,"then",function(e,t){var r=Du(this),i=Ou(Mk(this,cr));return r.parent=!0,i.ok=Us(e)?e:!0,i.fail=Us(t)&&t,i.domain=Hs?Nu.domain:void 0,r.state===pb?r.reactions.add(i):Bu(function(){Pb(i,r)}),i.promise}),hb=function(){var a=new qs,e=Du(a);this.promise=a,this.resolve=Yr(Vu,e),this.reject=Yr(zr,e)},vb.f=Ou=function(a){return a===cr||a===Hk?new hb(a):Nk(a)},!wk&&Us(js)&&Wr!==Object.prototype)){mb=Wr.then,Bk||cb(Wr,"then",function(e,t){var r=this;return new cr(function(i,s){Kr(mb,r,i,s)}).then(e,t)},{unsafe:!0});try{delete Wr.constructor}catch(a){}db&&db(Wr,Fs)}Pk({global:!0,constructor:!0,wrap:!0,forced:Sb},{Promise:cr});Ak(cr,Gs,!1,!0);kk(Gs)});var Db=f((bB,Mb)=>{"use strict";var Qk=he(),$b=Qk("iterator"),Lb=!1;try{Rb=0,qu={next:function(){return{done:!!Rb++}},return:function(){Lb=!0}},qu[$b]=function(){return this},Array.from(qu,function(){throw 2})}catch(a){}var Rb,qu;Mb.exports=function(a,e){try{if(!e&&!Lb)return!1}catch(i){return!1}var t=!1;try{var r={};r[$b]=function(){return{next:function(){return{done:t=!0}}}},a(r)}catch(i){}return t}});var Uu=f((gB,Cb)=>{"use strict";var Wk=lr(),Yk=Db(),zk=Gr().CONSTRUCTOR;Cb.exports=zk||!Yk(function(a){Wk.all(a).then(void 0,function(){})})});var Ob=f(()=>{"use strict";var Kk=ie(),Xk=Me(),Jk=st(),Zk=Qr(),eR=Ns(),tR=Ds(),rR=Uu();Kk({target:"Promise",stat:!0,forced:rR},{all:function(e){var t=this,r=Zk.f(t),i=r.resolve,s=r.reject,n=eR(function(){var o=Jk(t.resolve),u=[],l=0,c=1;tR(e,function(d){var p=l++,h=!1;c++,Xk(o,t,d).then(function(m){h||(h=!0,u[p]=m,--c||i(u))},s)}),--c||i(u)});return n.error&&s(n.value),r.promise}})});var Bb=f(()=>{"use strict";var iR=ie(),aR=ze(),sR=Gr().CONSTRUCTOR,ju=lr(),nR=pt(),oR=Z(),uR=Ur(),Vb=ju&&ju.prototype;iR({target:"Promise",proto:!0,forced:sR,real:!0},{catch:function(a){return this.then(void 0,a)}});!aR&&oR(ju)&&(Hu=nR("Promise").prototype.catch,Vb.catch!==Hu&&uR(Vb,"catch",Hu,{unsafe:!0}));var Hu});var _b=f(()=>{"use strict";var lR=ie(),cR=Me(),dR=st(),pR=Qr(),hR=Ns(),mR=Ds(),fR=Uu();lR({target:"Promise",stat:!0,forced:fR},{race:function(e){var t=this,r=pR.f(t),i=r.reject,s=hR(function(){var n=dR(t.resolve);mR(e,function(o){cR(n,t,o).then(r.resolve,i)})});return s.error&&i(s.value),r.promise}})});var Nb=f(()=>{"use strict";var bR=ie(),gR=Qr(),vR=Gr().CONSTRUCTOR;bR({target:"Promise",stat:!0,forced:vR},{reject:function(e){var t=gR.f(this),r=t.reject;return r(e),t.promise}})});var Gu=f((wB,Fb)=>{"use strict";var SR=nt(),yR=De(),TR=Qr();Fb.exports=function(a,e){if(SR(a),yR(e)&&e.constructor===a)return e;var t=TR.f(a),r=t.resolve;return r(e),t.promise}});var Hb=f(()=>{"use strict";var IR=ie(),ER=pt(),qb=ze(),xR=lr(),Ub=Gr().CONSTRUCTOR,PR=Gu(),wR=ER("Promise"),AR=qb&&!Ub;IR({target:"Promise",stat:!0,forced:qb||Ub},{resolve:function(e){return PR(AR&&this===wR?xR:this,e)}})});var jb=f(()=>{"use strict";kb();Ob();Bb();_b();Nb();Hb()});var Yb=f(()=>{"use strict";var kR=ie(),RR=ze(),Qs=lr(),$R=pe(),Qb=pt(),Wb=Z(),LR=mu(),Gb=Gu(),MR=Ur(),Wu=Qs&&Qs.prototype,DR=!!Qs&&$R(function(){Wu.finally.call({then:function(){}},function(){})});kR({target:"Promise",proto:!0,real:!0,forced:DR},{finally:function(a){var e=LR(this,Qb("Promise")),t=Wb(a);return this.then(t?function(r){return Gb(e,a()).then(function(){return r})}:a,t?function(r){return Gb(e,a()).then(function(){throw r})}:a)}});!RR&&Wb(Qs)&&(Qu=Qb("Promise").prototype.finally,Wu.finally!==Qu&&MR(Wu,"finally",Qu,{unsafe:!0}));var Qu});var Kb=f((DB,zb)=>{"use strict";af();jb();Yb();var CR=Dt();zb.exports=CR("Promise","finally")});var Jb=f((CB,Xb)=>{"use strict";var OR=Kb();Xb.exports=OR});var Ws=f((OB,Zb)=>{"use strict";var VR=Jb();Zb.exports=VR});var pg=f(()=>{"use strict";var KR=ie(),XR=Fo().values;KR({target:"Object",stat:!0},{values:function(e){return XR(e)}})});var mg=f((S_,hg)=>{"use strict";pg();var JR=Dr();hg.exports=JR.Object.values});var bg=f((y_,fg)=>{"use strict";var ZR=mg();fg.exports=ZR});var Jr=f((T_,gg)=>{"use strict";var e$=bg();gg.exports=e$});var $g=f(()=>{"use strict";var b$=ie(),g$=Cr(),v$=Fr(),S$=Ri(),y$=$i();b$({target:"Array",proto:!0},{at:function(e){var t=g$(this),r=v$(t),i=S$(e),s=i>=0?i:r+i;return s<0||s>=r?void 0:t[s]}});y$("at")});var Mg=f((z_,Lg)=>{"use strict";$g();var T$=Dt();Lg.exports=T$("Array","at")});var Cg=f((K_,Dg)=>{"use strict";var I$=Mg();Dg.exports=I$});var ei=f((X_,Og)=>{"use strict";var E$=Cg();Og.exports=E$});var bl=f((wF,dv)=>{"use strict";var aL=rr();dv.exports=Array.isArray||function(e){return aL(e)==="Array"}});var hv=f((AF,pv)=>{"use strict";var sL=TypeError,nL=9007199254740991;pv.exports=function(a){if(a>nL)throw sL("Maximum allowed index exceeded");return a}});var bv=f((kF,fv)=>{"use strict";var oL=bl(),uL=Fr(),lL=hv(),cL=Vr(),mv=function(a,e,t,r,i,s,n,o){for(var u=i,l=0,c=n?cL(n,o):!1,d,p;l<r;)l in t&&(d=c?c(t[l],l,e):t[l],s>0&&oL(d)?(p=uL(d),u=mv(a,e,d,p,u,s-1)-1):(lL(u+1),a[u]=d),u++),l++;return u};fv.exports=mv});var yv=f((RF,Sv)=>{"use strict";var gv=bl(),dL=hu(),pL=De(),hL=he(),mL=hL("species"),vv=Array;Sv.exports=function(a){var e;return gv(a)&&(e=a.constructor,dL(e)&&(e===vv||gv(e.prototype))?e=void 0:pL(e)&&(e=e[mL],e===null&&(e=void 0))),e===void 0?vv:e}});var Iv=f(($F,Tv)=>{"use strict";var fL=yv();Tv.exports=function(a,e){return new(fL(a))(e===0?0:e)}});var Ev=f(()=>{"use strict";var bL=ie(),gL=bv(),vL=st(),SL=Cr(),yL=Fr(),TL=Iv();bL({target:"Array",proto:!0},{flatMap:function(e){var t=SL(this),r=yL(t),i;return vL(e),i=TL(t,0),i.length=gL(i,t,t,r,0,1,e,arguments.length>1?arguments[1]:void 0),i}})});var xv=f(()=>{"use strict";var IL=$i();IL("flatMap")});var wv=f((OF,Pv)=>{"use strict";Ev();xv();var EL=Dt();Pv.exports=EL("Array","flatMap")});var kv=f((VF,Av)=>{"use strict";var xL=wv();Av.exports=xL});var gl=f((BF,Rv)=>{"use strict";var PL=kv();Rv.exports=PL});var ia=f((YF,zv)=>{"use strict";var DL=Mi(),CL=String;zv.exports=function(a){if(DL(a)==="Symbol")throw new TypeError("Cannot convert a Symbol value to a string");return CL(a)}});var Sl=f((zF,Kv)=>{"use strict";Kv.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 Zv=f((KF,Jv)=>{"use strict";var OL=ne(),VL=Mt(),BL=ia(),Tl=Sl(),Xv=OL("".replace),_L=RegExp("^["+Tl+"]+"),NL=RegExp("(^|[^"+Tl+"])["+Tl+"]+$"),yl=function(a){return function(e){var t=BL(VL(e));return a&1&&(t=Xv(t,_L,"")),a&2&&(t=Xv(t,NL,"$1")),t}};Jv.exports={start:yl(1),end:yl(2),trim:yl(3)}});var iS=f((XF,rS)=>{"use strict";var FL=Wo().PROPER,qL=pe(),eS=Sl(),tS="\u200B\x85\u180E";rS.exports=function(a){return qL(function(){return!!eS[a]()||tS[a]()!==tS||FL&&eS[a].name!==a})}});var Il=f((JF,aS)=>{"use strict";var UL=Zv().start,HL=iS();aS.exports=HL("trimStart")?function(){return UL(this)}:"".trimStart});var nS=f(()=>{"use strict";var jL=ie(),sS=Il();jL({target:"String",proto:!0,name:"trimStart",forced:"".trimLeft!==sS},{trimLeft:sS})});var uS=f(()=>{"use strict";nS();var GL=ie(),oS=Il();GL({target:"String",proto:!0,name:"trimStart",forced:"".trimStart!==oS},{trimStart:oS})});var cS=f((iq,lS)=>{"use strict";uS();var QL=Dt();lS.exports=QL("String","trimLeft")});var pS=f((aq,dS)=>{"use strict";var WL=cS();dS.exports=WL});var mS=f((sq,hS)=>{"use strict";var YL=pS();hS.exports=YL});var $S=f(()=>{"use strict"});var LS=f(()=>{"use strict"});var DS=f((M1,MS)=>{"use strict";var gM=De(),vM=rr(),SM=he(),yM=SM("match");MS.exports=function(a){var e;return gM(a)&&((e=a[yM])!==void 0?!!e:vM(a)==="RegExp")}});var OS=f((D1,CS)=>{"use strict";var TM=nt();CS.exports=function(){var a=TM(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 _S=f((C1,BS)=>{"use strict";var IM=Me(),EM=Ke(),xM=Ei(),PM=OS(),VS=RegExp.prototype;BS.exports=function(a){var e=a.flags;return e===void 0&&!("flags"in VS)&&!EM(a,"flags")&&xM(VS,a)?IM(PM,a):e}});var FS=f((O1,NS)=>{"use strict";var Ll=ne(),wM=Cr(),AM=Math.floor,Rl=Ll("".charAt),kM=Ll("".replace),$l=Ll("".slice),RM=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,$M=/\$([$&'`]|\d{1,2})/g;NS.exports=function(a,e,t,r,i,s){var n=t+a.length,o=r.length,u=$M;return i!==void 0&&(i=wM(i),u=RM),kM(s,u,function(l,c){var d;switch(Rl(c,0)){case"$":return"$";case"&":return a;case"`":return $l(e,0,t);case"'":return $l(e,n);case"<":d=i[$l(c,1,-1)];break;default:var p=+c;if(p===0)return l;if(p>o){var h=AM(p/10);return h===0?l:h<=o?r[h-1]===void 0?Rl(c,1):r[h-1]+Rl(c,1):l}d=r[p-1]}return d===void 0?"":d})}});var HS=f(()=>{"use strict";var LM=ie(),MM=Me(),Dl=ne(),qS=Mt(),DM=Z(),CM=Mr(),OM=DS(),ni=ia(),VM=Pi(),BM=_S(),_M=FS(),NM=he(),FM=ze(),qM=NM("replace"),UM=TypeError,Ml=Dl("".indexOf),HM=Dl("".replace),US=Dl("".slice),jM=Math.max;LM({target:"String",proto:!0},{replaceAll:function(e,t){var r=qS(this),i,s,n,o,u,l,c,d,p,h,m=0,b="";if(!CM(e)){if(i=OM(e),i&&(s=ni(qS(BM(e))),!~Ml(s,"g")))throw new UM("`.replaceAll` does not allow non-global regexes");if(n=VM(e,qM),n)return MM(n,e,r,t);if(FM&&i)return HM(ni(r),e,t)}for(o=ni(r),u=ni(e),l=DM(t),l||(t=ni(t)),c=u.length,d=jM(1,c),p=Ml(o,u);p!==-1;)h=l?ni(t(u,p,o)):_M(u,o,p,[],void 0,t),b+=US(o,m,p)+h,m=p+c,p=p+d>o.length?-1:Ml(o,u,p+d);return m<o.length&&(b+=US(o,m)),b}})});var GS=f((_1,jS)=>{"use strict";$S();LS();HS();var GM=Dt();jS.exports=GM("String","replaceAll")});var WS=f((N1,QS)=>{"use strict";var QM=GS();QS.exports=QM});var zS=f((F1,YS)=>{"use strict";var WM=WS();YS.exports=WM});var XS=f((q1,KS)=>{"use strict";var YM=Ri(),zM=ia(),KM=Mt(),XM=RangeError;KS.exports=function(e){var t=zM(KM(this)),r="",i=YM(e);if(i<0||i===1/0)throw new XM("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))i&1&&(r+=t);return r}});var ry=f((U1,ty)=>{"use strict";var ey=ne(),JM=Mo(),JS=ia(),ZM=XS(),eD=Mt(),tD=ey(ZM),rD=ey("".slice),iD=Math.ceil,ZS=function(a){return function(e,t,r){var i=JS(eD(e)),s=JM(t),n=i.length,o=r===void 0?" ":JS(r),u,l;return s<=n||o===""?i:(u=s-n,l=tD(o,iD(u/o.length)),l.length>u&&(l=rD(l,0,u)),a?i+l:l+i)}};ty.exports={start:ZS(!1),end:ZS(!0)}});var ay=f((H1,iy)=>{"use strict";var aD=ar();iy.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(aD)});var sy=f(()=>{"use strict";var sD=ie(),nD=ry().start,oD=ay();sD({target:"String",proto:!0,forced:oD},{padStart:function(e){return nD(this,e,arguments.length>1?arguments[1]:void 0)}})});var oy=f((Q1,ny)=>{"use strict";sy();var uD=Dt();ny.exports=uD("String","padStart")});var ly=f((W1,uy)=>{"use strict";var lD=oy();uy.exports=lD});var dy=f((Y1,cy)=>{"use strict";var cD=ly();cy.exports=cD});var od="2.0.123-dev.43da90c8.0";var ye=(i=>(i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused",i))(ye||{}),Lt=(y=>(y.MPEG="MPEG",y.DASH="DASH",y.DASH_SEP="DASH_SEP",y.DASH_SEP_VK="DASH_SEP",y.DASH_WEBM="DASH_WEBM",y.DASH_WEBM_AV1="DASH_WEBM_AV1",y.DASH_STREAMS="DASH_STREAMS",y.DASH_WEBM_VK="DASH_WEBM",y.DASH_ONDEMAND="DASH_ONDEMAND",y.DASH_ONDEMAND_VK="DASH_ONDEMAND",y.DASH_LIVE="DASH_LIVE",y.DASH_LIVE_CMAF="DASH_LIVE_CMAF",y.DASH_LIVE_WEBM="DASH_LIVE_WEBM",y.HLS="HLS",y.HLS_ONDEMAND="HLS_ONDEMAND",y.HLS_JS="HLS",y.HLS_LIVE="HLS_LIVE",y.HLS_LIVE_CMAF="HLS_LIVE_CMAF",y.WEB_RTC_LIVE="WEB_RTC_LIVE",y))(Lt||{});var hs=(i=>(i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED",i))(hs||{}),eo=(r=>(r.HTTP1="http1",r.HTTP2="http2",r.QUIC="quic",r))(eo||{});var to=(n=>(n.NONE="none",n.INLINE="inline",n.FULLSCREEN="fullscreen",n.SECOND_SCREEN="second_screen",n.PIP="pip",n.INVISIBLE="invisible",n))(to||{});var NT=_(Xe(),1);import{assertNever as sh,assertNonNullable as Ex,isNonNullable as vs,ValueSubject as Co,Subject as xx,Subscription as Px,merge as wx,observableFrom as Ax,fromEvent as th,map as rh,tap as ih,filterChanged as kx,isNullable as Oo,ErrorCategory as ah}from"@vkontakte/videoplayer-shared/es2015";var eh=a=>new Promise((e,t)=>{let r=document.createElement("script");r.setAttribute("src",a),r.onload=()=>e(),r.onerror=i=>t(i),document.body.appendChild(r)});var Ss=class{constructor(e){this.connection$=new Co(void 0);this.castState$=new Co("NOT_AVAILABLE");this.errorEvent$=new xx;this.realCastState$=new Co("NOT_AVAILABLE");this.subscription=new Px;this.isDestroyed=!1;var s;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");let t="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${t}`}),e.isDisabled||!t)return;let r=vs((s=window.chrome)==null?void 0:s.cast),i=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&!this.isDestroyed&&this.initializeCastApi()},i||eh("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:ah.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())==null||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())==null?void 0:e.getCurrentSession())==null||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,i,s;(s=(i=(r=cast.framework.CastContext.getInstance())==null?void 0:r.getCurrentSession())==null?void 0:i.getMediaSession())==null||s.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){vs(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){let t=this.connection$.getValue();Oo(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){let t=this.connection$.getValue();Oo(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.isDestroyed=!0,this.subscription.unsubscribe()}initListeners(){let e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(th(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(i=>{var s,n,o;switch(i.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=(s=r.getCurrentSession())==null?void 0:s.getMediaSession())==null?void 0:n.media)==null?void 0:o.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return sh(i.sessionState)}})).add(wx(th(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ih(i=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(i)}`})}),rh(i=>i.castState)),Ax([r.getCastState()])).pipe(kx(),rh(Rx),ih(i=>{this.log({message:`realCastState$: ${i}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(i=>{var o,u;let s=i==="CONNECTED",n=vs(this.connection$.getValue());if(s&&!n){let l=r.getCurrentSession();Ex(l);let c=l.getCastDevice(),d=(u=(o=l.getMediaSession())==null?void 0:o.media)==null?void 0:u.contentId;(Oo(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:c}))}else!s&&n&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(i==="CONNECTED"?vs(this.connection$.getValue())?"CONNECTED":"AVAILABLE":i)}))}initializeCastApi(){var i;let e,t,r;try{e=cast.framework.CastContext.getInstance(),t=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(s){return}try{e.setOptions({receiverApplicationId:(i=this.params.receiverApplicationId)!=null?i:t,autoJoinPolicy:r}),this.initListeners()}catch(s){this.errorEvent$.next({id:"ChromecastInitializer",category:ah.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:s})}}},Rx=a=>{switch(a){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return"NOT_AVAILABLE";case cast.framework.CastState.NOT_CONNECTED:return"AVAILABLE";case cast.framework.CastState.CONNECTING:return"CONNECTING";case cast.framework.CastState.CONNECTED:return"CONNECTED";default:return sh(a)}};var mc=_(Xe(),1),yT=_(qr(),1),TT=_(uu(),1);var lg=_(Ws(),1);import{assertNever as eg}from"@vkontakte/videoplayer-shared/es2015";var me=(a,e=0,t=0)=>{switch(t){case 0:return a.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case 1:{if(e===0)return a;let r=new URL(a);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case 2:{let r=new URL(a);return!r.searchParams.get("offset_p")&&e===0?a:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:eg(t)}return a},Ys=(a,e)=>{var t;switch(e){case 0:return NaN;case 1:{let r=new URL(a);return Number(r.searchParams.get("playback_shift"))}case 2:{let r=new URL(a);return Number((t=r.searchParams.get("offset_p"))!=null?t:0)}default:eg(e)}};var x=(a,e,t=!1)=>{let r=a.getTransition();(t||!r||r.to===e)&&a.setState(e)};import{isNonNullable as BR,Subject as zs,merge as tg}from"@vkontakte/videoplayer-shared/es2015";var O=class{constructor(e){this.transitionStarted$=new zs;this.transitionEnded$=new zs;this.transitionUpdated$=new zs;this.forceChanged$=new zs;this.stateChangeStarted$=tg(this.transitionStarted$,this.transitionUpdated$);this.stateChangeEnded$=tg(this.transitionEnded$,this.forceChanged$);this.state=e,this.prevState=void 0}setState(e){let t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){let t=this.transition,r=this.state;r===e||BR(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}};import{assertNever as _R}from"@vkontakte/videoplayer-shared/es2015";var rg=a=>{switch(a){case"MPEG":case"DASH":case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":case"HLS":case"HLS_ONDEMAND":return!1;case"DASH_LIVE":case"DASH_LIVE_CMAF":case"HLS_LIVE":case"HLS_LIVE_CMAF":case"DASH_LIVE_WEBM":case"WEB_RTC_LIVE":return!0;default:return _R(a)}};import{assertNever as Xr,assertNonNullable as dr,debounce as ig,ErrorCategory as ag,fromEvent as pr,isNonNullable as sg,map as ng,merge as og,observableFrom as NR,Subject as FR,Subscription as Yu,timeout as qR,getHighestQuality as UR}from"@vkontakte/videoplayer-shared/es2015";var HR=5,jR=5,GR=500,ug=7e3,Hi=class{constructor(e){this.subscription=new Yu;this.loadMediaTimeoutSubscription=new Yu;this.videoState=new O("stopped");this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.stop());return}if(!t){if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&e!=="stopped"){this.seek(s.position/1e3);return}switch(r){case"ready":{switch(e){case"playing":case"paused":case"ready":break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Xr(e)}break}case"playing":{switch(e){case"playing":break;case"paused":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"ready":this.videoState.startTransitionTo("playing"),this.params.connection.remotePlayerController.playOrPause();break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Xr(e)}break}case"paused":{switch(e){case"playing":this.videoState.startTransitionTo("paused"),this.params.connection.remotePlayerController.playOrPause();break;case"paused":break;case"ready":this.videoState.startTransitionTo("paused"),this.videoState.setState("paused");break;case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();break;default:Xr(e)}break}default:Xr(r)}}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(rg(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 Yu;this.subscription.add(e),this.subscription.add(og(this.videoState.stateChangeStarted$.pipe(ng(i=>`stateChangeStarted$ ${JSON.stringify(i)}`)),this.videoState.stateChangeEnded$.pipe(ng(i=>`stateChangeEnded$ ${JSON.stringify(i)}`))).subscribe(i=>this.log({message:`[videoState] ${i}`})));let t=(i,s)=>this.subscription.add(i.subscribe(s));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{let i=new FR;e.add(i.pipe(ig(GR)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let s=NaN;e.add(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);let o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state==="applying"||Math.abs(o-s)>HR)&&i.next(o),s=o})),e.add(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),i=>{this.logRemoteEvent(i),i.value?this.handleRemotePause():this.handleRemotePlay()}),t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),i=>{this.logRemoteEvent(i);let{remotePlayer:s}=this.params.connection,n=i.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&s.duration-s.currentTime<jR&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,"stopped");break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:Xr(n)}}),t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({volume:i.value})}),t(pr(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),i=>{this.logRemoteEvent(i),this.handleRemoteVolumeChange({muted:i.value})});let r=og(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,NR(["init"])).pipe(ig(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});let{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"));let r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:"none"})}}prepare(){let e=this.params.format;this.log({message:`[prepare] format: ${e}`});let t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="paused"||e==="playing")&&(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused"))}handleRemotePlay(){let e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)==="playing"||e==="paused")&&(this.videoState.setState("playing"),x(this.params.desiredState.playbackState,"playing"))}handleRemoteReady(){var t;let e=this.videoState.getTransition();(e==null?void 0:e.to)==="ready"&&this.videoState.setState("ready"),((t=this.params.desiredState.playbackState.getTransition())==null?void 0:t.to)==="ready"&&x(this.params.desiredState.playbackState,"ready")}handleRemoteStop(){this.videoState.getState()!=="stopped"&&this.videoState.setState("stopped")}handleRemoteVolumeChange(e){var i,s;let t=this.params.output.volume$.getValue(),r={volume:(i=e.volume)!=null?i:t.volume,muted:(s=e.muted)!=null?s:t.muted};(r.volume!==t.volume||r.muted!==r.muted)&&this.params.output.volume$.next(r)}seek(e){this.params.output.willSeekEvent$.next();let{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){let{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var l;let t=this.params.source,r,i,s;switch(e){case"MPEG":{let c=t[e];dr(c);let d=UR(Object.keys(c));dr(d);let p=c[d];dr(p),r=p,i="video/mp4",s=chrome.cast.media.StreamType.BUFFERED;break}case"HLS":case"HLS_ONDEMAND":{let c=t[e];dr(c),r=c.url,i="application/x-mpegurl",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_SEP":case"DASH_ONDEMAND":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_STREAMS":{let c=t[e];dr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.BUFFERED;break}case"DASH_LIVE_CMAF":{let c=t[e];dr(c),r=c.url,i="application/dash+xml",s=chrome.cast.media.StreamType.LIVE;break}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let c=t[e];dr(c),r=me(c.url),i="application/x-mpegurl",s=chrome.cast.media.StreamType.LIVE;break}case"DASH_LIVE":case"WEB_RTC_LIVE":{let c="Unsupported format for Chromecast",d=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:ag.VIDEO_PIPELINE,message:c,thrown:d}),d}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Xr(e)}let n=new chrome.cast.media.MediaInfo((l=this.params.meta.videoId)!=null?l:r,i);n.contentUrl=r,n.streamType=s,n.metadata=new chrome.cast.media.GenericMediaMetadata;let{title:o,subtitle:u}=this.params.meta;return sg(o)&&(n.metadata.title=o),sg(u)&&(n.metadata.subtitle=u),n}createLoadRequest(e){let t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;let r=this.params.desiredState.seekState.getState();return r.state==="applying"||r.state==="requested"?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){let t=this.params.connection.session.loadMedia(e),r=new Promise((i,s)=>{this.loadMediaTimeoutSubscription.add(qR(ug).subscribe(()=>s(`timeout(${ug})`)))});(0,lg.default)(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},i=>{let s=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${i}`;this.log({message:s}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:ag.VIDEO_PIPELINE,message:s,thrown:i})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}};var ml=_(Xe(),1);import{clearVideoElement as dg}from"@vkontakte/videoplayer-shared/es2015";import{clearVideoElement as QR}from"@vkontakte/videoplayer-shared/es2015";var cg=a=>{try{a.pause(),a.playbackRate=0,QR(a),a.remove()}catch(e){console.error(e)}};import{fromEvent as WR,Subscription as YR}from"@vkontakte/videoplayer-shared/es2015";var zu=class{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}},Ku=window.WeakMap?new WeakMap:new zu,Xu=window.WeakMap?new WeakMap:new Map,zR=(a,e=20)=>{let t=0;return WR(a,"ratechange").subscribe(r=>{t++,t>=e&&(a.currentTime=a.currentTime,t=0)})},Te=(a,{audioVideoSyncRate:e})=>{let t=a.querySelector("video"),r=!!t;t?dg(t):(t=document.createElement("video"),a.appendChild(t)),Ku.set(t,r);let i=new YR;return i.add(zR(t,e)),Xu.set(t,i),t.setAttribute("crossorigin","anonymous"),t.setAttribute("playsinline","playsinline"),t.controls=!1,t.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),t},Ie=a=>{let e=Xu.get(a);e==null||e.unsubscribe(),Xu.delete(a);let t=Ku.get(a);Ku.delete(a),t?dg(a):cg(a)};var Zu=_(Jr(),1);import{assertNonNullable as ji,isNonNullable as ut,isNullable as i$,fromEvent as Zr,merge as vg,observableFrom as Sg,filterChanged as yg,map as Gi,Subject as Tg,Subscription as a$,ValueSubject as s$,ErrorCategory as n$}from"@vkontakte/videoplayer-shared/es2015";import{isNonNullable as Ju,isNullable as t$,Subscription as r$}from"@vkontakte/videoplayer-shared/es2015";var Ks=(a,e,t,{equal:r=(n,o)=>n===o,changed$:i,onError:s}={})=>{let n=a.getState(),o=e(),u=t$(i),l=new r$;return i&&l.add(i.subscribe(c=>{let d=a.getState();r(c,d)&&a.setState(c)},s)),r(o,n)||(t(n),u&&a.setState(n)),l.add(a.stateChangeStarted$.subscribe(c=>{t(c.to),u&&a.setState(c.to)},s)),l},ot=(a,e,t)=>Ks(e,()=>a.loop,r=>{Ju(r)&&(a.loop=r)},{onError:t}),Ee=(a,e,t,r)=>Ks(e,()=>({muted:a.muted,volume:a.volume}),i=>{Ju(i)&&(a.muted=i.muted,a.volume=i.volume)},{equal:(i,s)=>i===s||(i==null?void 0:i.muted)===(s==null?void 0:s.muted)&&(i==null?void 0:i.volume)===(s==null?void 0:s.volume),changed$:t,onError:r}),Ne=(a,e,t,r)=>Ks(e,()=>a.playbackRate,i=>{Ju(i)&&(a.playbackRate=i)},{changed$:t,onError:r}),Ot=Ks;var o$=a=>["__",a.language,a.label].join("|"),u$=(a,e)=>{if(a.id===e)return!0;let[t,r,i]=e.split("|");return a.language===r&&a.label===i},el=class a{constructor(e){this.available$=new Tg;this.current$=new s$(void 0);this.error$=new Tg;this.subscription=new a$;this.externalTracks=new Map;this.internalTracks=new Map;this.baseURL=e}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();let i=s=>{this.error$.next({id:"TextTracksManager",category:n$.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:s})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ot(t.internalTextTracks,()=>(0,Zu.default)(this.internalTracks),s=>{ut(s)&&this.setInternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Gi(s=>s.filter(({type:n})=>n==="internal"))),onError:i})),this.subscription.add(Ot(t.externalTextTracks,()=>(0,Zu.default)(this.externalTracks),s=>{ut(s)&&this.setExternal(s)},{equal:(s,n)=>ut(s)&&ut(n)&&s.length===n.length&&s.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(Gi(s=>s.filter(({type:n})=>n==="external"))),onError:i})),this.subscription.add(Ot(t.currentTextTrack,()=>{if(this.video)return;let s=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return s&&this.htmlTextTrackToITextTrack(s).id},s=>this.select(s),{changed$:this.current$,onError:i})),this.subscription.add(Ot(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(let s of this.htmlTextTracksAsArray())this.applyCueSettings(s.cues),this.applyCueSettings(s.activeCues)}))}subscribe(){ji(this.video);let{textTracks:e}=this.video;this.subscription.add(Zr(e,"addtrack").subscribe(()=>{let r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(vg(Zr(e,"addtrack"),Zr(e,"removetrack"),Sg(["init"])).pipe(Gi(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),yg((r,i)=>r.length===i.length&&r.every(({id:s},n)=>s===i[n].id))).subscribe(this.available$)),this.subscription.add(vg(Zr(e,"change"),Sg(["init"])).pipe(Gi(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),Gi(r=>r&&this.htmlTextTrackToITextTrack(r).id),yg()).subscribe(this.current$));let t=r=>{var i,s;return this.applyCueSettings((s=(i=r.target)==null?void 0:i.activeCues)!=null?s:null)};this.subscription.add(Zr(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)==null||s.addEventListener("cuechange",t);let i=o=>{var l,c,d,p,h;let u=(c=(l=o.target)==null?void 0:l.cues)!=null?c:null;u&&u.length&&(this.applyCueSettings((p=(d=o.target)==null?void 0:d.cues)!=null?p:null),(h=o.target)==null||h.removeEventListener("cuechange",i))};(n=r.track)==null||n.addEventListener("cuechange",i)})),this.subscription.add(Zr(e,"removetrack").subscribe(r=>{var i;(i=r.track)==null||i.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;let t=this.cueSettings.getState();for(let r of Array.from(e)){let i=r;ut(t.align)&&(i.align=t.align),ut(t.position)&&(i.position=t.position),ut(t.size)&&(i.size=t.size),ut(t.line)&&(i.line=t.line)}}htmlTextTracksAsArray(e=!1){ji(this.video);let t=[...this.video.textTracks];return e?t:t.filter(a.isHealthyTrack)}htmlTextTrackToITextTrack(e){var o,u,l,c,d;let{language:t,label:r}=e,i=e.id?e.id:o$(e),s=this.externalTracks.has(i),n=(l=s?(o=this.externalTracks.get(i))==null?void 0:o.isAuto:(u=this.internalTracks.get(i))==null?void 0:u.isAuto)!=null?l:i.includes("auto");return s?{id:i,type:"external",isAuto:n,language:t,label:r,url:(c=this.externalTracks.get(i))==null?void 0:c.url}:{id:i,type:"internal",isAuto:n,language:t,label:r,url:(d=this.internalTracks.get(i))==null?void 0:d.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){let t=[...this.externalTracks];e.filter(({id:r,language:i,isAuto:s})=>!this.internalTracks.has(r)&&!t.some(([,n])=>n.language===i&&n.isAuto===s)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(i=>i.id===r)).forEach(([,r])=>this.detach(r))}select(e){ji(this.video);for(let t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(let t of this.htmlTextTracksAsArray(!0))(i$(e)||!u$(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){ji(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){ji(this.video);let t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}},Fe=el;var ft=class{constructor(){this.pausedTime=0;this.streamOffset=0;this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}};var Ig=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},tl=a=>{let e=Ig(a);return!!(e&&e.fullscreenElement&&e.fullscreenElement===a)},Eg=a=>{let e=Ig(a);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===a)};import{fromEvent as qe,map as Vt,merge as Pg,filterChanged as c$,isNonNullable as wg,Subject as d$,filter as Ag,mapTo as kg,combine as p$,once as h$,ErrorCategory as m$,ValueSubject as Rg,clientChecker as f$}from"@vkontakte/videoplayer-shared/es2015";var l$=3,xg=(a,e,t=l$)=>{let r=0,i=0;for(let s=0;s<a.length;s++){let n=a.start(s),o=a.end(s);if(n<=e&&e<=o){if(r=n,i=o,!t)return{from:r,to:i};for(let u=s-1;u>=0;u--)a.end(u)+t>=r&&(r=a.start(u));for(let u=s+1;u<a.length;u++)a.start(u)-t<=i&&(i=a.end(u))}}return{from:r,to:i}};var xe=a=>{let e=y=>qe(a,y).pipe(kg(void 0)),r=Pg(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(y=>qe(a,y))).pipe(Vt(y=>y.type==="ended"?a.readyState<2:a.readyState<3),c$()),i=Pg(qe(a,"progress"),qe(a,"timeupdate")).pipe(Vt(()=>xg(a.buffered,a.currentTime))),s=f$.isSafari?p$({play:e("play").pipe(h$()),playing:e("playing")}).pipe(kg(void 0)):e("playing"),n=qe(a,"volumechange").pipe(Vt(()=>({muted:a.muted,volume:a.volume}))),o=qe(a,"ratechange").pipe(Vt(()=>a.playbackRate)),u=qe(a,"error").pipe(Ag(()=>!!(a.error||a.played.length)),Vt(()=>{var I;let y=a.error;return{id:y?`MediaError#${y.code}`:"HtmlVideoError",category:m$.VIDEO_PIPELINE,message:y?y.message:"Error event from HTML video element",thrown:(I=a.error)!=null?I:void 0}})),l=qe(a,"timeupdate").pipe(Vt(()=>a.currentTime)),c=new d$,d=.3,p;l.subscribe(y=>{a.loop&&wg(p)&&wg(y)&&p>=a.duration-d&&y<=d&&c.next(p),p=y});let h=e("pause").pipe(Ag(()=>!a.error&&p!==a.duration)),m=qe(a,"enterpictureinpicture"),b=qe(a,"leavepictureinpicture"),g=new Rg(Eg(a));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));let v=new Rg(tl(a));return qe(a,"fullscreenchange").pipe(Vt(()=>tl(a))).subscribe(v),{playing$:s,pause$:h,canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:qe(a,"durationchange").pipe(Vt(()=>a.duration)),isBuffering$:r,currentBuffer$:i,volumeState$:n,playbackRateState$:o,inPiP$:g,inFullscreen$:v,enterPip$:m,leavePip$:b}};import{VideoQuality as Bt}from"@vkontakte/videoplayer-shared/es2015";var _t=a=>{switch(a){case"mobile":return Bt.Q_144P;case"lowest":return Bt.Q_240P;case"low":return Bt.Q_360P;case"sd":case"medium":return Bt.Q_480P;case"hd":case"high":return Bt.Q_720P;case"fullhd":case"full":return Bt.Q_1080P;case"quadhd":case"quad":return Bt.Q_1440P;case"ultrahd":case"ultra":return Bt.Q_2160P}};var Nt=_(ei(),1),Ug=_(Xe(),1),Xs=_(qr(),1);import{isNonNullable as oe,isNullable as il,now as Hg,isHigher as al,isHigherOrEqual as sl,isInvariantQuality as Ng,isLower as Fg,isLowerOrEqual as nl,videoSizeToQuality as x$,assertNotEmptyArray as jg,assertNonNullable as P$}from"@vkontakte/videoplayer-shared/es2015";var rl=!1,bt={},Vg=a=>{rl=a},Bg=()=>{bt={}},_g=a=>{a(bt)},Qi=(a,e)=>{var t;rl&&(bt.meta=(t=bt.meta)!=null?t:{},bt.meta[a]=e)},ge=class{constructor(e){this.name=e}next(e){var r,i;if(!rl)return;bt.series=(r=bt.series)!=null?r:{};let t=(i=bt.series[this.name])!=null?i:[];t.push([Date.now(),e]),bt.series[this.name]=t}};var w$=new ge("best_bitrate"),Gg=(a,e,t)=>(e-t)*Math.pow(2,-10*a)+t;var ol=a=>(e,t)=>a*(Number(e.bitrate)-Number(t.bitrate)),Wi=class{constructor(){this.history={}}recordSelection(e){this.history[e.id]=Hg()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}},Qg='Assertion "ABR Tracks is empty array" failed',Js=(a,e,t,r)=>{var u;let i=[...e].sort(ol(1)),s=[...t].sort(ol(1)),n=s.filter(l=>oe(l.bitrate)&&oe(a.bitrate)?a.bitrate/l.bitrate>r:!0),o=(u=(0,Nt.default)(s,Math.round(s.length*i.indexOf(a)/(i.length+1))))!=null?u:(0,Nt.default)(s,-1);return o&&(0,Ug.default)(n,o)?o:n.length?(0,Nt.default)(n,-1):(0,Nt.default)(s,0)},qg=a=>"quality"in a,Wg=(a,e,t,r)=>{var n;let i=oe((n=r==null?void 0:r.last)==null?void 0:n.bitrate)&&oe(t==null?void 0:t.bitrate)&&r.last.bitrate<t.bitrate?a.trackCooldownIncreaseQuality:a.trackCooldownDecreaseQuality,s=t&&r&&r.history[t.id]&&Hg()-r.history[t.id]<=i&&(!r.last||t.id!==r.last.id);if(t!=null&&t.id&&r&&!s&&r.recordSelection(t),s&&(r!=null&&r.last)){let o=r.last;r==null||r.recordSwitch(o);let u=qg(o)?"video":"audio",l=qg(o)?o.quality:o.bitrate;return e({message:`
8
8
  [last ${u} selected] ${l}
9
- `}),o}return r==null||r.recordSwitch(t),t},I$=(a,e)=>Math.log(e)/Math.log(a),Ft=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:f})=>{var q,R,U,N,W,A;Bg(a,_g);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let T=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(T-1)+1;else{let D=r.pixelRatioLogBase,[M=0,se=0,Be=0]=r.pixelRatioLogCoefficients,It=I$(D,M*T+se)+Be;Number.isFinite(It)&&(b*=It)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,S=r.considerPlaybackRate&&oe(o)?o:1,v=a.filter(T=>!Lg(T.quality)).sort((T,D)=>al(T.quality,D.quality)?-1:1),y=(q=(0,Nt.default)(v,-1))==null?void 0:q.quality,I=(R=(0,Nt.default)(v,0))==null?void 0:R.quality,E=il(i)||oe(i.min)&&oe(i.max)&&Mg(i.max,i.min)||oe(i.min)&&I&&al(i.min,I)||oe(i.max)&&y&&Mg(i.max,y),$=S*Vg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),B={},L=v.filter(T=>{let D=!0;if(g)if(T.size)D=T.size.width<=g.width&&T.size.height<=g.height;else{let de=g&&S$(g);D=de?nl(T.quality,de):!0}if(!D)return B[T.quality]="FitsContainer",!1;let M=h||t;if(!(oe(M)&&isFinite(M)&&oe(T.bitrate)?M-s>=T.bitrate*$:!0))return B[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&oe(r.minBufferToSwitchUp)&&u&&!Lg(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&al(T.quality,u.quality))return B[T.quality]="Buffer",!1;if(!!d&&sl(T.quality,d))return B[T.quality]="DroppedFramesLimit",!1;if(!!p&&sl(T.quality,p))return B[T.quality]="StallsLimit",!1;let j=E||(il(i.max)||nl(T.quality,i.max))&&(il(i.min)||sl(T.quality,i.min)),ce=oe(c)&&!c?nl(T.quality,r.backgroundVideoQualityLimit):!0;return!j||!ce?(B[T.quality]="FitsQualityLimits",!1):!0})[0];L&&L.bitrate&&T$.next(L.bitrate);let F=(U=L!=null?L:(0,Nt.default)(v,-1))!=null?U:a[0];return F.quality!==((N=l==null?void 0:l.last)==null?void 0:N.quality)&&f({message:`
9
+ `}),o}return r==null||r.recordSwitch(t),t},A$=(a,e)=>Math.log(e)/Math.log(a),Ft=(a,{container:e,estimatedThroughput:t,tuning:r,limits:i,reserve:s=0,forwardBufferHealth:n,playbackRate:o,current:u,history:l,visible:c,droppedVideoMaxQualityLimit:d,stallsVideoMaxQualityLimit:p,stallsPredictedThroughput:h,abrLogger:m})=>{var q,R,H,N,W,k;jg(a,Qg);let b=r.containerSizeFactor;if(r.usePixelRatio&&window.devicePixelRatio){let T=window.devicePixelRatio;if(r.pixelRatioMultiplier)b*=r.pixelRatioMultiplier*(T-1)+1;else{let C=r.pixelRatioLogBase,[D=0,se=0,Ve=0]=r.pixelRatioLogCoefficients,It=A$(C,D*T+se)+Ve;Number.isFinite(It)&&(b*=It)}}let g=r.limitByContainer&&e&&e.width>0&&e.height>0?{width:e.width*b,height:e.height*b}:void 0,v=r.considerPlaybackRate&&oe(o)?o:1,S=a.filter(T=>!Ng(T.quality)).sort((T,C)=>al(T.quality,C.quality)?-1:1),y=(q=(0,Nt.default)(S,-1))==null?void 0:q.quality,I=(R=(0,Nt.default)(S,0))==null?void 0:R.quality,w=il(i)||oe(i.min)&&oe(i.max)&&Fg(i.max,i.min)||oe(i.min)&&I&&al(i.min,I)||oe(i.max)&&y&&Fg(i.max,y),L=v*Gg(n!=null?n:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),B={},M=S.filter(T=>{let C=!0;if(g)if(T.size)C=T.size.width<=g.width&&T.size.height<=g.height;else{let de=g&&x$(g);C=de?nl(T.quality,de):!0}if(!C)return B[T.quality]="FitsContainer",!1;let D=h||t;if(!(oe(D)&&isFinite(D)&&oe(T.bitrate)?D-s>=T.bitrate*L:!0))return B[T.quality]="FitsThroughput",!1;if(r.lazyQualitySwitch&&oe(r.minBufferToSwitchUp)&&u&&!Ng(u.quality)&&(n!=null?n:0)<r.minBufferToSwitchUp&&al(T.quality,u.quality))return B[T.quality]="Buffer",!1;if(!!d&&sl(T.quality,d))return B[T.quality]="DroppedFramesLimit",!1;if(!!p&&sl(T.quality,p))return B[T.quality]="StallsLimit",!1;let j=w||(il(i.max)||nl(T.quality,i.max))&&(il(i.min)||sl(T.quality,i.min)),ce=oe(c)&&!c?nl(T.quality,r.backgroundVideoQualityLimit):!0;return!j||!ce?(B[T.quality]="FitsQualityLimits",!1):!0})[0];M&&M.bitrate&&w$.next(M.bitrate);let F=(H=M!=null?M:(0,Nt.default)(S,-1))!=null?H:a[0];return F.quality!==((N=l==null?void 0:l.last)==null?void 0:N.quality)&&m({message:`
10
10
  [VIDEO TRACKS ABR]
11
11
  [available video tracks]
12
- ${a.map(T=>{var D,M;return`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${(D=T.size)==null?void 0:D.width}:${(M=T.size)==null?void 0:M.height} }`}).join(`
12
+ ${a.map(T=>{var C,D;return`{ id: ${T.id}, quality: ${T.quality}, bitrate: ${T.bitrate}, size: ${(C=T.size)==null?void 0:C.width}:${(D=T.size)==null?void 0:D.height} }`}).join(`
13
13
  `)}
14
14
 
15
15
  [tuning]
16
- ${(0,Xs.default)(r!=null?r:{}).map(([T,D])=>`${T}: ${D}`).join(`
16
+ ${(0,Xs.default)(r!=null?r:{}).map(([T,C])=>`${T}: ${C}`).join(`
17
17
  `)}
18
18
 
19
19
  [limit params]
20
20
  containerSizeFactor: ${b},
21
- containerSizeLimit: ${(W=g==null?void 0:g.width)!=null?W:0} x ${(A=g==null?void 0:g.height)!=null?A:0},
21
+ containerSizeLimit: ${(W=g==null?void 0:g.width)!=null?W:0} x ${(k=g==null?void 0:g.height)!=null?k:0},
22
22
  estimatedThroughput: ${t},
23
23
  stallsPredictedThroughput: ${h},
24
24
  reserve: ${s},
25
25
  playbackRate: ${o},
26
- playbackRateFactor: ${S},
26
+ playbackRateFactor: ${v},
27
27
  forwardBufferHealth: ${n},
28
- bitrateFactor: ${$},
28
+ bitrateFactor: ${L},
29
29
  minBufferToSwitchUp: ${r.minBufferToSwitchUp},
30
30
  droppedVideoMaxQualityLimit: ${d},
31
31
  stallsVideoMaxQualityLimit: ${p},
32
- limitsAreInvalid: ${E},
32
+ limitsAreInvalid: ${w},
33
33
  maxQualityLimit: ${i==null?void 0:i.max},
34
34
  minQualityLimit: ${i==null?void 0:i.min},
35
35
 
36
36
  [limited video tracks]
37
- ${(0,Xs.default)(B).map(([T,D])=>`${T}: ${D}`).join(`
37
+ ${(0,Xs.default)(B).map(([T,C])=>`${T}: ${C}`).join(`
38
38
  `)||"All tracks are available"}
39
39
 
40
- [best video track] ${L==null?void 0:L.quality}
40
+ [best video track] ${M==null?void 0:M.quality}
41
41
  [selected video track] ${F==null?void 0:F.quality}
42
- `}),Ng(r,f,F,l)},Fg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var S;Bg(t,_g);let c=i.considerPlaybackRate&&oe(s)?s:1,d=[...t].sort(ol(-1)),p=a.bitrate;y$(p);let h=c*Vg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),f,b=Zs(a,e,t,i.minVideoAudioRatio),g=l||r;return oe(g)&&isFinite(g)&&(f=d.find(v=>oe(v.bitrate)&&oe(b==null?void 0:b.bitrate)?g-p>=v.bitrate*h&&v.bitrate>=b.bitrate:!1)),f||(f=b),(f==null?void 0:f.bitrate)!==((S=o==null?void 0:o.last)==null?void 0:S.bitrate)&&u({message:`
42
+ `}),Wg(r,m,F,l)},Yg=(a,e,t,{estimatedThroughput:r,tuning:i,playbackRate:s,forwardBufferHealth:n,history:o,abrLogger:u,stallsPredictedThroughput:l})=>{var v;jg(t,Qg);let c=i.considerPlaybackRate&&oe(s)?s:1,d=[...t].sort(ol(-1)),p=a.bitrate;P$(p);let h=c*Gg(n!=null?n:.5,i.bitrateAudioFactorAtEmptyBuffer,i.bitrateAudioFactorAtFullBuffer),m,b=Js(a,e,t,i.minVideoAudioRatio),g=l||r;return oe(g)&&isFinite(g)&&(m=d.find(S=>oe(S.bitrate)&&oe(b==null?void 0:b.bitrate)?g-p>=S.bitrate*h&&S.bitrate>=b.bitrate:!1)),m||(m=b),(m==null?void 0:m.bitrate)!==((v=o==null?void 0:o.last)==null?void 0:v.bitrate)&&u({message:`
43
43
  [AUDIO TRACKS ABR]
44
44
  [available audio tracks]
45
- ${t.map(v=>`{ id: ${v.id}, bitrate: ${v.bitrate} }`).join(`
45
+ ${t.map(S=>`{ id: ${S.id}, bitrate: ${S.bitrate} }`).join(`
46
46
  `)}
47
47
 
48
48
  [tuning]
49
- ${(0,Xs.default)(i!=null?i:{}).map(([v,y])=>`${v}: ${y}`).join(`
49
+ ${(0,Xs.default)(i!=null?i:{}).map(([S,y])=>`${S}: ${y}`).join(`
50
50
  `)}
51
51
 
52
52
  [limit params]
@@ -59,15 +59,15 @@ var HT=Object.create;var Jn=Object.defineProperty,jT=Object.defineProperties,GT=
59
59
  bitrateFactor: ${h},
60
60
  minBufferToSwitchUp: ${i.minBufferToSwitchUp},
61
61
 
62
- [selected audio track] ${f==null?void 0:f.id}
63
- `}),f&&Ng(i,u,f,o)};var ue=a=>new URL(a).hostname;import{assertNever as Kg,assertNonNullable as Jg,combine as H$,debounce as j$,ErrorCategory as Xg,filter as Zg,filterChanged as G$,isNonNullable as pl,map as sn,merge as ev,observableFrom as Q$,once as W$,Subscription as Y$,ValueSubject as hl,videoQualityToHeight as z$,videoSizeToQuality as K$}from"@vkontakte/videoplayer-shared/es2015";var Ug=_(Je(),1);var qg=a=>{if(a instanceof DOMException&&(0,Ug.default)(["Failed to load because no supported source was found.","The element has no supported sources."],a.message))throw a;return!(a instanceof DOMException&&(a.code===20||a.name==="AbortError"))},xe=(a,e)=>k(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!qg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return qg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as tn,isNullable as P$,assertNonNullable as Ki}from"@vkontakte/videoplayer-shared/es2015";var jg=_(Zr(),1);import{isNonNullable as Hg,assertNonNullable as en,now as E$}from"@vkontakte/videoplayer-shared/es2015";function le(){return E$()}function ul(a){return le()-a}function ll(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Gg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ri(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",f=7e3,b=2e3,g=()=>{if(u)return;en(c);let R=ul(c),U;if(R<b){U=b-R,setTimeout(g,U);return}b*=2,b>f&&(b=f),n&&n.abort(),n=new i,$()},S=R=>(s=R,q),v=R=>(d=R,q),y=()=>(h="json",q),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},E=R=>(p=R,q),$=()=>{c=le(),n=new i,n.open("get",a);let R=0,U,N=0,W=()=>(en(c),Math.max(c,Math.max(U||0,N||0)));if(s&&n.addEventListener("progress",A=>{let T=le();s.updateChunk&&A.loaded>R&&(s.updateChunk(W(),A.loaded-R),R=A.loaded,U=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;en(n);let A=n.status;if(A>=200&&A<300){if(n.response.byteLength&&s){let T=n.response.byteLength-R;T&&s.updateChunk&&s.updateChunk(W(),T)}n.responseType==="json"&&!(0,jg.default)(n.response).length?I():(d&&d(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),p){let A=()=>{en(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(N=le(),n.removeEventListener("readystatechange",A))};n.addEventListener("readystatechange",A)}return n.responseType=h,n.send(),q},q={withBitrateReporting:S,withParallel:E,withJSONResponse:y,withRetryCount:R=>(l=R,q),withRetryInterval:(R,U)=>(Hg(R)&&(b=R),Hg(U)&&(f=U),q),withTimeout:R=>(o=R,q),withFinally:v,send:$,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return q}var Yi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var Qg=_(Zr(),1);var zi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=le(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=le()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ri(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=le()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=le();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,Qg.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as w$}from"@vkontakte/videoplayer-shared/es2015";var rn=1e4,cl=3;var A$=6e4,k$=10,R$=1,$$=500,Ji=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new w$,this.chunkRateEstimator=new Yi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ll(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ll(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||tn(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Gg(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new zi(cl,rn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},p=(I,E,$)=>{u&&u.abort(),u=ri(this.urlResolver.resolve(I,!1),E,$,()=>this._retryCallback()).withTimeout(rn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(cl).withFinally(()=>{u=null}).send()},h=(I,E,$)=>{Ki(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),E,$,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},f=I=>{let E=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${E}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)f(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){f(1);return}let $=le()-1e4,B=0;for(let L=0;L<this.bufferStates.length;L++){let F=this.bufferStates[L];I=Math.min(I,F.buf),F.ts<$&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${I} drop=${B} jitter=${this.sourceJitter}`);let J=I-R$;this.sourceJitter>=0?J-=this.sourceJitter/2:this.sourceJitter-=1,J>3?f(1.15):J>1?f(1.1):J>.3?f(1.05):f(1)}},S=I=>{let E,$=()=>E&&E.start?E.start.length:0,B=A=>E.start[A]/1e3,J=A=>E.dur[A]/1e3,L=A=>E.fragIndex+A,F=(A,T)=>({chunkIdx:L(A),startTS:B(A),dur:J(A),discontinuity:T}),q=()=>{let A=0;if(E&&E.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,D=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,M=T;this.sourceJitter>1&&(M+=this.sourceJitter-1);let se=E.dur.length-1;for(;se>=0&&(M-=E.dur[se],!(M<=0));--se);A=Math.min(se,E.dur.length-1-D),A=Math.max(A,0)}return F(A,!0)},R=A=>{let T=$();if(!(T<=0)){if(tn(A)){for(let D=0;D<T;D++)if(B(D)>A)return F(D)}return q()}},U=A=>{let T=$(),D=A?A.chunkIdx+1:0,M=D-E.fragIndex;if(!(T<=0)){if(!A||M<0||M-T>k$)return t(`Resync: offset=${M} bChunks=${T} chunk=`+JSON.stringify(A)),q();if(!(M>=T))return F(D-E.fragIndex,!1)}},N=(A,T,D)=>{l&&l.abort(),l=ri(this.urlResolver.resolve(A,!0,this.lowLatency),T,D,()=>this._retryCallback()).withTimeout(rn).withRetryCount(cl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(A,T)=>{N(I,D=>{if(!d())return;E=D;let M=!!E.lowLatency;M!==this.lowLatency&&b(M);let se=0;for(let Be=0;Be<E.dur.length;++Be)se+=E.dur[Be];se>0&&(Ki(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/E.dur.length)),i({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,A(R(T))},()=>this._handleNetworkError())},nextChunk:U}},v=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ki(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:E,logger:$}=this.params,B=S(e.jidxUrl),J,L,F,q,R=0,U,N,W,A=()=>{U&&(clearTimeout(U),U=void 0);let j=Math.max($$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ce=R+j,de=le(),Ve=Math.min(1e4,ce-de);R=de;let Et=()=>{l||d()&&B.seek(()=>{d()&&(R=le(),T(),A())})};Ve>0?U=window.setTimeout(()=>{this.paused?A():Et()},Ve):Et()},T=()=>{let j;for(;j=B.nextChunk(q);)q=j,It(j);let ce=B.nextChunk(F);if(ce){if(F&&ce.discontinuity){$("Detected discontinuity; restarting playback"),this.paused?A():(v(),this._initPlayerWith(e));return}Be(ce)}else A()},D=(j,ce)=>{if(!d()||!this.sourceBuffer)return;let de,Ve,Et,Pr=xt=>{window.setTimeout(()=>{d()&&D(j,ce)},xt)};if(this.sourceBuffer.updating)$("Source buffer is updating; delaying appendBuffer"),Pr(100);else{let xt=le(),zt=E.currentTime;!this.paused&&E.buffered.length>1&&N===zt&&xt-W>500&&($("Stall suspected; trying to fix"),this._fixupStall()),N!==zt&&(N=zt,W=xt);let wr=this._getBufferSizeSec();if(wr>30)$(`Buffered ${wr} seconds; delaying appendBuffer`),Pr(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:xt,buf:wr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ce&&ce()}catch(hi){if(hi.name==="QuotaExceededError")$("QuotaExceededError; delaying appendBuffer"),Et=this.sourceBuffer.buffered.length,Et!==0&&(de=this.sourceBuffer.buffered.start(0),Ve=zt,Ve-de>4&&this.sourceBuffer.remove(de,Ve-3)),Pr(1e3);else throw hi}}},M=()=>{L&&J&&($([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(F)]),D(L,function(){L=null,T()}))},se=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),Be=j=>{d()&&h(se(j),(ce,de)=>{if(d()){if(de/=1e3,L=ce,F=j,n=j.startTS,de){let Ve=Math.min(10,j.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ve:Ve}M()}},()=>this._handleNetworkError())},It=j=>{d()&&(Ki(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(j),!1)))},xr=j=>{d()&&(e.cachedHeader=j,D(j,()=>{J=!0,M()}))};s=!0,B.seek(j=>{if(d()){if(R=le(),!j){A();return}q=j,!P$(I)||j.startTS>I?Be(j):(F=j,T())}},I),e.cachedHeader?xr(e.cachedHeader):p(e.headerUrl,xr,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),tn(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ki(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return tn(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,f;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),f=d/this.bitrate,h>10&&f>.8||h>15&&f>.5||h>20&&f>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let f=le();if(this.chunkRateEstimator.addInterval(p,f,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:f-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&ul(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=le();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ri(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(rn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;xe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},A$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var zg=_(Ur(),1);import{debounce as L$,filter as Wg,fromEvent as M$,interval as C$,isHigher as D$,isInvariantQuality as O$,isLower as B$,merge as V$,Subject as Yg,Subscription as _$}from"@vkontakte/videoplayer-shared/es2015";var dl=class{constructor(){this.onDroopedVideoFramesLimit$=new Yg;this.subscription=new _$;this.playing=!1;this.tracks=[];this.forceChecker$=new Yg;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&&!O$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&D$(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(M$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=C$(this.droppedFramesChecker.checkTime).pipe(Wg(()=>this.playing),Wg(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(L$(this.droppedFramesChecker.checkTime)),r=V$(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,zg.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>B$(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},an=dl;import{map as N$,Observable as F$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as q$}from"@vkontakte/videoplayer-shared/es2015";var Xi=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var U$=(a,e)=>new F$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Xi()))},x(x({},r),e));i.observe(a);let s=q$(document,"visibilitychange").pipe(N$(n=>!document.hidden||Xi())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ue=U$;var J$=["paused","playing","ready"],X$=["paused","playing","ready"],Zi=class{constructor(e){this.subscription=new Y$;this.videoState=new O("stopped");this.representations$=new hl([]);this.textTracksManager=new Fe;this.droppedFramesManager=new an;this.maxSeekBackTime$=new hl(1/0);this.zeroTime$=new hl(void 0);this.liveOffset=new ft;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:Xg.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=_t(u.name))!=null?r:K$(u.video),d=u.bitrate/1e3,p=x({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),pl(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,fl.default)(X$,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,fl.default)(J$,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(fe(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(fe(this.params.source.url,u))}return;default:return Kg(e)}};this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:Xg.WTF,message:"DashLiveProvider internal logic error",thrown:i})};ev(this.videoState.stateChangeStarted$.pipe(sn(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(sn(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=Ee(this.video);this.subscription.add(this.representations$.pipe(sn(i=>i.map(({track:s})=>s)),Zg(i=>!!i.length),W$()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(G$(),sn(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(H$({zeroTime:this.zeroTime$.pipe(Zg(pl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(nt(this.video,this.params.desiredState.isLooped,t)).add(Ie(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ne(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ue(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&z$(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return Kg(i.to)}},t)).add(ev(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Q$(["init"])).pipe(j$(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Te(this.video)}createLiveDashPlayer(){let e=new Ji({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,f;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&pl(t)?t:Ft(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(f=e.find(({track:g})=>g.id===s))==null?void 0:f.representation;Jg(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;Jg(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(fe(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var tv=Zi;var Ny=_(Je(),1);var ut=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as FC,assertNonNullable as qC,debounce as UC,ErrorCategory as Zl,filter as By,filterChanged as qa,fromEvent as HC,isNonNullable as Vy,map as ec,merge as Mn,observableFrom as tc,once as _y,Subscription as jC}from"@vkontakte/videoplayer-shared/es2015";var nn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ii=class extends nn{constructor(){super(),this.listeners||nn.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 ii,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ea.prototype[Symbol.toStringTag]="AbortController",ii.prototype[Symbol.toStringTag]="AbortSignal");function on(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 ml(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!on({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,f)=>{c.addEventListener("abort",()=>f(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ta=on({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),rv=ta?ml({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,bt=ta?rv.fetch:window.fetch,pF=ta?rv.Request:window.Request,De=ta?ea:window.AbortController,hF=ta?ii:window.AbortSignal;var Kl=_(gl(),1);var bn=_(ti(),1);var gt=()=>window.ManagedMediaSource||window.MediaSource,un=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Iv=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Ev=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as vn,clientChecker as gn}from"@vkontakte/videoplayer-shared/es2015";var He=document.createElement("video"),EL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',xL='video/mp4; codecs="hev1.1.6.L93.B0"',Dv='video/webm; codecs="vp09.00.10.08"',Ov='video/webm; codecs="av01.0.00M.08"',PL='audio/mp4; codecs="mp4a.40.2"',wL='audio/webm; codecs="opus"',xv,Pv,ra={mms:un(),mse:Iv(),hls:!!((xv=He.canPlayType)!=null&&xv.call(He,"application/x-mpegurl")||(Pv=He.canPlayType)!=null&&Pv.call(He,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},wv,Av,Pe={mp4:!!((wv=He.canPlayType)!=null&&wv.call(He,"video/mp4")),webm:!!((Av=He.canPlayType)!=null&&Av.call(He,"video/webm")),cmaf:!0},cn,kv,dn,Rv,pn,$v,hn,Lv,fn,Mv,mn,Cv,we={h264:!!((kv=(cn=gt())==null?void 0:cn.isTypeSupported)!=null&&kv.call(cn,EL)),h265:!!((Rv=(dn=gt())==null?void 0:dn.isTypeSupported)!=null&&Rv.call(dn,xL)),vp9:!!(($v=(pn=gt())==null?void 0:pn.isTypeSupported)!=null&&$v.call(pn,Dv)),av1:!!((Lv=(hn=gt())==null?void 0:hn.isTypeSupported)!=null&&Lv.call(hn,Ov)),aac:!!((Mv=(fn=gt())==null?void 0:fn.isTypeSupported)!=null&&Mv.call(fn,PL)),opus:!!((Cv=(mn=gt())==null?void 0:mn.isTypeSupported)!=null&&Cv.call(mn,wL))},ai=(we.h264||we.h265)&&we.aac,hr,AL=()=>k(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(C(x({},a),{video:C(x({},a.video),{contentType:Ov})})),window.navigator.mediaCapabilities.decodingInfo(C(x({},a),{video:C(x({},a.video),{contentType:Dv})}))]);hr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{AL()}catch(a){console.error(a)}var si=ra.hls&&Pe.mp4,Bv=()=>Object.keys(we).filter(a=>we[a]),Vv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ra.mse&&(!r||!!window.MediaStreamTrack)||ra.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&Pe.mp4&&ai;case"DASH_WEBM":return i&&Pe.webm&&we.vp9&&we.opus;case"DASH_WEBM_AV1":return i&&Pe.webm&&we.av1&&we.opus;case"DASH_STREAMS":return i&&(Pe.mp4&&ai||Pe.webm&&(we.vp9||we.av1)&&(we.opus||we.aac));case"DASH_LIVE":return i&&Pe.mp4&&ai;case"DASH_LIVE_CMAF":return i&&Pe.mp4&&ai&&Pe.cmaf;case"DASH_ONDEMAND":return i&&Pe.mp4&&ai;case"HLS":case"HLS_ONDEMAND":return si||e&&i&&Pe.mp4&&ai;case"HLS_LIVE":case"HLS_LIVE_CMAF":return si;case"MPEG":return Pe.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ra.webrtc&&ra.ws&&we.h264&&(Pe.mp4||Pe.webm);default:return vn(s)}})},ln=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return hr?hr[t].smooth?[t,e]:hr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return hr?hr[t].powerEfficient?[t,e]:hr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:vn(a)}return[e,t]},_v=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...ln(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(gn.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...ln(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...ln(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...ln(a),...i,"HLS","HLS_ONDEMAND"];default:vn(e)}return si?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Nv=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=gn.isMac&&gn.isSafari;if(gn.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:vn(a)}else si&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},vl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Fv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,bn.default)(t.value.split("."),0)}for(let t of a){let r=(0,bn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,bn.default)(e.value.split("."),0)};var oS=_(nS(),1);import{ErrorCategory as aa}from"@vkontakte/videoplayer-shared/es2015";var uS=a=>{if(!a)return{id:"EmptyResponse",category:aa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:aa.NETWORK,message:`UV Error ${a}`};let e=(0,oS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:aa.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:aa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:aa.PARSER,message:"Response is valid XML, but parser failed"}};var qt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as Yl,assertNonNullable as yr,clientChecker as yC,combine as ci,ErrorCategory as Gt,filter as Va,filterChanged as wn,flattenObject as _a,fromEvent as Tr,getTraceSubscriptionMethod as TC,interval as zl,isNonNullable as Ay,map as Na,merge as Ir,now as IC,Subject as ky,Subscription as Ry,tap as EC,throttle as xC,ValueSubject as re}from"@vkontakte/videoplayer-shared/es2015";var yn=_(Je(),1),ui=_(ti(),1),Tn=_(gl(),1);var jL=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},GL=a=>window.clearTimeout(a),lS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),cS=!lS(window.requestIdleCallback)||!lS(window.cancelIdleCallback),El=cS?jL:window.requestIdleCallback,sa=cS?GL:window.cancelIdleCallback;var Sy=_(Ys(),1);import{assertNever as QL,ErrorCategory as dS,clientChecker as xl,Subject as pS}from"@vkontakte/videoplayer-shared/es2015";var WL=18,hS=!1;try{hS=xl.isSafari&&!!xl.macVersion&&xl.macVersion<=WL}catch(a){console.error(a)}var Pl=class{constructor(e){this.bufferFull$=new pS;this.error$=new pS;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:dS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return k(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return k(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return k(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};hS&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:dS.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:s}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){let{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:QL(t)}}},fS=Pl;var wl=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 br,assertNonNullable as je,clientChecker as lC,ErrorCategory as Ht,fromEvent as Hl,getExponentialDelay as jl,isNonNullable as $a,isNullable as ke,now as Sn,once as cC,Subject as dC,Subscription as pC,ValueSubject as gr}from"@vkontakte/videoplayer-shared/es2015";var Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var ni=class extends Q{};var na=class extends Q{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var oa=class extends Q{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ua=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var X=class extends Q{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var la=class extends X{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 ca=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var da=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var fr=class extends X{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var pa=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ha=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var fa=class extends X{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 X{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ba=class extends X{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ga=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var va=class extends X{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 Sa=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ya=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ta=class extends X{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ia=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ea=class extends X{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 xa=class extends X{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Pa=class extends X{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var zL={ftyp:oa,moov:ua,mvhd:la,moof:ca,mdat:da,sidx:fr,trak:pa,mdia:ga,mfhd:Ta,tkhd:va,traf:Ia,tfhd:Ea,tfdt:xa,trun:Pa,minf:Sa,sv3d:ha,st3d:fa,prhd:ma,proj:ya,equi:ba,uuid:na,unknown:ni},vt=class a{constructor(e={}){this.options=x({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=zL[e];return r?new r(t,new a):new ni(t,new a)}};var Ut=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var JL=new TextDecoder("ascii"),XL=a=>JL.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",ZL=a=>{let e=new fr(a,new vt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},eM=(a,e)=>{let r=new vt().parse(a),i=new Ut(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},tM=a=>{let t=new vt().parse(a),r=new Ut(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},rM=a=>{var i;let t=new vt().parse(a);return(i=new Ut(t).find("sidx"))==null?void 0:i.timescale},iM=(a,e)=>{let r=new vt().parse(a),s=new Ut(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},aM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new vt().parse(a),i=new Ut(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},mS={validateData:XL,parseInit:aM,getIndexRange:()=>{},parseSegments:ZL,parseFeedableSegmentChunk:eM,getChunkEndTime:iM,getServerLatencyTimestamps:tM,getTimescaleFromIndex:rM};var Aa=_(Je(),1);import{assertNonNullable as kl,isNonNullable as SS,isNullable as nM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as sM}from"@vkontakte/videoplayer-shared/es2015";var bS={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"}},gS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=wa(a,t),i=r in bS,s=i?bS[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=wa(u),d=l*it(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},wa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*it(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*it(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*it(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 wa(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:sM(e)}},mr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=gS(r);if(!e(i))return;i.type==="master"&&mr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},vS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=gS(a);return mr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=Ze(o,n):s===17026?t=Ze(o,n):s===17029&&(r=Ze(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var yS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],oM=[231,22612,22743,167,171,163,160,175],uM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return mr(a,({tag:p,type:h,value:f,valueSize:b})=>{if(p===21419){let g=Ze(f,h);l=wa(g)}else p!==21420&&(l=void 0);return p===408125543?(e=f.byteOffset,t=f.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=Ze(f,h):p===17545?i=Ze(f,h):p===21420&&l===475249515?u=Ze(f,h):p===374648427?mr(f,({tag:g,type:S,value:v})=>g===30321?(c=Ze(v,S)===1,!1):!0):s&&n&&(0,Aa.default)(yS,p)&&(o=!0),!o}),kl(e,"Failed to parse webm Segment start"),kl(t,"Failed to parse webm Segment end"),kl(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},lM=a=>{if(nM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},cM=(a,e)=>{let t=!1,r=!1,i=o=>SS(o.time)&&SS(o.position),s=[],n;return mr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=Ze(l,u));break;case 183:break;case 241:n&&(n.position=Ze(l,u));break;default:t&&(0,Aa.default)(yS,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},dM=a=>{let e=0,t=!1;try{mr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Aa.default)(oM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Aa.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},TS={validateData:vS,parseInit:uM,getIndexRange:lM,parseSegments:cM,parseFeedableSegmentChunk:dM};var ka=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return TS;case"mp4":return mS}}throw new ReferenceError(`Unsupported mime type ${a}`)};var Fl=_(qS(),1),hy=_(Ur(),1),fy=_(iy(),1),my=_(ti(),1),ql=_(Zr(),1);var ay=_(Je(),1),Dl=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,ay.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as uC,isNullable as dy}from"@vkontakte/videoplayer-shared/es2015";var sy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var ny=a=>{var e;try{let t=nC(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function nC(){let a="(?<extlang>(?:[a-z]{3}(?:-[a-z]{3}){0,2}))",e="x(?:-[a-z0-9]{1,8})+",c=`^(?:(?<langtag>${`
62
+ [selected audio track] ${m==null?void 0:m.id}
63
+ `}),m&&Wg(i,u,m,o)};var ue=a=>new URL(a).hostname;import{assertNever as av,assertNonNullable as sv,combine as Y$,debounce as z$,ErrorCategory as nv,filter as ov,filterChanged as K$,isNonNullable as pl,map as an,merge as uv,observableFrom as X$,once as J$,Subscription as Z$,ValueSubject as hl,videoQualityToHeight as eL,videoSizeToQuality as tL}from"@vkontakte/videoplayer-shared/es2015";var Kg=_(Xe(),1);var zg=a=>{if(a instanceof DOMException&&(0,Kg.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"))},Pe=(a,e)=>A(void 0,null,function*(){let t=a.muted;try{yield a.play()}catch(r){if(!zg(r))return!1;if(e&&e(),t)return console.warn(r),!1;a.muted=!0;try{yield a.play()}catch(i){return zg(i)&&(a.muted=!1,console.warn(i)),!1}}return!0});import{isNonNullable as en,isNullable as $$,assertNonNullable as Ki}from"@vkontakte/videoplayer-shared/es2015";var Jg=_(Jr(),1);import{isNonNullable as Xg,assertNonNullable as Zs,now as k$}from"@vkontakte/videoplayer-shared/es2015";function le(){return k$()}function ul(a){return le()-a}function ll(a){let e=a.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,i=n=>r.test(n);return{resolve:(n,o,u=!1)=>{i(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let l=n.indexOf("?")>-1?"&":"?";return u&&(n+=l+"lowLat=1",l="&"),o&&(n+=l+"_rnd="+Math.floor(999999999*Math.random())),n}}}function Zg(a,e,t){let r=(...i)=>{t.apply(null,i),a.removeEventListener(e,r)};a.addEventListener(e,r)}function ti(a,e,t,r){let i=window.XMLHttpRequest,s,n,o,u=!1,l=0,c,d,p=!1,h="arraybuffer",m=7e3,b=2e3,g=()=>{if(u)return;Zs(c);let R=ul(c),H;if(R<b){H=b-R,setTimeout(g,H);return}b*=2,b>m&&(b=m),n&&n.abort(),n=new i,L()},v=R=>(s=R,q),S=R=>(d=R,q),y=()=>(h="json",q),I=()=>{if(!u){if(--l>=0){g(),r&&r();return}u=!0,d&&d(),t&&t()}},w=R=>(p=R,q),L=()=>{c=le(),n=new i,n.open("get",a);let R=0,H,N=0,W=()=>(Zs(c),Math.max(c,Math.max(H||0,N||0)));if(s&&n.addEventListener("progress",k=>{let T=le();s.updateChunk&&k.loaded>R&&(s.updateChunk(W(),k.loaded-R),R=k.loaded,H=T)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>I())),n.addEventListener("load",()=>{if(u)return;Zs(n);let k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&s){let T=n.response.byteLength-R;T&&s.updateChunk&&s.updateChunk(W(),T)}n.responseType==="json"&&!(0,Jg.default)(n.response).length?I():(d&&d(),e(n.response))}else I()}),n.addEventListener("error",()=>{I()}),p){let k=()=>{Zs(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(N=le(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=h,n.send(),q},q={withBitrateReporting:v,withParallel:w,withJSONResponse:y,withRetryCount:R=>(l=R,q),withRetryInterval:(R,H)=>(Xg(R)&&(b=R),Xg(H)&&(m=H),q),withTimeout:R=>(o=R,q),withFinally:S,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,d&&d()}};return q}var Yi=class{constructor(e){this.intervals=[];this.currentRate=0;this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;let e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-500;if(t-e>2e3){let r=0,i=0;for(;this.intervals.length>0;){let s=this.intervals[0];if(s.end<=t)r+=s.end-s.start,i+=s.bytes,this.intervals.splice(0,1);else{if(s.start>=t)break;{let n=t-s.start,o=s.end-s.start;r+=n;let u=s.bytes*n/o;i+=u,s.start=t,s.bytes-=u}}}if(i>0&&r>0){let s=i*8/(r/1e3);return this._updateRate(s),this.logger(`rate updated, new=${Math.round(s/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(i)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>100&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};var ev=_(Jr(),1);var zi=class{constructor(e,t,r,i,s){this.pendingQueue=[];this.activeRequests={};this.completeRequests={};this.averageSegmentDuration=2e3;this.lastPrefetchStart=0;this.throttleTimeout=null;this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=i,this.logger=s}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){let t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){let r=le(),i=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},s=u=>{e._complete=1,e._responseData=u,e._downloadTime=le()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ti(t,s,()=>i("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=le()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){let e=this._getParallelRequestCount(),t=le();if(Object.keys(this.activeRequests).length>=e)return!1;let r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){let e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){(0,ev.default)(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,i){let s={};return s.send=()=>{let n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=r,n._retryCB=i,n._finallyCB=s._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(n._errorMsg)),s._finallyCB&&s._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{let o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(s,e)}},s._cb=t,s._errorCB=r,s._retryCB=i,s.abort=function(){s.request&&s.request.abort()},s.withFinally=n=>(s._finallyCB=n,s),s}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}};import{Subject as L$}from"@vkontakte/videoplayer-shared/es2015";var tn=1e4,cl=3;var M$=6e4,D$=10,C$=1,O$=500,Xi=class{constructor(e){this.paused=!1;this.autoQuality=!0;this.maxAutoQuality=void 0;this.buffering=!0;this.destroyed=!1;this.videoPlayStarted=!1;this.lowLatency=!1;this.bitrate=0;this.manifest=[];this.sourceBuffer=0;this.bufferStates=[];this.sourceJitter=-1;this.params=e,this.soundProhibitedEvent$=new L$,this.chunkRateEstimator=new Yi(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ll(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(){this.paused=!1;let e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement():this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ll(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){let e=this.params.videoElement,t=0,r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){let{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)==null?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{let r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){let{logger:e,videoElement:t}=this.params,r=t.buffered.length,i;r!==0&&(i=t.buffered.start(r-1),t.currentTime<i&&(e("Fixup stall"),t.currentTime=i))}_selectQuality(e){let{videoElement:t}=this.params,r,i,s,n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)s=this.manifest[o],!(this.maxAutoQuality&&s.video.height>this.maxAutoQuality)&&(s.bitrate<e&&n>Math.min(s.video.height,s.video.width)?(!i||s.bitrate>i.bitrate)&&(i=s):(!r||r.bitrate>s.bitrate)&&(r=s));return i||r}shouldPlay(){if(this.paused)return!1;let t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||en(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){let{logger:r,videoElement:i,playerCallback:s}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),i.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,i.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});let n=()=>{Zg(i,"progress",()=>{i.buffered.length?(i.currentTime=i.buffered.start(0),s({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new zi(cl,tn,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){let{logger:t,videoElement:r,playerCallback:i}=this.params,s=!1,n=null,o=null,u=null,l=null,c=!1,d=()=>{let I=s&&(!c||c===this.rep);return I||t("Not running!"),I},p=(I,w,L)=>{u&&u.abort(),u=ti(this.urlResolver.resolve(I,!1),w,L,()=>this._retryCallback()).withTimeout(tn).withBitrateReporting(this.bitrateSwitcher).withRetryCount(cl).withFinally(()=>{u=null}).send()},h=(I,w,L)=>{Ki(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(I,!1),w,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=I=>{let w=r.playbackRate;r.playbackRate!==I&&(t(`Playback rate switch: ${w}=>${I}`),r.playbackRate=I)},b=I=>{this.lowLatency=I,t(`lowLatency changed to ${I}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let I=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}let L=le()-1e4,B=0;for(let M=0;M<this.bufferStates.length;M++){let F=this.bufferStates[M];I=Math.min(I,F.buf),F.ts<L&&B++}this.bufferStates.splice(0,B),t(`update playback rate; minBuffer=${I} drop=${B} jitter=${this.sourceJitter}`);let X=I-C$;this.sourceJitter>=0?X-=this.sourceJitter/2:this.sourceJitter-=1,X>3?m(1.15):X>1?m(1.1):X>.3?m(1.05):m(1)}},v=I=>{let w,L=()=>w&&w.start?w.start.length:0,B=k=>w.start[k]/1e3,X=k=>w.dur[k]/1e3,M=k=>w.fragIndex+k,F=(k,T)=>({chunkIdx:M(k),startTS:B(k),dur:X(k),discontinuity:T}),q=()=>{let k=0;if(w&&w.dur){let T=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,C=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,D=T;this.sourceJitter>1&&(D+=this.sourceJitter-1);let se=w.dur.length-1;for(;se>=0&&(D-=w.dur[se],!(D<=0));--se);k=Math.min(se,w.dur.length-1-C),k=Math.max(k,0)}return F(k,!0)},R=k=>{let T=L();if(!(T<=0)){if(en(k)){for(let C=0;C<T;C++)if(B(C)>k)return F(C)}return q()}},H=k=>{let T=L(),C=k?k.chunkIdx+1:0,D=C-w.fragIndex;if(!(T<=0)){if(!k||D<0||D-T>D$)return t(`Resync: offset=${D} bChunks=${T} chunk=`+JSON.stringify(k)),q();if(!(D>=T))return F(C-w.fragIndex,!1)}},N=(k,T,C)=>{l&&l.abort(),l=ti(this.urlResolver.resolve(k,!0,this.lowLatency),T,C,()=>this._retryCallback()).withTimeout(tn).withRetryCount(cl).withFinally(()=>{l=null}).withJSONResponse().send()};return{seek:(k,T)=>{N(I,C=>{if(!d())return;w=C;let D=!!w.lowLatency;D!==this.lowLatency&&b(D);let se=0;for(let Ve=0;Ve<w.dur.length;++Ve)se+=w.dur[Ve];se>0&&(Ki(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/w.dur.length)),i({name:"index",zeroTime:w.zeroTime,shiftDuration:w.shiftDuration}),this.sourceJitter=w.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,w.jitter/1e3)):1,k(R(T))},()=>this._handleNetworkError())},nextChunk:H}},S=()=>{s=!1,o&&o.abort(),u&&u.abort(),l&&l.abort(),Ki(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:I=>{let{videoElement:w,logger:L}=this.params,B=v(e.jidxUrl),X,M,F,q,R=0,H,N,W,k=()=>{H&&(clearTimeout(H),H=void 0);let j=Math.max(O$,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ce=R+j,de=le(),Be=Math.min(1e4,ce-de);R=de;let Et=()=>{l||d()&&B.seek(()=>{d()&&(R=le(),T(),k())})};Be>0?H=window.setTimeout(()=>{this.paused?k():Et()},Be):Et()},T=()=>{let j;for(;j=B.nextChunk(q);)q=j,It(j);let ce=B.nextChunk(F);if(ce){if(F&&ce.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?k():(S(),this._initPlayerWith(e));return}Ve(ce)}else k()},C=(j,ce)=>{if(!d()||!this.sourceBuffer)return;let de,Be,Et,xr=xt=>{window.setTimeout(()=>{d()&&C(j,ce)},xt)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),xr(100);else{let xt=le(),zt=w.currentTime;!this.paused&&w.buffered.length>1&&N===zt&&xt-W>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),N!==zt&&(N=zt,W=xt);let Pr=this._getBufferSizeSec();if(Pr>30)L(`Buffered ${Pr} seconds; delaying appendBuffer`),xr(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:xt,buf:Pr}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ce&&ce()}catch(hi){if(hi.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Et=this.sourceBuffer.buffered.length,Et!==0&&(de=this.sourceBuffer.buffered.start(0),Be=zt,Be-de>4&&this.sourceBuffer.remove(de,Be-3)),xr(1e3);else throw hi}}},D=()=>{M&&X&&(L([`Appending chunk, sz=${M.byteLength}:`,JSON.stringify(F)]),C(M,function(){M=null,T()}))},se=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),Ve=j=>{d()&&h(se(j),(ce,de)=>{if(d()){if(de/=1e3,M=ce,F=j,n=j.startTS,de){let Be=Math.min(10,j.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Be:Be}D()}},()=>this._handleNetworkError())},It=j=>{d()&&(Ki(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(j),!1)))},Er=j=>{d()&&(e.cachedHeader=j,C(j,()=>{X=!0,D()}))};s=!0,B.seek(j=>{if(d()){if(R=le(),!j){k();return}q=j,!$$(I)||j.startTS>I?Ve(j):(F=j,T())}},I),e.cachedHeader?Er(e.cachedHeader):p(e.headerUrl,Er,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},c}_switchToQuality(e){let{logger:t,playerCallback:r}=this.params,i;e.bitrate!==this.bitrate&&(this.rep&&(i=this.rep.getTimestampSec(),en(i)&&(i+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,Ki(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(i),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return en(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){let{logger:e,playerCallback:t}=this.params,r=d=>{if(!this.autoQuality)return;let p,h,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&d<this.bitrate&&(h=this._getBufferSizeSec(),m=d/this.bitrate,h>10&&m>.8||h>15&&m>.5||h>20&&m>.3)){e(`Not switching: buffer=${Math.floor(h)}; bitrate=${this.bitrate}; newRate=${Math.floor(d)}`);return}p=this._selectQuality(d),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${d}`)},s={updateChunk:(p,h)=>{let m=le();if(this.chunkRateEstimator.addInterval(p,m,h)){let g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:h,duration:m-p,speed:g}),!0}},get:()=>{let p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}},n=-1/0,o,u=!0,l=()=>{let d=s.get();if(d&&o&&this.autoQuality){if(u&&d>o&&ul(n)<3e4)return;r(d)}u=this.autoQuality};return{updateChunk:(d,p)=>{let h=s.updateChunk(d,p);return h&&l(),h},notifySwitch:d=>{let p=le();d<o&&(n=p),o=d}}}_fetchManifest(e,t,r){this.manifestRequest=ti(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(tn).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(){let{videoElement:e}=this.params;Pe(e,()=>{this.soundProhibitedEvent$.next()}).then(t=>{t||(this.params.liveOffset.pause(),this.params.videoState.setState("paused"))})}_handleManifestUpdate(e){let{logger:t,playerCallback:r,videoElement:i}=this.params,s=n=>{let o=[];return n!=null&&n.length?(n.forEach((u,l)=>{u.video&&i.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=l,o.push(u))}),o.sort(function(u,l){return u.video&&l.video?l.video.height-u.video.height:l.bitrate-u.bitrate}),o):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=s(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},M$))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}};var iv=_(qr(),1);import{debounce as V$,filter as tv,fromEvent as B$,interval as _$,isHigher as N$,isInvariantQuality as F$,isLower as q$,merge as U$,Subject as rv,Subscription as H$}from"@vkontakte/videoplayer-shared/es2015";var dl=class{constructor(){this.onDroopedVideoFramesLimit$=new rv;this.subscription=new H$;this.playing=!1;this.tracks=[];this.forceChecker$=new rv;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&&!F$(e.quality)&&this.onChangeQuality(e.quality)};this.checkDroppedFrames=()=>{var n;let{totalVideoFrames:e,droppedVideoFrames:t}=this.video.getVideoPlaybackQuality(),r=e-this.prevTotalVideoFrames,i=t-this.prevDroppedVideoFrames,s=1-(r-i)/r;!isNaN(s)&&s>0&&this.log({message:`[dropped]. current dropped percent: ${s}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(s)&&s>=this.droppedFramesChecker.percentLimit&&N$(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(B$(this.video,"resize").subscribe(this.handleChangeVideoQuality));let e=_$(this.droppedFramesChecker.checkTime).pipe(tv(()=>this.playing),tv(()=>{let i=!!this.isForceCheckCounter;return i&&(this.isForceCheckCounter-=1),!i})),t=this.forceChecker$.pipe(V$(this.droppedFramesChecker.checkTime)),r=U$(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;let{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var r,i;let t=(i=(r=(0,iv.default)(this.limitCounts).filter(([,s])=>s>=this.droppedFramesChecker.countLimit).sort(([s],[n])=>q$(s,n)?-1:1))==null?void 0:r[0])==null?void 0:i[0];return e!=null?e:t}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}},rn=dl;import{map as j$,Observable as G$}from"@vkontakte/videoplayer-shared/es2015";import{fromEvent as Q$}from"@vkontakte/videoplayer-shared/es2015";var Ji=()=>{var a;return!!((a=window.documentPictureInPicture)!=null&&a.window)||!!document.pictureInPictureElement};var W$=(a,e)=>new G$(t=>{if(!window.IntersectionObserver)return;let r={root:null},i=new IntersectionObserver((n,o)=>{n.forEach(u=>t.next(u.isIntersecting||Ji()))},E(E({},r),e));i.observe(a);let s=Q$(document,"visibilitychange").pipe(j$(n=>!document.hidden||Ji())).subscribe(n=>t.next(n));return()=>{i.unobserve(a),s.unsubscribe}}),Ue=W$;var rL=["paused","playing","ready"],iL=["paused","playing","ready"],Zi=class{constructor(e){this.subscription=new Z$;this.videoState=new O("stopped");this.representations$=new hl([]);this.droppedFramesManager=new rn;this.maxSeekBackTime$=new hl(1/0);this.zeroTime$=new hl(void 0);this.liveOffset=new ft;this._dashCb=e=>{var t,r,i,s;switch(e.name){case"buffering":{let n=e.isBuffering;this.params.output.isBuffering$.next(n);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,category:nv.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{let n=e.manifest,o=[];for(let u of n){let l=(t=u.name)!=null?t:u.index.toString(10),c=(r=_t(u.name))!=null?r:tL(u.video),d=u.bitrate/1e3,p=E({},u.video);if(!c)continue;let h={id:l,quality:c,bitrate:d,size:p};o.push({track:h,representation:u})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),((i=this.videoState.getTransition())==null?void 0:i.to)==="manifest_ready"&&this.videoState.setState("manifest_ready");break}case"qualitySwitch":{let n=e.quality,o=(s=this.representations$.getValue().find(({representation:u})=>u===n))==null?void 0:s.track;this.params.output.hostname$.next(new URL(n.headerUrl,this.params.source.url).hostname),pl(o)&&this.params.output.currentVideoTrack$.next(o);break}case"bandwidth":{let{size:n,duration:o}=e;this.params.dependencies.throughputEstimator.addRawSpeed(n,o);break}case"index":{this.maxSeekBackTime$.next(e.shiftDuration||0),this.zeroTime$.next(e.zeroTime);break}}};this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(t)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(s)};`}),r==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"));return}if(t)return;let n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((0,ml.default)(iL,e)&&(n||o)){this.prepare();return}if((i==null?void 0:i.to)!=="paused"&&s.state==="requested"&&(0,ml.default)(rL,e)){this.seek(s.position-this.liveOffset.getTotalPausedTime());return}switch(e){case"stopped":this.videoState.startTransitionTo("manifest_ready"),this.dash.attachSource(me(this.params.source.url));return;case"manifest_ready":this.videoState.startTransitionTo("ready"),this.prepare();break;case"ready":if(r==="paused")this.videoState.setState("paused");else if(r==="playing"){this.videoState.startTransitionTo("playing");let u=i==null?void 0:i.from;u&&u==="ready"&&this.dash.catchUp(),this.dash.play()}return;case"playing":r==="paused"&&(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.dash.pause());return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let u=this.liveOffset.getTotalOffset();u>=this.maxSeekBackTime$.getValue()&&(u=0,this.liveOffset.resetTo(u)),this.liveOffset.resume(),this.params.output.position$.next(-u/1e3),this.dash.reinit(me(this.params.source.url,u))}return;default:return av(e)}};this.textTracksManager=new Fe(e.source.url),this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");let t=i=>{e.output.error$.next({id:"DashLiveProvider",category:nv.WTF,message:"DashLiveProvider internal logic error",thrown:i})};uv(this.videoState.stateChangeStarted$.pipe(an(i=>({transition:i,type:"start"}))),this.videoState.stateChangeEnded$.pipe(an(i=>({transition:i,type:"end"})))).subscribe(({transition:i,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(i)}`})}),this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.subscription.add(this.dash.soundProhibitedEvent$.subscribe(this.params.output.soundProhibitedEvent$)),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);let r=xe(this.video);this.subscription.add(this.representations$.pipe(an(i=>i.map(({track:s})=>s)),ov(i=>!!i.length),J$()).subscribe(i=>this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:i}))),this.subscription.add(r.canplay$.subscribe(()=>{var i;((i=this.videoState.getTransition())==null?void 0:i.to)==="ready"&&this.videoState.setState("ready")},t)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused")},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state==="applying"&&this.params.output.seekedEvent$.next(),this.videoState.setState("playing")},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(K$(),an(i=>-i/1e3)).subscribe(this.params.output.duration$)).add(Y$({zeroTime:this.zeroTime$.pipe(ov(pl)),position:r.timeUpdate$}).subscribe(({zeroTime:i,position:s})=>this.params.output.liveTime$.next(i+s*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Ee(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ne(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.loadedMetadata$.subscribe(this.params.output.loadedMetadataEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(Ue(this.video).subscribe(this.params.output.elementVisible$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:i}})=>{let s=i&&eL(i);this.dash.setMaxAutoQuality(s),this.params.output.autoVideoTrackLimits$.next({max:i})})).add(this.videoState.stateChangeEnded$.subscribe(i=>{var s;switch(i.to){case"stopped":this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState("stopped");break;case"manifest_ready":case"ready":((s=this.params.desiredState.playbackState.getTransition())==null?void 0:s.to)==="ready"&&this.params.desiredState.playbackState.setState("ready");break;case"paused":this.params.desiredState.playbackState.setState("paused");break;case"playing":this.params.desiredState.playbackState.setState("playing");break;default:return av(i.to)}},t)).add(uv(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,X$(["init"])).pipe(z$(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),Ie(this.video)}createLiveDashPlayer(){let e=new Xi({videoElement:this.video,videoState:this.videoState,liveOffset:this.liveOffset,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var l,c,d,p,h,m;let e=this.representations$.getValue(),t=(c=(l=this.params.desiredState.videoTrack.getTransition())==null?void 0:l.to)!=null?c:this.params.desiredState.videoTrack.getState(),r=(p=(d=this.params.desiredState.autoVideoTrackSwitching.getTransition())==null?void 0:d.to)!=null?p:this.params.desiredState.autoVideoTrackSwitching.getState(),i=!r&&pl(t)?t:Ft(e.map(({track:b})=>b),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),s=i==null?void 0:i.id,n=this.params.desiredState.videoTrack.getTransition(),o=(h=this.params.desiredState.videoTrack.getState())==null?void 0:h.id,u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&(n||s!==o)&&this.setVideoTrack(i),u&&this.setAutoQuality(r),n||u||s!==o){let b=(m=e.find(({track:g})=>g.id===s))==null?void 0:m.representation;sv(b,"Representations missing"),this.dash.startPlay(b,r)}}setVideoTrack(e){var r;let t=(r=this.representations$.getValue().find(({track:i})=>i.id===e.id))==null?void 0:r.representation;sv(t,`No such representation ${e.id}`),this.dash.switchByName(t.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=s<=this.maxSeekBackTime$.getValue()?s:0;this.params.output.position$.next(e/1e3),this.dash.reinit(me(this.params.source.url,n)),i&&this.dash.pause(),this.liveOffset.resetTo(n,i)}};var lv=Zi;var jy=_(Xe(),1);var lt=(a,e)=>{let t=0;for(let r=0;r<a.length;r++){let i=a.start(r)*1e3,s=a.end(r)*1e3;i<=e&&e<=s&&(t=s)}return Math.max(t-e,0)};import{assertNever as GD,assertNonNullable as QD,debounce as WD,ErrorCategory as ic,filter as qy,filterChanged as Fa,fromEvent as YD,isNonNullable as Uy,map as ac,merge as Ln,observableFrom as sc,once as Hy,Subscription as zD}from"@vkontakte/videoplayer-shared/es2015";var sn=class{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;let r=this.listeners[e];for(let i=0,s=r.length;i<s;i++)if(r[i].callback===t){r.splice(i,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;let r=this.listeners[e.type].slice();for(let i=0,s=r.length;i<s;i++){let n=r[i];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}},ri=class extends sn{constructor(){super(),this.listeners||sn.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 ri,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(i){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(i){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ea.prototype[Symbol.toStringTag]="AbortController",ri.prototype[Symbol.toStringTag]="AbortSignal");function nn(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 fl(a){typeof a=="function"&&(a={fetch:a});let{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i=!1}=a;if(!nn({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:i}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||i)&&(s=function(l,c){let d;c&&c.signal&&(d=c.signal,delete c.signal);let p=new t(l,c);return d&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:d}),p},s.prototype=t.prototype);let n=e;return{fetch:(u,l)=>{let c=s&&s.prototype.isPrototypeOf(u)?u.signal:l?l.signal:void 0;if(c){let d;try{d=new DOMException("Aborted","AbortError")}catch(h){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);let p=new Promise((h,m)=>{c.addEventListener("abort",()=>m(d),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([p,n(u,l)])}return n(u,l)},Request:s}}var ta=nn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),cv=ta?fl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ze=ta?cv.fetch:window.fetch,EF=ta?cv.Request:window.Request,fe=ta?ea:window.AbortController,xF=ta?ri:window.AbortSignal;var Zl=_(gl(),1);var fn=_(ei(),1);var gt=()=>window.ManagedMediaSource||window.MediaSource,on=()=>{var a,e;return!!(window.ManagedMediaSource&&((e=(a=window.ManagedSourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},$v=()=>{var a,e;return!!(window.MediaSource&&((e=(a=window.SourceBuffer)==null?void 0:a.prototype)!=null&&e.appendBuffer))},Lv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource;import{assertNever as gn,clientChecker as bn}from"@vkontakte/videoplayer-shared/es2015";var He=document.createElement("video"),kL='video/mp4; codecs="avc1.42000a,mp4a.40.2"',RL='video/mp4; codecs="hev1.1.6.L93.B0"',Uv='video/webm; codecs="vp09.00.10.08"',Hv='video/webm; codecs="av01.0.00M.08"',$L='audio/mp4; codecs="mp4a.40.2"',LL='audio/webm; codecs="opus"',Mv,Dv,ra={mms:on(),mse:$v(),hls:!!((Mv=He.canPlayType)!=null&&Mv.call(He,"application/x-mpegurl")||(Dv=He.canPlayType)!=null&&Dv.call(He,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Cv,Ov,we={mp4:!!((Cv=He.canPlayType)!=null&&Cv.call(He,"video/mp4")),webm:!!((Ov=He.canPlayType)!=null&&Ov.call(He,"video/webm")),cmaf:!0},ln,Vv,cn,Bv,dn,_v,pn,Nv,hn,Fv,mn,qv,Ae={h264:!!((Vv=(ln=gt())==null?void 0:ln.isTypeSupported)!=null&&Vv.call(ln,kL)),h265:!!((Bv=(cn=gt())==null?void 0:cn.isTypeSupported)!=null&&Bv.call(cn,RL)),vp9:!!((_v=(dn=gt())==null?void 0:dn.isTypeSupported)!=null&&_v.call(dn,Uv)),av1:!!((Nv=(pn=gt())==null?void 0:pn.isTypeSupported)!=null&&Nv.call(pn,Hv)),aac:!!((Fv=(hn=gt())==null?void 0:hn.isTypeSupported)!=null&&Fv.call(hn,$L)),opus:!!((qv=(mn=gt())==null?void 0:mn.isTypeSupported)!=null&&qv.call(mn,LL))},ii=(Ae.h264||Ae.h265)&&Ae.aac,hr,ML=()=>A(void 0,null,function*(){if(!window.navigator.mediaCapabilities)return;let a={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo($(E({},a),{video:$(E({},a.video),{contentType:Hv})})),window.navigator.mediaCapabilities.decodingInfo($(E({},a),{video:$(E({},a.video),{contentType:Uv})}))]);hr={DASH_WEBM_AV1:e,DASH_WEBM:t}});try{ML()}catch(a){console.error(a)}var ai=ra.hls&&we.mp4,jv=()=>Object.keys(Ae).filter(a=>Ae[a]),Gv=(a,{useHlsJs:e,useManagedMediaSource:t,useOldMSEDetection:r})=>{let i=ra.mse&&(!r||!!window.MediaStreamTrack)||ra.mms&&t;return a.filter(s=>{switch(s){case"DASH_SEP":return i&&we.mp4&&ii;case"DASH_WEBM":return i&&we.webm&&Ae.vp9&&Ae.opus;case"DASH_WEBM_AV1":return i&&we.webm&&Ae.av1&&Ae.opus;case"DASH_STREAMS":return i&&(we.mp4&&ii||we.webm&&(Ae.vp9||Ae.av1)&&(Ae.opus||Ae.aac));case"DASH_LIVE":return i&&we.mp4&&ii;case"DASH_LIVE_CMAF":return i&&we.mp4&&ii&&we.cmaf;case"DASH_ONDEMAND":return i&&we.mp4&&ii;case"HLS":case"HLS_ONDEMAND":return ai||e&&i&&we.mp4&&ii;case"HLS_LIVE":case"HLS_LIVE_CMAF":return ai;case"MPEG":return we.mp4;case"DASH":case"DASH_LIVE_WEBM":return!1;case"WEB_RTC_LIVE":return ra.webrtc&&ra.ws&&Ae.h264&&(we.mp4||we.webm);default:return gn(s)}})},un=a=>{let e="DASH_WEBM",t="DASH_WEBM_AV1";switch(a){case"vp9":return[e,t];case"av1":return[t,e];case"none":return[];case"smooth":return hr?hr[t].smooth?[t,e]:hr[e].smooth?[e,t]:[t,e]:[e,t];case"power_efficient":return hr?hr[t].powerEfficient?[t,e]:hr[e].powerEfficient?[e,t]:[t,e]:[e,t];default:gn(a)}return[e,t]},Qv=({webmCodec:a,androidPreferredFormat:e,preferMultiStream:t})=>{let r=[...t?["DASH_STREAMS"]:[],...un(a),"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]],i=[...t?["DASH_STREAMS"]:[],"DASH_SEP","DASH_ONDEMAND",...t?[]:["DASH_STREAMS"]];if(bn.isAndroid)switch(e){case"mpeg":return["MPEG",...r,"HLS","HLS_ONDEMAND"];case"hls":return["HLS","HLS_ONDEMAND",...r,"MPEG"];case"dash":return[...r,"HLS","HLS_ONDEMAND","MPEG"];case"dash_any_mpeg":return[...i,"MPEG",...un(a),"HLS","HLS_ONDEMAND"];case"dash_any_webm":return[...un(a),"MPEG",...i,"HLS","HLS_ONDEMAND"];case"dash_sep":return["DASH_SEP","MPEG",...un(a),...i,"HLS","HLS_ONDEMAND"];default:gn(e)}return ai?[...r,"HLS","HLS_ONDEMAND","MPEG"]:[...r,"HLS","HLS_ONDEMAND","MPEG"]},Wv=({androidPreferredFormat:a,preferCMAF:e,preferWebRTC:t})=>{let r=e?["DASH_LIVE_CMAF","DASH_LIVE"]:["DASH_LIVE","DASH_LIVE_CMAF"],i=e?["HLS_LIVE_CMAF","HLS_LIVE"]:["HLS_LIVE","HLS_LIVE_CMAF"],s=[...r,...i],n=[...i,...r],o,u=bn.isMac&&bn.isSafari;if(bn.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:gn(a)}else ai&&!u?o=n:u?o=e?["DASH_LIVE_CMAF","HLS_LIVE_CMAF","HLS_LIVE","DASH_LIVE"]:["HLS_LIVE","DASH_LIVE","DASH_LIVE_CMAF","HLS_LIVE_CMAF"]:o=s;return t?["WEB_RTC_LIVE",...o]:[...o,"WEB_RTC_LIVE"]},vl=a=>a?["HLS_LIVE","HLS_LIVE_CMAF","DASH_LIVE_CMAF"]:["DASH_WEBM","DASH_WEBM_AV1","DASH_SEP","DASH_ONDEMAND","HLS","HLS_ONDEMAND","MPEG"],Yv=a=>{if(a.size===0)return;if(a.size===1){let t=a.values().next();return(0,fn.default)(t.value.split("."),0)}for(let t of a){let r=(0,fn.default)(t.split("."),0);if(r==="opus"||r==="vp09"||r==="av01")return r}let e=a.values().next();return(0,fn.default)(e.value.split("."),0)};var fS=_(mS(),1);import{ErrorCategory as aa}from"@vkontakte/videoplayer-shared/es2015";var bS=a=>{if(!a)return{id:"EmptyResponse",category:aa.PARSER,message:"Empty response"};if(a.length<=2&&a.match(/^\d+$/))return{id:`UVError#${a}`,category:aa.NETWORK,message:`UV Error ${a}`};let e=(0,fS.default)(a).substring(0,100).toLowerCase();if(e.startsWith("<!doctype")||e.startsWith("<html>")||e.startsWith("<body>")||e.startsWith("<head>"))return{id:"UnexpectedHTML",category:aa.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:aa.PARSER,message:"XML parsing error"}:{id:"XMLParserLogicError",category:aa.PARSER,message:"Response is valid XML, but parser failed"}};var qt=(a,e,t=0)=>{for(let r=0;r<a.length;r++)if(a.start(r)*1e3-t<=e&&a.end(r)*1e3+t>e)return!0;return!1};import{abortable as Xl,assertNonNullable as li,clientChecker as PD,combine as ci,ErrorCategory as Gt,filter as Ba,filterChanged as Pn,flattenObject as _a,fromEvent as yr,getTraceSubscriptionMethod as wD,interval as Jl,isNonNullable as Dy,map as Na,merge as Tr,now as AD,Subject as Cy,Subscription as Oy,tap as kD,throttle as RD,ValueSubject as ee}from"@vkontakte/videoplayer-shared/es2015";var Sn=_(Xe(),1),oi=_(ei(),1),yn=_(gl(),1);var zL=(a,e={})=>{let r=e.timeout||1,i=performance.now();return window.setTimeout(()=>{a({get didTimeout(){return e.timeout?!1:performance.now()-i-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-i))}})},1)},KL=a=>window.clearTimeout(a),gS=a=>typeof a=="function"&&(a==null?void 0:a.toString().endsWith("{ [native code] }")),vS=!gS(window.requestIdleCallback)||!gS(window.cancelIdleCallback),El=vS?zL:window.requestIdleCallback,sa=vS?KL:window.cancelIdleCallback;var Py=_(Ws(),1);import{assertNever as XL,ErrorCategory as SS,clientChecker as xl,Subject as yS}from"@vkontakte/videoplayer-shared/es2015";var JL=18,TS=!1;try{TS=xl.isSafari&&!!xl.macVersion&&xl.macVersion<=JL}catch(a){console.error(a)}var Pl=class{constructor(e){this.bufferFull$=new yS;this.error$=new yS;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:SS.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:t})}};this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return A(this,null,function*(){return t&&t.aborted?!1:new Promise(r=>{let i={operation:"append",data:e,signal:t,callback:r};this.queue.push(i),this.pull()})})}remove(e,t,r){return A(this,null,function*(){return r&&r.aborted?!1:new Promise(i=>{let s={operation:"remove",from:e,to:t,signal:r,callback:i};this.queue.unshift(s),this.pull()})})}abort(e){return A(this,null,function*(){return new Promise(t=>{let r,i=s=>{this.abortRequested=!1,t(s)};TS&&e?r={operation:"safariAbort",init:e,callback:i}:r={operation:"abort",callback:i};for(let{callback:s}of this.queue)s(!1);this.abortRequested=!0,r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var i;if((this.buffer.updating||this.currentTask||this.destroyed)&&!this.abortRequested)return;let e=this.queue.shift();if(!e)return;if((i=e.signal)!=null&&i.aborted){e.callback(!1),this.pull();return}this.currentTask=e;let{operation:t}=this.currentTask;try{this.execute(this.currentTask)}catch(s){s instanceof DOMException&&s.name==="QuotaExceededError"&&t==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):s instanceof DOMException&&s.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${t}`,category:SS.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:XL(t)}}},IS=Pl;var wl=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 br,assertNonNullable as je,clientChecker as mD,ErrorCategory as Ht,fromEvent as Gl,getExponentialDelay as Ql,isNonNullable as $a,isNullable as Re,now as vn,once as fD,Subject as bD,Subscription as gD,ValueSubject as gr}from"@vkontakte/videoplayer-shared/es2015";var Q=class{constructor(e,t){this.cursor=0;this.source=e,this.boxParser=t,this.children=[];let r=this.readUint32();this.type=this.readString(4),this.size32=r<=e.buffer.byteLength-e.byteOffset?r:NaN;let i=this.size32?this.size32-8:void 0,s=e.byteOffset+this.cursor;this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,s,i),this.children=this.parseChildrenBoxes()}get id(){return this.type}get size(){return this.size32}parseChildrenBoxes(){return[]}scanForBoxes(e){return this.boxParser.parse(e)}readString(e,t="ascii"){let i=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,i}readUint8(){let e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){let e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){let e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){let e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}};var si=class extends Q{};var na=class extends Q{constructor(t,r){super(t,r);this.ondemandPrefix="ondemandlivejson";this.ondemandDataReceivedKey="t-in";this.ondemandDataPreparedKey="t-out";let i=this.content.byteOffset,s=i+this.content.byteLength,n=new TextDecoder("ascii").decode(this.content.buffer.slice(i,s)).split(this.ondemandPrefix)[1],o=JSON.parse(n);this.serverDataReceivedTimestamp=o[this.ondemandDataReceivedKey],this.serverDataPreparedTime=o[this.ondemandDataPreparedKey]}};var oa=class extends Q{constructor(e,t){super(e,t),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let r=this.size-this.cursor;for(;r;){let i=this.readString(4);this.compatibleBrands.push(i),r-=4}}};var ua=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var J=class extends Q{constructor(e,t){super(e,t);let r=this.readUint32();this.version=r>>>24,this.flags=r&16777215}};var la=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.timescale=this.readUint32(),this.duration=this.readUint32(),this.rate=this.readUint32(),this.volume=this.readUint16()}};var ca=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var da=class extends Q{constructor(e,t){super(e,t),this.data=this.content}};var mr=class extends J{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e,t){super(e,t),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let r=0;r<this.referenceCount;r++){let i=this.readUint32(),s=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();let u=i>>>28,l=i<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:u,SAPDeltaTime:l})}}};var pa=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ha=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ma=class extends J{constructor(e,t){switch(super(e,t),this.readUint8()){case 0:this.stereoMode=0;break;case 1:this.stereoMode=1;break;case 2:this.stereoMode=2;break;case 3:this.stereoMode=3;break;case 4:this.stereoMode=4;break}this.cursor+=1}};var fa=class extends J{constructor(e,t){super(e,t),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}};var ba=class extends J{constructor(e,t){super(e,t),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}};var ga=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var va=class extends J{constructor(e,t){super(e,t),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}};var Sa=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var ya=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ta=class extends J{constructor(e,t){super(e,t),this.sequenceNumber=this.readUint32()}};var Ia=class extends Q{parseChildrenBoxes(){return this.scanForBoxes(this.content)}};var Ea=class extends J{constructor(e,t){super(e,t),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}};var xa=class extends J{constructor(t,r){super(t,r);this.baseMediaDecodeTime32=0;this.baseMediaDecodeTime64=BigInt(0);this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}};var Pa=class extends J{constructor(t,r){super(t,r);this.sampleDuration=[];this.sampleSize=[];this.sampleFlags=[];this.sampleCompositionTimeOffset=[];this.optionalFields=0;this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let i=0;i<this.sampleCount;i++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}};var eM={ftyp:oa,moov:ua,mvhd:la,moof:ca,mdat:da,sidx:mr,trak:pa,mdia:ga,mfhd:Ta,tkhd:va,traf:Ia,tfhd:Ea,tfdt:xa,trun:Pa,minf:Sa,sv3d:ha,st3d:ma,prhd:fa,proj:ya,equi:ba,uuid:na,unknown:si},vt=class a{constructor(e={}){this.options=E({offset:0},e)}parse(e){let t=[],r=this.options.offset;for(;r<e.byteLength;)try{let s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+r+4,4)),n=this.createBox(s,new DataView(e.buffer,e.byteOffset+r));if(!n.size)break;t.push(n),r+=n.size}catch(i){break}return t}createBox(e,t){let r=eM[e];return r?new r(t,new a):new si(t,new a)}};var Ut=class{constructor(e){this.index={},this.indexBoxLevel(e)}indexBoxLevel(e){e.forEach(t=>{var r,i,s;(s=(r=this.index)[i=t.type])!=null||(r[i]=[]),this.index[t.type].push(t),t.children.length>0&&this.indexBoxLevel(t.children)})}find(e){return this.index[e]&&this.index[e][0]?this.index[e][0]:null}findAll(e){return this.index[e]||[]}};var rM=new TextDecoder("ascii"),iM=a=>rM.decode(new DataView(a.buffer,a.byteOffset+4,4))==="ftyp",aM=a=>{let e=new mr(a,new vt),t=e.earliestPresentationTime/e.timescale*1e3,r=a.byteOffset+a.byteLength+e.firstOffset;return e.segments.map(s=>{if(s.referenceType!==0)throw new Error("Unsupported multilevel sidx");let n=s.subsegmentDuration/e.timescale*1e3,o={status:"none",time:{from:t,to:t+n},byte:{from:r,to:r+s.referencedSize-1}};return t+=n,r+=s.referencedSize,o})},sM=(a,e)=>{let r=new vt().parse(a),i=new Ut(r),s=i.findAll("moof"),n=e?i.findAll("uuid"):i.findAll("mdat");if(!(n.length&&s.length))return null;let o=s[0],u=n[n.length-1],l=o.source.byteOffset,d=u.source.byteOffset-o.source.byteOffset+u.size;return new DataView(a.buffer,l,d)},nM=a=>{let t=new vt().parse(a),r=new Ut(t),i={},s=r.findAll("uuid");return s.length?s[s.length-1]:i},oM=a=>{var i;let t=new vt().parse(a);return(i=new Ut(t).find("sidx"))==null?void 0:i.timescale},uM=(a,e)=>{let r=new vt().parse(a),s=new Ut(r).findAll("traf"),n=s[s.length-1].children.find(d=>d.type==="tfhd"),o=s[s.length-1].children.find(d=>d.type==="tfdt"),u=s[s.length-1].children.find(d=>d.type==="trun"),l=0;return u.sampleDuration.length?l=u.sampleDuration.reduce((d,p)=>d+p,0):l=n.defaultSampleDuration*u.sampleCount,(Number(o.baseMediaDecodeTime)+l)/e*1e3},lM=a=>{let e={is3dVideo:!1,stereoMode:0,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}},r=new vt().parse(a),i=new Ut(r);if(i.find("sv3d")){e.is3dVideo=!0;let n=i.find("st3d");n&&(e.stereoMode=n.stereoMode);let o=i.find("prhd");o&&(e.projectionData.pose.yaw=o.poseYawDegrees,e.projectionData.pose.pitch=o.posePitchDegrees,e.projectionData.pose.roll=o.poseRollDegrees);let u=i.find("equi");u&&(e.projectionData.bounds.top=u.projectionBoundsTop,e.projectionData.bounds.right=u.projectionBoundsRight,e.projectionData.bounds.bottom=u.projectionBoundsBottom,e.projectionData.bounds.left=u.projectionBoundsLeft)}return e},ES={validateData:iM,parseInit:lM,getIndexRange:()=>{},parseSegments:aM,parseFeedableSegmentChunk:sM,getChunkEndTime:uM,getServerLatencyTimestamps:nM,getTimescaleFromIndex:oM};var Aa=_(Xe(),1);import{assertNonNullable as kl,isNonNullable as AS,isNullable as dM}from"@vkontakte/videoplayer-shared/es2015";import{assertNever as cM}from"@vkontakte/videoplayer-shared/es2015";var xS={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"}},PS=a=>{let e=a.getUint8(0),t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);let r=wa(a,t),i=r in xS,s=i?xS[r].type:"binary",n=a.getUint8(t),o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);let u=new DataView(a.buffer,a.byteOffset+t+1,o-1),l=n&255>>o,c=wa(u),d=l*at(2,(o-1)*8)+c,p=t+o,h;return p+d>a.byteLength?h=new DataView(a.buffer,a.byteOffset+p):h=new DataView(a.buffer,a.byteOffset+p,d),{tag:i?r:"0x"+r.toString(16).toUpperCase(),type:s,tagHeaderSize:p,tagSize:p+d,value:h,valueSize:d}},wa=(a,e=a.byteLength)=>{switch(e){case 1:return a.getUint8(0);case 2:return a.getUint16(0);case 3:return a.getUint8(0)*at(2,16)+a.getUint16(1);case 4:return a.getUint32(0);case 5:return a.getUint8(0)*at(2,32)+a.getUint32(1);case 6:return a.getUint16(0)*at(2,32)+a.getUint32(2);case 7:{let t=a.getUint8(0)*281474976710656+a.getUint16(1)*4294967296+a.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},et=(a,e)=>{switch(e){case"int":return a.getInt8(0);case"uint":return wa(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:cM(e)}},fr=(a,e)=>{let t=0;for(;t<a.byteLength;){let r=new DataView(a.buffer,a.byteOffset+t),i=PS(r);if(!e(i))return;i.type==="master"&&fr(i.value,e),t=i.value.byteOffset-a.byteOffset+i.valueSize}},wS=a=>{if(a.getUint32(0)!==440786851)return!1;let e,t,r,i=PS(a);return fr(i.value,({tag:s,type:n,value:o})=>(s===17143?e=et(o,n):s===17026?t=et(o,n):s===17029&&(r=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)};var kS=[357149030,290298740,374648427,174,224,30320,30321,30322,272869232,524531317,475249515,423732329,307544935],pM=[231,22612,22743,167,171,163,160,175],hM=a=>{let e,t,r,i,s=!1,n=!1,o=!1,u,l,c=!1,d=0;return fr(a,({tag:p,type:h,value:m,valueSize:b})=>{if(p===21419){let g=et(m,h);l=wa(g)}else p!==21420&&(l=void 0);return p===408125543?(e=m.byteOffset,t=m.byteOffset+b):p===357149030?s=!0:p===290298740?n=!0:p===2807729?r=et(m,h):p===17545?i=et(m,h):p===21420&&l===475249515?u=et(m,h):p===374648427?fr(m,({tag:g,type:v,value:S})=>g===30321?(c=et(S,v)===1,!1):!0):s&&n&&(0,Aa.default)(kS,p)&&(o=!0),!o}),kl(e,"Failed to parse webm Segment start"),kl(t,"Failed to parse webm Segment end"),kl(i,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(i/1e9*r*1e3),cuesSeekPosition:u,is3dVideo:c,stereoMode:d,projectionType:1,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},mM=a=>{if(dM(a.cuesSeekPosition))return;let e=a.segmentStart+a.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},fM=(a,e)=>{let t=!1,r=!1,i=o=>AS(o.time)&&AS(o.position),s=[],n;return fr(a,({tag:o,type:u,value:l})=>{switch(o){case 475249515:t=!0;break;case 187:n&&i(n)&&s.push(n),n={};break;case 179:n&&(n.time=et(l,u));break;case 183:break;case 241:n&&(n.position=et(l,u));break;default:t&&(0,Aa.default)(kS,o)&&(r=!0)}return!(t&&r)}),n&&i(n)&&s.push(n),s.map((o,u)=>{let{time:l,position:c}=o,d=s[u+1];return{status:"none",time:{from:l,to:d?d.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:d?e.segmentStart+d.position-1:e.segmentEnd-1}}})},bM=a=>{let e=0,t=!1;try{fr(a,r=>r.tag===524531317?r.tagSize<=a.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):(0,Aa.default)(pM,r.tag)?(e+r.tagSize<=a.byteLength&&(e+=r.tagSize,t||(t=(0,Aa.default)([163,160,175],r.tag))),!0):!1)}catch(r){}return e>0&&e<=a.byteLength&&t?new DataView(a.buffer,a.byteOffset,e):null},RS={validateData:wS,parseInit:hM,getIndexRange:mM,parseSegments:fM,parseFeedableSegmentChunk:bM};var ka=a=>{let e=/^(.+)\/([^;]+)(?:;.*)?$/.exec(a);if(e){let[,t,r]=e;if(t==="audio"||t==="video")switch(r){case"webm":return RS;case"mp4":return ES}}throw new ReferenceError(`Unsupported mime type ${a}`)};var ql=_(zS(),1),yy=_(qr(),1),Ty=_(dy(),1),Ul=_(ei(),1),Hl=_(Jr(),1);var py=_(Xe(),1),Cl=a=>{let e=a.split("."),[t,...r]=e;if(!t)return!1;switch(t){case"av01":{let[i,s,n]=r;return!!(n&&parseInt(n,10)>8)}case"vp09":{let[i,s,n]=r;return!!(i&&parseInt(i,10)>=2&&n&&parseInt(n,10)>8)}case"avc1":{let i=r[0];if(!i||i.length!==6)return!1;let[s,n]=i.toUpperCase(),o=s+n;return(0,py.default)(["6E","7A","F4"],o)}}return!1};import{isNonNullable as hD,isNullable as Sy}from"@vkontakte/videoplayer-shared/es2015";var hy=a=>{if(a.includes("/")){let e=a.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(a)};var my=a=>{var e;try{let t=dD(),r=a.match(t),{groups:i}=r!=null?r:{};if(i){let s={};if(i.extensions){let u=i.extensions.toLowerCase().match(/(?:[0-9a-wy-z](?:-[a-z0-9]{2,8})+)/g);Array.from(u||[]).forEach(l=>{s[l[0]]=l.slice(2)})}let n=(e=i.variants)==null?void 0:e.split(/-/).filter(u=>u!==""),o={extlang:i.extlang,langtag:i.langtag,language:i.language,privateuse:i.privateuse||i.privateuse2,region:i.region,script:i.script,extensions:s,variants:n};return Object.keys(o).forEach(u=>{let l=o[u];(typeof l=="undefined"||l==="")&&delete o[u]}),o}return null}catch(t){return null}};function dD(){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 Bl=_(ti(),1);import{videoSizeToQuality as oC}from"@vkontakte/videoplayer-shared/es2015";var oy=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?_t(s):void 0)!=null?u:oC({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},uy=({id:a,bitrate:e})=>({id:a,bitrate:e}),ly=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),cy=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Vl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Bl.default)(r.split("."),0),isDefault:i}),_l=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Bl.default)(i.split("."),0)}),Nl=a=>"url"in a,ge=a=>a.type==="template",Ra=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var py=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},St=(a,e)=>{let t=a;t=(0,Fl.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,hy.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,Fl.default)(t,n,(o,u)=>dy(s)?o:dy(u)?s:(0,fy.default)(s,parseInt(u,10),"0"))}return t},by=(a,e)=>{var E,$,B,J,L,F,q,R,U,N,W,A,T,D,M,se,Be,It,xr,j,ce,de,Ve,Et,Pr,xt,zt,wr,hi,gc,vc,Sc,yc,Tc,Ic,Ec,xc,Pc,wc,Ac,kc,Rc,$c,Lc,Mc,Cc,Dc,Oc,Bc,Vc,_c,Nc,Fc,qc,Uc,Hc,jc,Gc,Qc,Wc;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Ge=>{var K,Kt;return(Kt=(K=Ge.textContent)==null?void 0:K.trim())!=null?Kt:""}),o=(E=(0,my.default)(n,0))!=null?E:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],f=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((Ge,K)=>C(x({},Ge),{[K.id]:K.children}),{}),S=b.reduce((Ge,K)=>C(x({},Ge),{[K.id]:K.getAttribute("duration")}),{});p?d=py(p):(0,ql.default)(S).filter(Ge=>Ge).length&&!u?d=(0,ql.default)(S).reduce((Ge,K)=>{var Kt;return Ge+((Kt=py(K))!=null?Kt:0)},0):f&&(d=parseInt(f,10));let v=0,y=(B=($=s.getAttribute("profiles"))==null?void 0:$.split(","))!=null?B:[];for(let Ge of b.map(K=>K.id))for(let K of g[Ge]){let Kt=(J=K.getAttribute("id"))!=null?J:"id"+(v++).toString(10),fi=(L=K.getAttribute("mimeType"))!=null?L:"",Qn=(F=K.getAttribute("codecs"))!=null?F:"",Wn=(q=K.getAttribute("contentType"))!=null?q:fi==null?void 0:fi.split("/")[0],OT=(U=(R=K.getAttribute("profiles"))==null?void 0:R.split(","))!=null?U:[],Yc=(W=ny((N=K.getAttribute("lang"))!=null?N:""))!=null?W:{},BT=(D=(T=(A=K.querySelector("Label"))==null?void 0:A.textContent)==null?void 0:T.trim())!=null?D:void 0,VT=K.querySelectorAll("Representation"),_T=K.querySelector("SegmentTemplate"),NT=(se=(M=K.querySelector("Role"))==null?void 0:M.getAttribute("value"))!=null?se:void 0,Ar=Wn,ee={id:Kt,language:Yc.language,isDefault:NT==="main",label:BT,codecs:Qn,hdr:Ar==="video"&&Dl(Qn),mime:fi,representations:[]};for(let Y of VT){let Pt=(Be=Y.getAttribute("lang"))!=null?Be:void 0,mi=(It=Y.getAttribute("label"))!=null?It:void 0,ts=(ce=(j=(xr=Y.querySelector("BaseURL"))==null?void 0:xr.textContent)==null?void 0:j.trim())!=null?ce:"",Jt=new URL(ts||o,e).toString(),wt=(de=Y.getAttribute("mimeType"))!=null?de:fi,rs=(Et=(Ve=Y.getAttribute("codecs"))!=null?Ve:Qn)!=null?Et:"",is;if(Wn==="text"){let At=Y.getAttribute("id")||"",as=((Pr=Yc.privateuse)==null?void 0:Pr.includes("x-auto"))||At.includes("_auto"),Xt=Y.querySelector("SegmentTemplate");if(Xt){let bi={representationId:(xt=Y.getAttribute("id"))!=null?xt:void 0,bandwidth:(zt=Y.getAttribute("bandwidth"))!=null?zt:void 0},ss=parseInt((wr=Y.getAttribute("bandwidth"))!=null?wr:"",10)/1e3,ns=(gc=parseInt((hi=Xt.getAttribute("startNumber"))!=null?hi:"",10))!=null?gc:1,kr=parseInt((vc=Xt.getAttribute("timescale"))!=null?vc:"",10),Yn=(Sc=Xt.querySelectorAll("SegmentTimeline S"))!=null?Sc:[],Rr=Xt.getAttribute("media");if(!Rr)continue;let os=[],us=0,ls="",$r=0,gi=ns,me=0;for(let Qe of Yn){let Zt=parseInt((yc=Qe.getAttribute("d"))!=null?yc:"",10),_e=parseInt((Tc=Qe.getAttribute("r"))!=null?Tc:"",10)||0,kt=parseInt((Ic=Qe.getAttribute("t"))!=null?Ic:"",10);me=Number.isFinite(kt)?kt:me;let er=Zt/kr*1e3,Rt=me/kr*1e3;for(let tt=0;tt<_e+1;tt++){let $t=St(Rr,C(x({},bi),{segmentNumber:gi.toString(10),segmentTime:(me+tt*Zt).toString(10)})),Lr=(Rt!=null?Rt:0)+tt*er,Si=Lr+er;gi++,os.push({time:{from:Lr,to:Si},url:$t})}me+=(_e+1)*Zt,us+=(_e+1)*er}$r=me/kr*1e3,ls=St(Rr,C(x({},bi),{segmentNumber:gi.toString(10),segmentTime:me.toString(10)}));let vi={time:{from:$r,to:1/0},url:ls},ct={type:"template",baseUrl:Jt,segmentTemplateUrl:Rr,initUrl:"",totalSegmentsDurationMs:us,segments:os,nextSegmentBeyondManifest:vi,timescale:kr};is={id:At,kind:"text",segmentReference:ct,profiles:[],duration:d,bitrate:ss,mime:"",codecs:"",width:0,height:0,isAuto:as}}else is={id:At,isAuto:as,kind:"text",url:Jt}}else{let At=(xc=(Ec=Y.getAttribute("contentType"))!=null?Ec:wt==null?void 0:wt.split("/")[0])!=null?xc:Wn,as=(wc=(Pc=K.getAttribute("profiles"))==null?void 0:Pc.split(","))!=null?wc:[],Xt=parseInt((Ac=Y.getAttribute("width"))!=null?Ac:"",10),bi=parseInt((kc=Y.getAttribute("height"))!=null?kc:"",10),ss=parseInt((Rc=Y.getAttribute("bandwidth"))!=null?Rc:"",10)/1e3,ns=($c=Y.getAttribute("frameRate"))!=null?$c:"",kr=(Lc=Y.getAttribute("quality"))!=null?Lc:void 0,Yn=ns?sy(ns):void 0,Rr=(Mc=Y.getAttribute("id"))!=null?Mc:"id"+(v++).toString(10),os=At==="video"?`${bi}p`:At==="audio"?`${ss}Kbps`:rs,us=`${Rr}@${os}`,ls=[...y,...OT,...as],$r,gi=Y.querySelector("SegmentBase"),me=(Cc=Y.querySelector("SegmentTemplate"))!=null?Cc:_T;if(gi){let ct=(Oc=(Dc=Y.querySelector("SegmentBase Initialization"))==null?void 0:Dc.getAttribute("range"))!=null?Oc:"",[Qe,Zt]=ct.split("-").map($t=>parseInt($t,10)),_e={from:Qe,to:Zt},kt=(Bc=Y.querySelector("SegmentBase"))==null?void 0:Bc.getAttribute("indexRange"),[er,Rt]=kt?kt.split("-").map($t=>parseInt($t,10)):[],tt=kt?{from:er,to:Rt}:void 0;$r={type:"byteRange",url:Jt,initRange:_e,indexRange:tt}}else if(me){let ct={representationId:(Vc=Y.getAttribute("id"))!=null?Vc:void 0,bandwidth:(_c=Y.getAttribute("bandwidth"))!=null?_c:void 0},Qe=parseInt((Nc=me.getAttribute("timescale"))!=null?Nc:"",10),Zt=(Fc=me.getAttribute("initialization"))!=null?Fc:"",_e=me.getAttribute("media"),kt=(Uc=parseInt((qc=me.getAttribute("startNumber"))!=null?qc:"",10))!=null?Uc:1,er=St(Zt,ct);if(!_e)throw new ReferenceError("No media attribute in SegmentTemplate");let Rt=(Hc=me.querySelectorAll("SegmentTimeline S"))!=null?Hc:[],tt=[],$t=0,Lr="",Si=0;if(Rt.length){let cs=kt,We=0;for(let Mr of Rt){let rt=parseInt((jc=Mr.getAttribute("d"))!=null?jc:"",10),tr=parseInt((Gc=Mr.getAttribute("r"))!=null?Gc:"",10)||0,ds=parseInt((Qc=Mr.getAttribute("t"))!=null?Qc:"",10);We=Number.isFinite(ds)?ds:We;let zn=rt/Qe*1e3,Kn=We/Qe*1e3;for(let ps=0;ps<tr+1;ps++){let qT=St(_e,C(x({},ct),{segmentNumber:cs.toString(10),segmentTime:(We+ps*rt).toString(10)})),zc=(Kn!=null?Kn:0)+ps*zn,UT=zc+zn;cs++,tt.push({time:{from:zc,to:UT},url:qT})}We+=(tr+1)*rt,$t+=(tr+1)*zn}Si=We/Qe*1e3,Lr=St(_e,C(x({},ct),{segmentNumber:cs.toString(10),segmentTime:We.toString(10)}))}else if(uC(d)){let We=parseInt((Wc=me.getAttribute("duration"))!=null?Wc:"",10)/Qe*1e3,Mr=Math.ceil(d/We),rt=0;for(let tr=1;tr<Mr;tr++){let ds=St(_e,C(x({},ct),{segmentNumber:tr.toString(10),segmentTime:rt.toString(10)}));tt.push({time:{from:rt,to:rt+We},url:ds}),rt+=We}Si=rt,Lr=St(_e,C(x({},ct),{segmentNumber:Mr.toString(10),segmentTime:rt.toString(10)}))}let FT={time:{from:Si,to:1/0},url:Lr};$r={type:"template",baseUrl:Jt,segmentTemplateUrl:_e,initUrl:er,totalSegmentsDurationMs:$t,segments:tt,nextSegmentBeyondManifest:FT,timescale:Qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!At||!wt)continue;let vi={video:"video",audio:"audio",text:"text"}[At];if(!vi)continue;Ar||(Ar=vi),is={id:us,kind:vi,segmentReference:$r,profiles:ls,duration:d,bitrate:ss,mime:wt,codecs:rs,width:Xt,height:bi,fps:Yn,quality:kr}}ee.language||(ee.language=Pt),ee.label||(ee.label=mi),ee.mime||(ee.mime=wt),ee.codecs||(ee.codecs=rs),ee.hdr||(ee.hdr=Ar==="video"&&Dl(rs)),ee.representations.push(is)}if(Ar){let Y=i[Ar].find(Pt=>Pt.id===ee.id);if(Y&&ee.representations.every(Pt=>ge(Pt.segmentReference)))for(let Pt of Y.representations){let mi=ee.representations.find(wt=>wt.id===Pt.id),ts=mi==null?void 0:mi.segmentReference,Jt=Pt.segmentReference;Jt.segments.push(...ts.segments),Jt.nextSegmentBeyondManifest=ts.nextSegmentBeyondManifest}else i[Ar].push(ee)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n}};var vy=_(Je(),1);import{isNonNullable as gy}from"@vkontakte/videoplayer-shared/es2015";var Ae=(a,e)=>gy(a)&&gy(e)&&a.readyState==="open"&&(0,vy.default)([...a.activeSourceBuffers],e);var La=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new gr(0);this.currentLowLatencySegmentLength$=new gr(0);this.currentSegmentLength$=new gr(0);this.onLastSegment$=new gr(!1);this.fullyBuffered$=new gr(!1);this.playingRepresentation$=new gr(void 0);this.playingRepresentationInit$=new gr(void 0);this.error$=new dC;this.gaps=[];this.subscription=new pC;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new De;this.switchAbortController=new De;this.destroyAbortController=new De;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=br(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new fS(this.sourceBuffer),this.subscription.add(Hl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ht.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ht.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Hl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ht.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!Ae(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,wl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=ut(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);je(r,"No init buffer for starting representation"),je(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchToOld=br(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);je(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(ke(s)||ke(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),je(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!Ae(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();$a(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Zn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=br(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){var u,l;let t=(u=(0,Tn.default)(e,c=>c.representations))!=null?u:[];if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!t)return;for(let c of this.representations.keys()){let d=t.find(f=>f.id===c);d&&this.representations.set(c,d);let p=this.representations.get(c);if(!p||!ge(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);je(i);let s=this.segments.get(r);je(s,"No segments for starting representation");let n=this.initData.get(r);if(je(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new De,br(this.switchAbortController.signal,function(r,i=!1){return ae(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);je(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(ke(o)||ke(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),je(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!Ae(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();$a(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!ke(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return k(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new De,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(ke(e)||ke(this.downloadingRepresentationId)||ke(this.playingRepresentationId)||ke(this.sourceBuffer)||!Ae(this.mediaSource,this.sourceBuffer)||$a(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);$a(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=ut(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&wl(this.sourceBuffer.buffered)>=this.bufferLimit){let l=ut(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,yn.default)(o,i))l="high";else{let c=(0,ui.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&ut(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,ui.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;$a(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,Tn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,Tn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!ge(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>C(x({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,ui.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!ge(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=St(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&sa&&sa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&sa&&sa(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},f)=>{let b=p<=r&&h>=r,g=p>r||b||f===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&p<=r+S||h<=r+S;return(d==="none"||d==="partially_ejected"&&g&&v&&this.sourceBuffer&&Ae(this.mediaSource,this.sourceBuffer)&&!(qt(this.sourceBuffer.buffered,p)&&qt(this.sourceBuffer.buffered,h)))&&g&&v});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return k(this,null,function*(){ge(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return k(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield br(o,function(){return ae(this,null,function*(){let c=jl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=Sn(),!c)return;let d=new DataView(c),p=ka(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:f}=p.getServerLatencyTimestamps(d);h&&f&&this.currentLiveSegmentServerLatency$.next(f-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ra(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())ge(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return k(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield br(n,function(){return ae(this,null,function*(){let u=jl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Hl(window,"online").pipe(cC()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=Sn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ra(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ge(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,ui.default)(e,0).byte.from,to:(0,ui.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>k(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=Sn(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!ge(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=Sn();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:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,yn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return k(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=ka(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return k(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,f=d<i,b=p<=i;if(!f)continue;let g=ka(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let S=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let S=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),v=l.loadedBytes===h?S:g.parseFeedableSegmentChunk(S);v!=null&&v.byteLength&&(c.status="partially_fed",l.feedingBytes+=v.byteLength,(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?(l.fedBytes+=v.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(ke(this.sourceBuffer)||!Ae(this.mediaSource,this.sourceBuffer))){!this.isLive&&lC.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qt(this.sourceBuffer.buffered,e.segment.time.from,100)&&qt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ht.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",Nl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=El(()=>(0,Sy.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return k(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?br(this.destroyAbortController.signal,function(){return ae(this,null,function*(){let o=jl(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ka(e.mime),i)).then(o=>k(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&ge(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ht.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return k(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return k(this,null,function*(){if(!this.sourceBuffer||!Ae(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||ke(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(x({},u.time)),i=n(i);let l=Nl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,yn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return k(this,null,function*(){if(!this.sourceBuffer||!Ae(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||!Ae(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!Ae(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||ke(e)?0:ut(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!Ae(this.mediaSource,this.sourceBuffer)))for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!Ae(this.mediaSource,this.sourceBuffer))){for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=El(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ht.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(ke(this.sourceBuffer)||!Ae(this.mediaSource,this.sourceBuffer)||ke(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Ma=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var yy=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Ca,assertNever as Iy,fromEvent as Ey,merge as hC,now as Da,Subscription as fC,ValueSubject as Gl,flattenObject as li}from"@vkontakte/videoplayer-shared/es2015";var Ty=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var In=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Gl(void 0);this.lastConnectionReused$=new Gl(void 0);this.lastRequestFirstBytes$=new Gl(void 0);this.abortAllController=new De;this.subscription=new fC;this.fetchManifest=Ca(this.abortAllController.signal,function(e){return ae(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ma(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Ty(r));let i=yield bt(r,{signal:this.abortAllController.signal}).catch(Oa);return i?(t.log("success",li({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",li({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Ca(this.abortAllController.signal,function(l){return ae(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var R,U;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let N=new URL(c,location.href);N.searchParams.append("bytes",`${r.from}-${r.to}`),c=N.toString();break}default:Iy(t)}this.requestQuic&&(c=Ma(c));let h=this.abortAllController.signal,f;if(n){let N=new De;if(f=hC(Ey(this.abortAllController.signal,"abort"),Ey(n,"abort")).subscribe(()=>{try{N.abort()}catch(W){Oa(W)}}),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(W){Oa(W)}h=N.signal}let b=Da();p.log("startRequest",li({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield bt(c,{priority:s,headers:d,signal:h}).catch(Oa),S=Da();if(!g)return p.error("error",{message:"No response in request"}),p.end(),f==null||f.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(S-b),!g.ok||!g.body){f==null||f.unsubscribe();let N=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:N}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){f==null||f.unsubscribe();let N=Da(),W={requestStartedAt:b,requestEndedAt:N,duration:N-b};return p.log("endRequest",li(W)),p.end(),g.arrayBuffer()}let[v,y]=g.body.tee(),I=v.getReader();o&&((U=this.throughputEstimator)==null||U.trackStream(y,u));let E=0,$=new Uint8Array(0),B=!1,J=N=>{f==null||f.unsubscribe(),B=!0,Oa(N)},L=Ca(h,function(A){return ae(this,arguments,function*({done:N,value:W}){if(E===0&&this.lastRequestFirstBytes$.next(Da()-b),h.aborted){f==null||f.unsubscribe();return}if(!N&&W){let T=new Uint8Array($.length+W.length);T.set($),T.set(W,$.length),$=T,E+=W.byteLength,i==null||i(new DataView($.buffer),E),yield I==null?void 0:I.read().then(L,J)}})}.bind(this));yield I==null?void 0:I.read().then(L,J),f==null||f.unsubscribe();let F=Da(),q={failed:B,requestStartedAt:b,requestEndedAt:F,duration:F-b};return B?(p.error("endRequest",li(q)),p.end(),null):(p.log("endRequest",li(q)),p.end(),$.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Ca(this.abortAllController.signal,function(e,t,r){return ae(this,null,function*(){var S;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),f=(S=e.indexRange)!=null?S:t.getIndexRange(h);if(!f)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,f.from-n,f.to-f.from+1);else{let v=yield this.fetch(e.url,{range:f,priority:r,measureThroughput:!1});if(!v)return null;b=new DataView(v)}let g=t.parseSegments(b,h,f);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Ca(this.abortAllController.signal,function(e,t){return ae(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>C(x({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=yy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return k(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:Iy(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Oa=a=>{if(!Ra(a))throw a};var vr=(a,e,t)=>t*e+(1-t)*a,Ql=(a,e)=>a.reduce((t,r)=>t+r,0)/e,xy=(a,e,t,r)=>{let i=0,s=t,n=Ql(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as mC,ValueSubject as Py}from"@vkontakte/videoplayer-shared/es2015";var jt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Py(e.initial),this.debounced$=new Py(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new be(`raw_${t}`),this.smoothedSeries$=new be(`smoothed_${t}`),this.reportedSeries$=new be(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=it(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(mC(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 jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=vr(this.slow,e,this.params.emaAlphaSlow),this.fast=vr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var xn=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Ql(this.pastMeasures,this.takenMeasures);this.emaSmoothed=vr(this.emaSmoothed,e,this.params.emaAlpha);let r=xy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var Pn=class extends jt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?vr(this.smoothed,t,this.params.emaAlpha):t}};var Sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new En({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new xn({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new Pn(x({initial:e,label:"liveEdgeDelay"},t))}};var Wl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as bC,ValueSubject as gC}from"@vkontakte/videoplayer-shared/es2015";var Ba=class a{constructor(e,t){this.currentRepresentation$=new gC(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(!bC(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next(C(x({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ge(t.segmentReference))}};var PC=["timeupdate","progress","play","seeked","stalled","waiting"],wC=["timeupdate","progress","loadeddata","playing","seeked"];var An=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Ry;this.representationSubscription=new Ry;this.state$=new O("none");this.currentVideoRepresentation$=new re(void 0);this.currentVideoRepresentationInit$=new re(void 0);this.currentAudioRepresentation$=new re(void 0);this.currentVideoSegmentLength$=new re(0);this.currentAudioSegmentLength$=new re(0);this.error$=new ky;this.lastConnectionType$=new re(void 0);this.lastConnectionReused$=new re(void 0);this.lastRequestFirstBytes$=new re(void 0);this.currentLiveTextRepresentation$=new re(null);this.isLive$=new re(!1);this.liveDuration$=new re(0);this.liveAvailabilityStartTime$=new re(void 0);this.bufferLength$=new re(0);this.liveLatency$=new re(void 0);this.liveLoadBufferLength$=new re(0);this.livePositionFromPlayer$=new re(0);this.isLowLatency$=new re(!1);this.isActiveLowLatency$=new re(!1);this.currentStallDuration$=new re(0);this.videoLastDataObtainedTimestamp$=new re(0);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new ky;this.gapWatchdogActive=!1;this.destroyController=new De;this.initManifest=Yl(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=fe(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Gt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Yl(this.destroyController.signal,function(){return ae(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Gt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=by(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=uS(e))!=null?n:{id:"ManifestParsing",category:Gt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,f;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((f=(h=gt())==null?void 0:h.isTypeSupported)!=null&&f.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:f})=>r(u,h,f)),d=new Set(c.map(({codecs:h})=>h)),p=Fv(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,f=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);yC.isHDR&&h&&f?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=C(x({},t),{streams:i});return this.tracer.log("updateManifestEnd",_a(s)),s})}.bind(this));this.initRepresentations=Yl(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",_a({initialVideo:e,initialAudio:t,sourceHls:r})),yr(this.manifest),yr(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(Tr(p,"error").pipe(Va(h=>{var f;return!!((f=this.element)!=null&&f.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Gt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Ev():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&un())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new La("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Ay(t)){let p=this.manifest.streams.audio.reduce((h,f)=>[...h,...f.representations],[]);this.audioBufferManager=new La("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Ba.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Ba(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(zl(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let f=zs(this.manifestUrlString,2);this.manifestUrlString=fe(this.manifestUrlString,f+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Ir(...wC.map(p=>Tr(this.element,p))).pipe(Na(p=>this.element?ut(this.element.buffered,this.element.currentTime*1e3):0),wn(),EC(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Ir(Tr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(wn()).subscribe(h=>Wl(this.element,1))),this.representationSubscription.add(ci({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Va(({bufferLength:h,isActiveLowLatency:f})=>f&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(ci({isActiveLowLatency:this.isActiveLowLatency$.pipe(wn()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(Va(({isActiveLowLatency:h,currentLowLatencySegmentLength:f})=>h&&!!f)).subscribe(({currentLowLatencySegmentLength:h})=>{let f=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(f,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(ci({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Va(({isLive:h})=>h),Na(h=>x({},h)),wn((h,f)=>f.bufferLength<h.bufferLength),Na(({rtt:h,bufferLength:f,segmentServerLatency:b})=>{let g=zs(this.manifestUrlString,2);return(h/2+f+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ci({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:f})=>{if(!f)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,S=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,v=h-b,y=1;Math.abs(v)>g&&(y=1+Math.sign(v)*S),Wl(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let f=0;if(h){let S=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;f=Math.min(...this.bufferManagers.map(y=>{var I,E;return(E=(I=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?E:S}))-S}this.liveLoadBufferLength$.getValue()!==f&&this.liveLoadBufferLength$.next(f)}));let p=0;this.representationSubscription.add(ci({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(xC(1e3)).subscribe(b=>k(this,[b],function*({liveLoadBufferLength:h,bufferLength:f}){if(yr(this.element),this.isUpdatingLive)return;let g=this.element.playbackRate,S=zs(this.manifestUrlString,2),v=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(v,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,E=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,$=isFinite(h)?h:f,B=this.isActiveLowLatency$.getValue(),J=v<=this.tuning.live.activeLiveDelay&&S===0;this.isActiveLowLatency$.next(B&&J);let L="none";if(B?L="active_low_latency":this.isLowLatency$.getValue()&&J?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),L="active_low_latency"):S!==0&&$<y?L="live_forward_buffering":$<y+E&&(L="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),L==="live_forward_buffering"||L==="live_with_target_offset"){let F=p-(y+I),q=this.normolizeLiveOffset(Math.trunc(S+F/g)),R=Math.abs(q-S),U;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?U=S:q>0&&R>this.tuning.dashCmafLive.offsetCalculationError?U=q:U=0,this.manifestUrlString=fe(this.manifestUrlString,U,2)}L!=="none"&&L!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=Ir(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Na(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Ir(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Na(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(Ir(this.forceEnded$,ci({allBuffersFull:l,someBufferEnded:c}).pipe(Va(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:Gt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Ir(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,Kl.default)((0,Kl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let f=[];return h.duration&&f.push(h.duration),ge(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&f.push(h.segmentReference.totalSegmentsDurationMs),f})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Ay(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=zl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Gt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new In({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=Sr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,x({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return k(this,null,function*(){var r,i,s;yr(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=fe(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){yr(this.element),this.state$.setState("running"),this.subscription.add(Ir(...PC.map(e=>Tr(this.element,e)),Tr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Gt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(Tr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(Tr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&qt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,f,b,g,S,v,y,I,E,$;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=IC(),n=100,o=(f=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?f:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(v=(S=this.videoBufferManager)==null?void 0:S.getForwardBufferDuration())!=null?v:0,c=(I=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let B=this.element.currentTime*1e3;(E=this.videoBufferManager)==null||E.maintain(B),($=this.audioBufferManager)==null||$.maintain(B),i.position=B}this.tracer.log("stallIntervalCallback",_a(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=zl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Gt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return k(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){return k(this,null,function*(){var i,s,n,o,u;yr(this.element),yr(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),qt(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",_a({requestedPosition:e,forcePrecise:t,position:r}))})}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=TC(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return k(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=C(x({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",_a(t)))}}};var kn=class{constructor(e,t){this.fov=e,this.orientation=t}};var Rn=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/it(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=x({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*it(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var $y=`attribute vec2 a_vertex;
70
+ `})|(?<privateuse2>${e}))$`.replace(/[\s\t\n]/g,"");return new RegExp(c,"i")}var Vl=_(ei(),1);import{videoSizeToQuality as pD}from"@vkontakte/videoplayer-shared/es2015";var fy=({id:a,width:e,height:t,bitrate:r,fps:i,quality:s,streamId:n})=>{var u;let o=(u=s?_t(s):void 0)!=null?u:pD({width:e,height:t});return o&&{id:a,quality:o,bitrate:r,size:{width:e,height:t},fps:i,streamId:n}},by=({id:a,bitrate:e})=>({id:a,bitrate:e}),gy=({language:a,label:e},{id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),vy=({language:a,label:e,id:t,url:r,isAuto:i})=>({id:t,url:r,isAuto:i,type:"internal",language:a,label:e}),Bl=({id:a,language:e,label:t,codecs:r,isDefault:i})=>({id:a,language:e,label:t,codec:(0,Vl.default)(r.split("."),0),isDefault:i}),_l=({id:a,language:e,label:t,hdr:r,codecs:i})=>({id:a,language:e,hdr:r,label:t,codec:(0,Vl.default)(i.split("."),0)}),Nl=a=>"url"in a,ve=a=>a.type==="template",Ra=a=>a instanceof DOMException&&(a.name==="AbortError"||a.code===20);var Fl=a=>{if(!(a!=null&&a.startsWith("P")))return;let e=(n,o)=>{let u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(a),i=(r==null?void 0:r[1])==="-"?-1:1,s={days:e(r==null?void 0:r[5],i),hours:e(r==null?void 0:r[6],i),minutes:e(r==null?void 0:r[7],i),seconds:e(r==null?void 0:r[8],i)};return s.days*24*60*60*1e3+s.hours*60*60*1e3+s.minutes*60*1e3+s.seconds*1e3},St=(a,e)=>{let t=a;t=(0,ql.default)(t,"$$","$");let r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(let[i,s]of(0,yy.default)(r)){let n=new RegExp(`\\$${i}(?:%0(\\d+)d)?\\$`,"g");t=(0,ql.default)(t,n,(o,u)=>Sy(s)?o:Sy(u)?s:(0,Ty.default)(s,parseInt(u,10),"0"))}return t},Iy=(a,e)=>{var L,B,X,M,F,q,R,H,N,W,k,T,C,D,se,Ve,It,Er,j,ce,de,Be,Et,xr,xt,zt,Pr,hi,Ic,Ec,xc,Pc,wc,Ac,kc,Rc,$c,Lc,Mc,Dc,Cc,Oc,Vc,Bc,_c,Nc,Fc,qc,Uc,Hc,jc,Gc,Qc,Wc,Yc,zc,Kc,Xc,Jc,Zc,ed,td;let r=new DOMParser().parseFromString(a,"application/xml"),i={video:[],audio:[],text:[]},s=r.children[0],n=Array.from(s.querySelectorAll("MPD > BaseURL").values()).map(Ge=>{var K,Kt;return(Kt=(K=Ge.textContent)==null?void 0:K.trim())!=null?Kt:""}),o=(L=(0,Ul.default)(n,0))!=null?L:"",u=s.getAttribute("type")==="dynamic",l=s.getAttribute("availabilityStartTime"),c=l?new Date(l).getTime():void 0,d,p=s.getAttribute("mediaPresentationDuration"),h=s.getElementsByTagName("vk:Attrs")[0],m=h==null?void 0:h.getElementsByTagName("vk:XPlaybackDuration")[0].textContent,b=[...s.getElementsByTagName("Period")],g=b.reduce((Ge,K)=>$(E({},Ge),{[K.id]:K.children}),{}),v=b.reduce((Ge,K)=>$(E({},Ge),{[K.id]:K.getAttribute("duration")}),{});p?d=Fl(p):(0,Hl.default)(v).filter(Ge=>Ge).length&&!u?d=(0,Hl.default)(v).reduce((Ge,K)=>{var Kt;return Ge+((Kt=Fl(K))!=null?Kt:0)},0):m&&(d=parseInt(m,10));let S=(X=Fl((B=(0,Ul.default)(b,-1))==null?void 0:B.getAttribute("duration")))!=null?X:null,y=0,I=(F=(M=s.getAttribute("profiles"))==null?void 0:M.split(","))!=null?F:[];for(let Ge of b.map(K=>K.id))for(let K of g[Ge]){let Kt=(q=K.getAttribute("id"))!=null?q:"id"+(y++).toString(10),mi=(R=K.getAttribute("mimeType"))!=null?R:"",Qn=(H=K.getAttribute("codecs"))!=null?H:"",Wn=(N=K.getAttribute("contentType"))!=null?N:mi==null?void 0:mi.split("/")[0],FT=(k=(W=K.getAttribute("profiles"))==null?void 0:W.split(","))!=null?k:[],rd=(C=my((T=K.getAttribute("lang"))!=null?T:""))!=null?C:{},qT=(Ve=(se=(D=K.querySelector("Label"))==null?void 0:D.textContent)==null?void 0:se.trim())!=null?Ve:void 0,UT=K.querySelectorAll("Representation"),HT=K.querySelector("SegmentTemplate"),jT=(Er=(It=K.querySelector("Role"))==null?void 0:It.getAttribute("value"))!=null?Er:void 0,wr=Wn,te={id:Kt,language:rd.language,isDefault:jT==="main",label:qT,codecs:Qn,hdr:wr==="video"&&Cl(Qn),mime:mi,representations:[]};for(let Y of UT){let Pt=(j=Y.getAttribute("lang"))!=null?j:void 0,fi=(ce=Y.getAttribute("label"))!=null?ce:void 0,es=(Et=(Be=(de=Y.querySelector("BaseURL"))==null?void 0:de.textContent)==null?void 0:Be.trim())!=null?Et:"",Xt=new URL(es||o,e).toString(),wt=(xr=Y.getAttribute("mimeType"))!=null?xr:mi,ts=(zt=(xt=Y.getAttribute("codecs"))!=null?xt:Qn)!=null?zt:"",rs;if(Wn==="text"){let At=Y.getAttribute("id")||"",is=((Pr=rd.privateuse)==null?void 0:Pr.includes("x-auto"))||At.includes("_auto"),Jt=Y.querySelector("SegmentTemplate");if(Jt){let bi={representationId:(hi=Y.getAttribute("id"))!=null?hi:void 0,bandwidth:(Ic=Y.getAttribute("bandwidth"))!=null?Ic:void 0},as=parseInt((Ec=Y.getAttribute("bandwidth"))!=null?Ec:"",10)/1e3,ss=(Pc=parseInt((xc=Jt.getAttribute("startNumber"))!=null?xc:"",10))!=null?Pc:1,Ar=parseInt((wc=Jt.getAttribute("timescale"))!=null?wc:"",10),Yn=(Ac=Jt.querySelectorAll("SegmentTimeline S"))!=null?Ac:[],kr=Jt.getAttribute("media");if(!kr)continue;let ns=[],os=0,us="",Rr=0,gi=ss,be=0;for(let Qe of Yn){let Zt=parseInt((kc=Qe.getAttribute("d"))!=null?kc:"",10),_e=parseInt((Rc=Qe.getAttribute("r"))!=null?Rc:"",10)||0,kt=parseInt(($c=Qe.getAttribute("t"))!=null?$c:"",10);be=Number.isFinite(kt)?kt:be;let er=Zt/Ar*1e3,Rt=be/Ar*1e3;for(let rt=0;rt<_e+1;rt++){let $t=St(kr,$(E({},bi),{segmentNumber:gi.toString(10),segmentTime:(be+rt*Zt).toString(10)})),$r=(Rt!=null?Rt:0)+rt*er,Si=$r+er;gi++,ns.push({time:{from:$r,to:Si},url:$t})}be+=(_e+1)*Zt,os+=(_e+1)*er}Rr=be/Ar*1e3,us=St(kr,$(E({},bi),{segmentNumber:gi.toString(10),segmentTime:be.toString(10)}));let vi={time:{from:Rr,to:1/0},url:us},dt={type:"template",baseUrl:Xt,segmentTemplateUrl:kr,initUrl:"",totalSegmentsDurationMs:os,segments:ns,nextSegmentBeyondManifest:vi,timescale:Ar};rs={id:At,kind:"text",segmentReference:dt,profiles:[],duration:d,bitrate:as,mime:"",codecs:"",width:0,height:0,isAuto:is}}else rs={id:At,isAuto:is,kind:"text",url:Xt}}else{let At=(Mc=(Lc=Y.getAttribute("contentType"))!=null?Lc:wt==null?void 0:wt.split("/")[0])!=null?Mc:Wn,is=(Cc=(Dc=K.getAttribute("profiles"))==null?void 0:Dc.split(","))!=null?Cc:[],Jt=parseInt((Oc=Y.getAttribute("width"))!=null?Oc:"",10),bi=parseInt((Vc=Y.getAttribute("height"))!=null?Vc:"",10),as=parseInt((Bc=Y.getAttribute("bandwidth"))!=null?Bc:"",10)/1e3,ss=(_c=Y.getAttribute("frameRate"))!=null?_c:"",Ar=(Nc=Y.getAttribute("quality"))!=null?Nc:void 0,Yn=ss?hy(ss):void 0,kr=(Fc=Y.getAttribute("id"))!=null?Fc:"id"+(y++).toString(10),ns=At==="video"?`${bi}p`:At==="audio"?`${as}Kbps`:ts,os=`${kr}@${ns}`,us=[...I,...FT,...is],Rr,gi=Y.querySelector("SegmentBase"),be=(qc=Y.querySelector("SegmentTemplate"))!=null?qc:HT;if(gi){let dt=(Hc=(Uc=Y.querySelector("SegmentBase Initialization"))==null?void 0:Uc.getAttribute("range"))!=null?Hc:"",[Qe,Zt]=dt.split("-").map($t=>parseInt($t,10)),_e={from:Qe,to:Zt},kt=(jc=Y.querySelector("SegmentBase"))==null?void 0:jc.getAttribute("indexRange"),[er,Rt]=kt?kt.split("-").map($t=>parseInt($t,10)):[],rt=kt?{from:er,to:Rt}:void 0;Rr={type:"byteRange",url:Xt,initRange:_e,indexRange:rt}}else if(be){let dt={representationId:(Gc=Y.getAttribute("id"))!=null?Gc:void 0,bandwidth:(Qc=Y.getAttribute("bandwidth"))!=null?Qc:void 0},Qe=parseInt((Wc=be.getAttribute("timescale"))!=null?Wc:"",10),Zt=(Yc=be.getAttribute("initialization"))!=null?Yc:"",_e=be.getAttribute("media"),kt=(Kc=parseInt((zc=be.getAttribute("startNumber"))!=null?zc:"",10))!=null?Kc:1,er=St(Zt,dt);if(!_e)throw new ReferenceError("No media attribute in SegmentTemplate");let Rt=(Xc=be.querySelectorAll("SegmentTimeline S"))!=null?Xc:[],rt=[],$t=0,$r="",Si=0;if(Rt.length){let ls=kt,We=0;for(let Lr of Rt){let it=parseInt((Jc=Lr.getAttribute("d"))!=null?Jc:"",10),tr=parseInt((Zc=Lr.getAttribute("r"))!=null?Zc:"",10)||0,cs=parseInt((ed=Lr.getAttribute("t"))!=null?ed:"",10);We=Number.isFinite(cs)?cs:We;let zn=it/Qe*1e3,Kn=We/Qe*1e3;for(let ds=0;ds<tr+1;ds++){let QT=St(_e,$(E({},dt),{segmentNumber:ls.toString(10),segmentTime:(We+ds*it).toString(10)})),id=(Kn!=null?Kn:0)+ds*zn,WT=id+zn;ls++,rt.push({time:{from:id,to:WT},url:QT})}We+=(tr+1)*it,$t+=(tr+1)*zn}Si=We/Qe*1e3,$r=St(_e,$(E({},dt),{segmentNumber:ls.toString(10),segmentTime:We.toString(10)}))}else if(hD(d)){let We=parseInt((td=be.getAttribute("duration"))!=null?td:"",10)/Qe*1e3,Lr=Math.ceil(d/We),it=0;for(let tr=1;tr<Lr;tr++){let cs=St(_e,$(E({},dt),{segmentNumber:tr.toString(10),segmentTime:it.toString(10)}));rt.push({time:{from:it,to:it+We},url:cs}),it+=We}Si=it,$r=St(_e,$(E({},dt),{segmentNumber:Lr.toString(10),segmentTime:it.toString(10)}))}let GT={time:{from:Si,to:1/0},url:$r};Rr={type:"template",baseUrl:Xt,segmentTemplateUrl:_e,initUrl:er,totalSegmentsDurationMs:$t,segments:rt,nextSegmentBeyondManifest:GT,timescale:Qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!At||!wt)continue;let vi={video:"video",audio:"audio",text:"text"}[At];if(!vi)continue;wr||(wr=vi),rs={id:os,kind:vi,segmentReference:Rr,profiles:us,duration:d,bitrate:as,mime:wt,codecs:ts,width:Jt,height:bi,fps:Yn,quality:Ar}}te.language||(te.language=Pt),te.label||(te.label=fi),te.mime||(te.mime=wt),te.codecs||(te.codecs=ts),te.hdr||(te.hdr=wr==="video"&&Cl(ts)),te.representations.push(rs)}if(wr){let Y=i[wr].find(Pt=>Pt.id===te.id);if(Y&&te.representations.every(Pt=>ve(Pt.segmentReference)))for(let Pt of Y.representations){let fi=te.representations.find(wt=>wt.id===Pt.id),es=fi==null?void 0:fi.segmentReference,Xt=Pt.segmentReference;Xt.segments.push(...es.segments),Xt.nextSegmentBeyondManifest=es.nextSegmentBeyondManifest}else i[wr].push(te)}}return{dynamic:u,liveAvailabilityStartTime:c,duration:d,streams:i,baseUrls:n,liveLastPeriodDuration:S}};var xy=_(Xe(),1);import{isNonNullable as Ey}from"@vkontakte/videoplayer-shared/es2015";var ke=(a,e)=>Ey(a)&&Ey(e)&&a.readyState==="open"&&(0,xy.default)([...a.activeSourceBuffers],e);var La=class{constructor(e,t,r,{fetcher:i,tuning:s,getCurrentPosition:n,isActiveLowLatency:o,compatibilityMode:u=!1,manifest:l}){this.currentLiveSegmentServerLatency$=new gr(0);this.currentLowLatencySegmentLength$=new gr(0);this.currentSegmentLength$=new gr(0);this.onLastSegment$=new gr(!1);this.fullyBuffered$=new gr(!1);this.playingRepresentation$=new gr(void 0);this.playingRepresentationInit$=new gr(void 0);this.error$=new bD;this.gaps=[];this.subscription=new gD;this.allInitsLoaded=!1;this.activeSegments=new Set;this.downloadAbortController=new fe;this.switchAbortController=new fe;this.destroyAbortController=new fe;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=br(this.destroyAbortController.signal,function(e){return ae(this,null,function*(){let t=this.representations.get(e);je(t,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${t.mime}; codecs="${t.codecs}"`),this.sourceBufferTaskQueue=new IS(this.sourceBuffer),this.subscription.add(Gl(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},n=>{let o,u=this.mediaSource.readyState;u!=="open"&&(o={id:`SegmentEjection_source_${u}`,category:Ht.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),o!=null||(o={id:"SegmentEjection",category:Ht.VIDEO_PIPELINE,message:"Error when trying to clear segments ejected by browser",thrown:n}),this.error$.next(o)})),this.subscription.add(Gl(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:Ht.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(n=>{let o=this.getCurrentPosition();if(!this.sourceBuffer||!o||!ke(this.mediaSource,this.sourceBuffer))return;let u=Math.min(this.bufferLimit,wl(this.sourceBuffer.buffered)*.8);this.bufferLimit=u;let l=lt(this.sourceBuffer.buffered,o),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(o,n*2,l<c)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(n=>this.error$.next(n))),yield this.loadInit(t,"high",!0);let r=this.initData.get(t.id),i=this.segments.get(t.id),s=this.parsedInitData.get(t.id);je(r,"No init buffer for starting representation"),je(i,"No segments for starting representation"),r instanceof ArrayBuffer&&(this.searchGaps(i,t),yield this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(s))})}.bind(this));this.switchToOld=br(this.destroyAbortController.signal,function(e,t=!1){return ae(this,null,function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return;this.switchingToRepresentationId=e;let r=this.representations.get(e);je(r,`No such representation ${e}`);let i=this.segments.get(e),s=this.initData.get(e);if(Re(s)||Re(i)?yield this.loadInit(r,"high",!1):s instanceof Promise&&(yield s),i=this.segments.get(e),je(i,"No segments for starting representation"),s=this.initData.get(e),!(!s||!(s instanceof ArrayBuffer)||!this.sourceBuffer||!ke(this.mediaSource,this.sourceBuffer)))if(yield this.abort(),yield this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal),t)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,yield this.dropBuffer(),this.maintain();else{let n=this.getCurrentPosition();$a(n)&&(this.isLive||(this.bufferLimit=1/0,yield new Zn(this.pruneBuffer(n,1/0,!0))),this.maintain(n)),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e}})}.bind(this));this.seekLive=br(this.destroyAbortController.signal,function(e){return ae(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 p=this.representations.get(c);if(!p||!ve(p.segmentReference))return;let h=this.getActualLiveStartingSegments(p.segmentReference);this.segments.set(p.id,h)}let r=(l=this.switchingToRepresentationId)!=null?l:this.downloadingRepresentationId,i=this.representations.get(r);je(i);let s=this.segments.get(r);je(s,"No segments for starting representation");let n=this.initData.get(r);if(je(n,"No init buffer for starting representation"),!(n instanceof ArrayBuffer))return;let o=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,yield this.abort(),o&&(yield this.sourceBufferTaskQueue.remove(o.from*1e3,o.to*1e3,this.destroyAbortController.signal)),this.searchGaps(s,i),yield this.sourceBufferTaskQueue.append(n,this.destroyAbortController.signal),this.isSeekingLive=!1})}.bind(this));var c;this.fetcher=i,this.tuning=s,this.compatibilityMode=u,this.forwardBufferTarget=s.dash.forwardBufferTargetAuto,this.getCurrentPosition=n,this.isActiveLowLatency=o,this.isLive=!!(l!=null&&l.dynamic),this.baseUrls=(c=l==null?void 0:l.baseUrls)!=null?c:[],this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}switchTo(e,t=!1){return this.tuning.useNewSwitchTo?this.switchToNew(e,t):this.switchToOld(e,t)}switchToNew(e,t=!1){e===this.downloadingRepresentationId||e===this.switchingToRepresentationId||(this.switchAbortController.abort(),this.switchAbortController=new fe,br(this.switchAbortController.signal,function(r,i=!1){return ae(this,null,function*(){this.switchingToRepresentationId=r;let s=this.representations.get(r);je(s,`No such representation ${r}`);let n=this.segments.get(r),o=this.initData.get(r);if(Re(o)||Re(n)?yield this.loadInit(s,"high",!1):o instanceof Promise&&(yield o),n=this.segments.get(r),je(n,"No segments for starting representation"),o=this.initData.get(r),!(!(o instanceof ArrayBuffer)||!this.sourceBuffer||!ke(this.mediaSource,this.sourceBuffer))){if(yield this.abort(),yield this.sourceBufferTaskQueue.append(o,this.downloadAbortController.signal),i)this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=r,yield this.dropBuffer();else{let u=this.getCurrentPosition();$a(u)&&!this.isLive&&(this.bufferLimit=this.forwardBufferTarget,yield this.pruneBuffer(u,1/0,!0)),this.downloadingRepresentationId=r,this.switchingToRepresentationId=void 0}this.maintain()}})}.bind(this))(e,t))}warmUpMediaSource(){!Re(this.sourceBuffer)&&!this.sourceBuffer.updating&&(this.sourceBuffer.mode="segments")}abort(){return A(this,null,function*(){for(let e of this.activeSegments)this.abortSegment(e.segment);return this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new fe,this.abortBuffer()})}maintain(e=this.getCurrentPosition()){if(Re(e)||Re(this.downloadingRepresentationId)||Re(this.playingRepresentationId)||Re(this.sourceBuffer)||!ke(this.mediaSource,this.sourceBuffer)||$a(this.switchingToRepresentationId)||this.isSeekingLive)return;let t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(je(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;let i=r.find(l=>e>=l.time.from&&e<l.time.to);$a(i)&&isFinite(i.time.from)&&isFinite(i.time.to)&&this.currentSegmentLength$.next((i==null?void 0:i.time.to)-i.time.from);let s=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){let c=lt(this.sourceBuffer.buffered,e),d=i?i.time.to+100:-1/0;i&&i.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=i.time.to-e+100&&(s=d)}if(isFinite(this.bufferLimit)&&wl(this.sourceBuffer.buffered)>=this.bufferLimit){let l=lt(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,l<c);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(r,t.segmentReference.type,s),o.length)){let l="auto";if(this.tuning.dash.useFetchPriorityHints&&i)if((0,Sn.default)(o,i))l="high";else{let c=(0,oi.default)(o,0);c&&c.time.from-i.time.to>=this.forwardBufferTarget/2&&(l="low")}this.loadSegments(o,t,l)}(!this.preloadOnly&&!this.allInitsLoaded&&i&&i.status==="fed"&&!o.length&&lt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();let u=(0,oi.default)(r,-1);u&&u.status==="fed"&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(i===u))}get lastDataObtainedTimestamp(){return this.lastDataObtainedTimestampMs}searchGaps(e,t){this.gaps=[];let r=0,i=this.isLive?this.liveInitialAdditionalOffset:0;for(let s of e)Math.trunc(s.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from+i}),r=s.time.to;$a(t.duration)&&t.duration-r>0&&!this.isLive&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){let t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,i=[],s=0,n=t.length-1;do i.unshift(t[n]),s+=t[n].time.to-t[n].time.from,n--;while(s<r&&n>=0);return this.liveInitialAdditionalOffset=s-r,this.isActiveLowLatency()?[i[0]]:i}getLiveSegmentsToLoadState(e){let t=(0,yn.default)(e==null?void 0:e.streams[this.kind],i=>i.representations).find(i=>i.id===this.downloadingRepresentationId);if(!t)return;let r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var r,i,s,n;let t=(r=(0,yn.default)(e==null?void 0:e.streams[this.kind],o=>o.representations))!=null?r:[];if(![...this.segments.values()].every(o=>!o.length))for(let o of t){if(!o||!ve(o.segmentReference))return;let u=o.segmentReference.segments.map(h=>$(E({},h),{status:"none",size:void 0})),l=100,c=(i=this.segments.get(o.id))!=null?i:[],d=(n=(s=(0,oi.default)(c,-1))==null?void 0:s.time.to)!=null?n:0,p=u==null?void 0:u.findIndex(h=>d>=h.time.from+l&&d<=h.time.to+l);if(p===-1){this.liveUpdateSegmentIndex=0;let h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{let h=u.slice(p+1);this.segments.set(o.id,[...c,...h])}}}proceedLowLatencyLive(){let e=this.downloadingRepresentationId;je(e);let t=this.segments.get(e);if(t!=null&&t.length){let r=t[t.length-1];this.updateLowLatencyLiveIfNeeded(r)}}updateLowLatencyLiveIfNeeded(e){var r;let t=0;for(let i of this.representations.values()){let s=i.segmentReference;if(!ve(s))return;let n=(r=this.segments.get(i.id))!=null?r:[],o=n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.from));if(o&&!isFinite(o.time.to)&&(o.time.to=e.time.to,t=o.time.to-o.time.from),!!!n.find(l=>Math.floor(l.time.from)===Math.floor(e.time.to))&&this.isActiveLowLatency()){let l=Math.round(e.time.to*s.timescale/1e3).toString(10),c=St(s.segmentTemplateUrl,{segmentTime:l});n.push({status:"none",time:{from:e.time.to,to:1/0},url:c})}}this.currentLowLatencySegmentLength$.next(t)}findSegmentStartTime(e){var s,n,o;let t=(n=(s=this.switchingToRepresentationId)!=null?s:this.downloadingRepresentationId)!=null?n:this.playingRepresentationId;if(!t)return;let r=this.segments.get(t);if(!r)return;let i=r.find(u=>u.time.from<=e&&u.time.to>=e);return(o=i==null?void 0:i.time.from)!=null?o:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)==null||e.destroy(),this.gapDetectionIdleCallback&&sa&&sa(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&sa&&sa(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer)try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}this.sourceBuffer=null,this.downloadAbortController.abort(),this.switchAbortController.abort(),this.destroyAbortController.abort(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){let r=e.findIndex(i=>t>=i.time.from&&t<i.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){let i=e.findIndex(({status:d,time:{from:p,to:h}},m)=>{let b=p<=r&&h>=r,g=p>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&p<=r+v||h<=r+v;return(d==="none"||d==="partially_ejected"&&g&&S&&this.sourceBuffer&&ke(this.mediaSource,this.sourceBuffer)&&!(qt(this.sourceBuffer.buffered,p)&&qt(this.sourceBuffer.buffered,h)))&&g&&S});if(i===-1)return[];if(t!=="byteRange")return e.slice(i,i+1);let s=e,n=0,o=0,u=[],l=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let d=i;d<s.length&&(n<=l||o<=c);d++){let p=s[d];if(n+=p.byte.to+1-p.byte.from,o+=p.time.to+1-p.time.from,p.status==="none"||p.status==="partially_ejected")u.push(p);else break}return u}loadSegments(e,t,r="auto"){return A(this,null,function*(){ve(t.segmentReference)?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return A(this,null,function*(){e.status="downloading";let i={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(i);let{range:s,url:n,signal:o,onProgress:u,onProgressTasks:l}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield br(o,function(){return ae(this,null,function*(){let c=Ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,c))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{let c=yield this.fetcher.fetch(n,{range:s,signal:o,onProgress:u,priority:r,isLowLatency:this.isActiveLowLatency()});if(this.lastDataObtainedTimestampMs=vn(),!c)return;let d=new DataView(c),p=ka(t.mime);if(!isFinite(i.segment.time.to)){let b=t.segmentReference.timescale;i.segment.time.to=p.getChunkEndTime(d,b)}u&&i.feedingBytes&&l?yield Promise.all(l):yield this.sourceBufferTaskQueue.append(d,o);let{serverDataReceivedTimestamp:h,serverDataPreparedTime:m}=p.getServerLatencyTimestamps(d);h&&m&&this.currentLiveSegmentServerLatency$.next(m-h),i.segment.status="downloaded",this.onSegmentFullyAppended(i,t.id),this.failedDownloads=0}catch(c){this.abortActiveSegments([e]),Ra(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())ve(t.segmentReference)?t.segmentReference.baseUrl=e:t.segmentReference.url=e}loadByteRangeSegments(e,t,r="auto"){return A(this,null,function*(){if(!e.length)return;for(let u of e)u.status="downloading",this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});let{range:i,url:s,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield br(n,function(){return ae(this,null,function*(){let u=Ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>{this.loadByteRangeSegmentsTimeoutId=window.setTimeout(l,u),Gl(window,"online").pipe(fD()).subscribe(()=>{l(),window.clearTimeout(this.loadByteRangeSegmentsTimeoutId)})})})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(s,{range:i,onProgress:o,signal:n,priority:r}),this.lastDataObtainedTimestampMs=vn(),this.failedDownloads=0}catch(u){this.abortActiveSegments(e),Ra(u)||(this.failedDownloads++,this.updateRepresentationsBaseUrlIfNeeded())}})}prepareByteRangeFetchSegmentParams(e,t){if(ve(t.segmentReference))throw new Error("Representation is not byte range type");let r=t.segmentReference.url,i={from:(0,oi.default)(e,0).byte.from,to:(0,oi.default)(e,-1).byte.to},{signal:s}=this.downloadAbortController;return{url:r,range:i,signal:s,onProgress:(o,u)=>A(this,null,function*(){if(!s.aborted)try{this.lastDataObtainedTimestampMs=vn(),yield this.onSomeByteRangesDataLoaded({dataView:o,loaded:u,signal:s,onSegmentAppendFailed:()=>this.abort(),globalFrom:i?i.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}})}}prepareTemplateFetchSegmentParams(e,t){if(!ve(t.segmentReference))throw new Error("Representation is not template type");let r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");let i=r.toString(),{signal:s}=this.downloadAbortController,n=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!s.aborted)try{this.lastDataObtainedTimestampMs=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:Ht.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}:void 0;return{url:i,signal:s,onProgress:u,onProgressTasks:n}}abortActiveSegments(e){for(let t of this.activeSegments)(0,Sn.default)(e,t.segment)&&this.abortSegment(t.segment)}onSomeTemplateDataLoaded(n){return A(this,arguments,function*({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:i,signal:s}){if(!this.activeSegments.size)return;let o=this.representations.get(t);if(o)for(let u of this.activeSegments){let{segment:l}=u;if(u.representationId===t){if(s.aborted){i();continue}if(u.loadedBytes=r,u.loadedBytes>u.feedingBytes){let c=new DataView(e.buffer,e.byteOffset+u.feedingBytes,u.loadedBytes-u.feedingBytes),d=ka(o.mime).parseFeedableSegmentChunk(c,this.isLive);d!=null&&d.byteLength&&(l.status="partially_fed",u.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),u.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded(o){return A(this,arguments,function*({dataView:e,representationId:t,globalFrom:r,loaded:i,signal:s,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;let u=this.representations.get(t);if(u)for(let l of this.activeSegments){let{segment:c}=l;if(l.representationId!==t)continue;if(s.aborted){yield n();continue}let d=c.byte.from-r,p=c.byte.to-r,h=p-d+1,m=d<i,b=p<=i;if(!m)continue;let g=ka(u.mime);if(c.status==="downloading"&&b){c.status="downloaded";let v=new DataView(e.buffer,e.byteOffset+d,h);(yield this.sourceBufferTaskQueue.append(v,s))&&!s.aborted?this.onSegmentFullyAppended(l,t):yield n()}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&(c.status==="downloading"||c.status==="partially_fed")&&(l.loadedBytes=Math.min(h,i-d),l.loadedBytes>l.feedingBytes)){let v=new DataView(e.buffer,e.byteOffset+d+l.feedingBytes,l.loadedBytes-l.feedingBytes),S=l.loadedBytes===h?v:g.parseFeedableSegmentChunk(v);S!=null&&S.byteLength&&(c.status="partially_fed",l.feedingBytes+=S.byteLength,(yield this.sourceBufferTaskQueue.append(S,s))&&!s.aborted?(l.fedBytes+=S.byteLength,l.fedBytes===h&&this.onSegmentFullyAppended(l,t)):yield n())}}})}onSegmentFullyAppended(e,t){var r;if(!(Re(this.sourceBuffer)||!ke(this.mediaSource,this.sourceBuffer))){!this.isLive&&mD.isSafari&&this.tuning.useSafariEndlessRequestBugfix&&(qt(this.sourceBuffer.buffered,e.segment.time.from,100)&&qt(this.sourceBuffer.buffered,e.segment.time.to,100)||this.error$.next({id:"EmptyAppendBuffer",category:Ht.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",Nl(e.segment)&&(e.segment.size=e.fedBytes);for(let i of this.representations.values())if(i.id!==t)for(let s of(r=this.segments.get(i.id))!=null?r:[])s.status==="fed"&&Math.round(s.time.from)===Math.round(e.segment.time.from)&&Math.round(s.time.to)===Math.round(e.segment.time.to)&&(s.status="none");this.updateLowLatencyLiveIfNeeded(e.segment),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}}abortSegment(e){e.status==="partially_fed"?e.status="partially_ejected":e.status!=="partially_ejected"&&(e.status="none");for(let t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(let[i,s]of this.initData.entries()){let n=s instanceof Promise;t||(t=n),s===null&&(e=i)}if(!e){this.allInitsLoaded=!0;return}if(t)return;let r=this.representations.get(e);r&&(this.initLoadIdleCallback=El(()=>(0,Py.default)(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return A(this,null,function*(){let i=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!r&&this.failedDownloads>0?br(this.destroyAbortController.signal,function(){return ae(this,null,function*(){let o=Ql(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,ka(e.mime),i)).then(o=>A(this,null,function*(){if(!o)return;let{init:u,dataView:l,segments:c}=o,d=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength);this.initData.set(e.id,d);let p=c;this.isLive&&ve(e.segmentReference)&&(p=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,p),u&&this.parsedInitData.set(e.id,u)})).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:Ht.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}dropBuffer(){return A(this,null,function*(){for(let e of this.segments.values())for(let t of e)t.status="none";yield this.pruneBuffer(0,1/0,!0)})}pruneBuffer(e,t,r=!1){return A(this,null,function*(){if(!this.sourceBuffer||!ke(this.mediaSource,this.sourceBuffer)||!this.playingRepresentationId||Re(e))return!1;let i=[],s=0,n=u=>{u.sort((c,d)=>c.from-d.from);let l=[u[0]];for(let c=1;c<u.length;c++){let{from:d,to:p}=u[c],h=l[l.length-1];h.to>=d?h.to=Math.max(h.to,p):l.push(u[c])}return l},o=u=>{var c;if(s>=t)return i;i.push(E({},u.time)),i=n(i);let l=Nl(u)?(c=u.size)!=null?c:0:u.byte.to-u.byte.from;s+=l};for(let u of this.segments.values())for(let l of u){let c=l.time.to<=e-this.tuning.dash.bufferPruningSafeZone,d=l.time.from>=e+Math.min(this.forwardBufferTarget,this.bufferLimit);(c||d)&&l.status==="fed"&&o(l)}for(let u=0;u<this.sourceBuffer.buffered.length;u++){let l=this.sourceBuffer.buffered.start(u)*1e3,c=this.sourceBuffer.buffered.end(u)*1e3,d=0;for(let p of this.segments.values())for(let h of p)(0,Sn.default)(["none","partially_ejected"],h.status)&&Math.round(h.time.from)<=Math.round(l)&&Math.round(h.time.to)>=Math.round(c)&&d++;if(d===this.segments.size){let p={time:{from:l,to:c},url:"",status:"none"};o(p)}}if(i.length&&r){let u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(let l of this.segments.values())for(let c of l)c.time.from>=e+u&&c.status==="fed"&&o(c)}return i.length?(yield Promise.all(i.map(l=>this.sourceBufferTaskQueue.remove(l.from,l.to)))).reduce((l,c)=>l||c,!1):!1})}abortBuffer(){return A(this,null,function*(){if(!this.sourceBuffer||!ke(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||!ke(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}getForwardBufferDuration(){let e=this.getCurrentPosition();return!this.sourceBuffer||!ke(this.mediaSource,this.sourceBuffer)||!this.sourceBuffer.buffered.length||Re(e)?0:lt(this.sourceBuffer.buffered,e)}detectGaps(e,t){if(!(!this.sourceBuffer||!ke(this.mediaSource,this.sourceBuffer)))for(let r of t){let i={representation:e,from:r.time.from,to:r.time.to};for(let s=0;s<this.sourceBuffer.buffered.length;s++){let n=this.sourceBuffer.buffered.start(s)*1e3,o=this.sourceBuffer.buffered.end(s)*1e3;if(!(o<=r.time.from||n>=r.time.to)){if(n<=r.time.from&&o>=r.time.to){i=void 0;break}o>r.time.from&&o<r.time.to&&(i.from=o),n<r.time.to&&n>r.time.from&&(i.to=n)}}i&&i.to-i.from>1&&!this.gaps.some(s=>i&&s.from===i.from&&s.to===i.to)&&this.gaps.push(i)}}detectGapsWhenIdle(e,t){if(!(this.gapDetectionIdleCallback||!this.sourceBuffer||!ke(this.mediaSource,this.sourceBuffer))){for(let r=0;r<this.sourceBuffer.buffered.length;r++)this.gaps=this.gaps.filter(i=>this.sourceBuffer&&(Math.round(i.from)<Math.round(this.sourceBuffer.buffered.start(r)*1e3)||Math.round(i.to)>Math.round(this.sourceBuffer.buffered.end(r)*1e3)));this.gapDetectionIdleCallback=El(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:Ht.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}})}}checkEjectedSegments(){if(Re(this.sourceBuffer)||!ke(this.mediaSource,this.sourceBuffer)||Re(this.playingRepresentationId))return;let e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){let i=Math.floor(this.sourceBuffer.buffered.start(r)*1e3),s=Math.ceil(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:i,to:s})}let t=100;for(let r of this.segments.values())for(let i of r){let{status:s}=i;if(s!=="fed"&&s!=="partially_ejected")continue;let n=Math.floor(i.time.from),o=Math.ceil(i.time.to),u=e.some(c=>c.from-t<=n&&c.to+t>=o),l=e.filter(c=>n>=c.from&&n<c.to-t||o>c.from+t&&o<=c.to);u||(l.length===1?i.status="partially_ejected":this.gaps.some(c=>c.from===i.time.from||c.to===i.time.to)?i.status="partially_ejected":i.status="none")}}};var Ma=a=>{let e=new URL(a);return e.searchParams.set("quic","1"),e.toString()};var wy=a=>{var s;let e=a.get("X-Delivery-Type"),t=a.get("X-Reused"),r=e===null?"http1":e!=null?e:void 0,i=t===null?void 0:(s={1:!0,0:!1}[t])!=null?s:void 0;return{type:r,reused:i}};import{abortable as Da,assertNever as ky,fromEvent as Ry,merge as vD,now as Ca,Subscription as SD,ValueSubject as Wl,flattenObject as ui}from"@vkontakte/videoplayer-shared/es2015";var Ay=a=>{let e=new URL(a);return e.searchParams.set("enable-subtitles","yes"),e.toString()};var Tn=class{constructor({throughputEstimator:e,requestQuic:t,tracer:r,compatibilityMode:i=!1,useEnableSubtitlesParam:s=!1}){this.lastConnectionType$=new Wl(void 0);this.lastConnectionReused$=new Wl(void 0);this.lastRequestFirstBytes$=new Wl(void 0);this.abortAllController=new fe;this.subscription=new SD;this.fetchManifest=Da(this.abortAllController.signal,function(e){return ae(this,null,function*(){let t=this.tracer.createComponentTracer("FetchManifest"),r=e;this.requestQuic&&(r=Ma(r)),!this.compatibilityMode&&this.useEnableSubtitlesParam&&(r=Ay(r));let i=yield Ze(r,{signal:this.abortAllController.signal}).catch(Oa);return i?(t.log("success",ui({url:r,message:"Request successfully executed"})),t.end(),this.onHeadersReceived(i.headers),i.text()):(t.error("error",ui({url:r,message:"No data in request manifest"})),t.end(),null)})}.bind(this));this.fetch=Da(this.abortAllController.signal,function(l){return ae(this,arguments,function*(e,{rangeMethod:t=this.compatibilityMode?0:1,range:r,onProgress:i,priority:s="auto",signal:n,measureThroughput:o=!0,isLowLatency:u=!1}={}){var R,H;let c=e,d=new Headers,p=this.tracer.createComponentTracer("Fetch");if(r)switch(t){case 0:{d.append("Range",`bytes=${r.from}-${r.to}`);break}case 1:{let N=new URL(c,location.href);N.searchParams.append("bytes",`${r.from}-${r.to}`),c=N.toString();break}default:ky(t)}this.requestQuic&&(c=Ma(c));let h=this.abortAllController.signal,m;if(n){let N=new fe;if(m=vD(Ry(this.abortAllController.signal,"abort"),Ry(n,"abort")).subscribe(()=>{try{N.abort()}catch(W){Oa(W)}}),this.abortAllController.signal.aborted||n.aborted)try{N.abort()}catch(W){Oa(W)}h=N.signal}let b=Ca();p.log("startRequest",ui({url:c,priority:s,rangeMethod:t,range:r,isLowLatency:u,requestStartedAt:b}));let g=yield Ze(c,{priority:s,headers:d,signal:h}).catch(Oa),v=Ca();if(!g)return p.error("error",{message:"No response in request"}),p.end(),m==null||m.unsubscribe(),null;if((R=this.throughputEstimator)==null||R.addRawRtt(v-b),!g.ok||!g.body){m==null||m.unsubscribe();let N=`Fetch error ${g.status}: ${g.statusText}`;return p.error("error",{message:N}),p.end(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`))}if(this.onHeadersReceived(g.headers),!i&&!o){m==null||m.unsubscribe();let N=Ca(),W={requestStartedAt:b,requestEndedAt:N,duration:N-b};return p.log("endRequest",ui(W)),p.end(),g.arrayBuffer()}let[S,y]=g.body.tee(),I=S.getReader();o&&((H=this.throughputEstimator)==null||H.trackStream(y,u));let w=0,L=new Uint8Array(0),B=!1,X=N=>{m==null||m.unsubscribe(),B=!0,Oa(N)},M=Da(h,function(k){return ae(this,arguments,function*({done:N,value:W}){if(w===0&&this.lastRequestFirstBytes$.next(Ca()-b),h.aborted){m==null||m.unsubscribe();return}if(!N&&W){let T=new Uint8Array(L.length+W.length);T.set(L),T.set(W,L.length),L=T,w+=W.byteLength,i==null||i(new DataView(L.buffer),w),yield I==null?void 0:I.read().then(M,X)}})}.bind(this));yield I==null?void 0:I.read().then(M,X),m==null||m.unsubscribe();let F=Ca(),q={failed:B,requestStartedAt:b,requestEndedAt:F,duration:F-b};return B?(p.error("endRequest",ui(q)),p.end(),null):(p.log("endRequest",ui(q)),p.end(),L.buffer)})}.bind(this));this.fetchByteRangeRepresentation=Da(this.abortAllController.signal,function(e,t,r){return ae(this,null,function*(){var v;if(e.type!=="byteRange")return null;let{from:i,to:s}=e.initRange,n=i,o=s,u=!1,l,c;e.indexRange&&(l=e.indexRange.from,c=e.indexRange.to,u=s+1===l,u&&(n=Math.min(l,i),o=Math.max(c,s))),n=Math.min(n,0);let d=yield this.fetch(e.url,{range:{from:n,to:o},priority:r,measureThroughput:!1});if(!d)return null;let p=new DataView(d,i-n,s-n+1);if(!t.validateData(p))throw new Error("Invalid media file");let h=t.parseInit(p),m=(v=e.indexRange)!=null?v:t.getIndexRange(h);if(!m)throw new ReferenceError("No way to load representation index");let b;if(u)b=new DataView(d,m.from-n,m.to-m.from+1);else{let S=yield this.fetch(e.url,{range:m,priority:r,measureThroughput:!1});if(!S)return null;b=new DataView(S)}let g=t.parseSegments(b,h,m);return{init:h,dataView:new DataView(d),segments:g}})}.bind(this));this.fetchTemplateRepresentation=Da(this.abortAllController.signal,function(e,t){return ae(this,null,function*(){if(e.type!=="template")return null;let r=new URL(e.initUrl,e.baseUrl).toString(),i=yield this.fetch(r,{priority:t,measureThroughput:!1});return i?{init:null,segments:e.segments.map(n=>$(E({},n),{status:"none",size:void 0})),dataView:new DataView(i)}:null})}.bind(this));this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i,this.tracer=r.createComponentTracer("Fetcher"),this.useEnableSubtitlesParam=s}onHeadersReceived(e){let{type:t,reused:r}=wy(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){return A(this,null,function*(){var s,n;let{type:i}=e;switch(i){case"byteRange":return(s=yield this.fetchByteRangeRepresentation(e,t,r))!=null?s:null;case"template":return(n=yield this.fetchTemplateRepresentation(e,r))!=null?n:null;default:ky(i)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe(),this.tracer.end()}},Oa=a=>{if(!Ra(a))throw a};var vr=(a,e,t)=>t*e+(1-t)*a,Yl=(a,e)=>a.reduce((t,r)=>t+r,0)/e,$y=(a,e,t,r)=>{let i=0,s=t,n=Yl(a,e),o=e<r?e:r;for(let u=0;u<o;u++)a[s]>n?i++:i--,s=(a.length+s-1)%a.length;return Math.abs(i)===o};import{isNullable as yD,ValueSubject as Ly}from"@vkontakte/videoplayer-shared/es2015";var jt=class{constructor(e){this.prevReported=void 0;this.pastMeasures=[];this.takenMeasures=0;this.measuresCursor=0;var r;this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new Ly(e.initial),this.debounced$=new Ly(e.initial);let t=(r=e.label)!=null?r:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ge(`raw_${t}`),this.smoothedSeries$=new ge(`smoothed_${t}`),this.reportedSeries$=new ge(`reported_${t}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=at(this.pastMeasures[o]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;let i=Math.sqrt(t),s=this.smoothed+this.params.deviationFactor*i,n=this.smoothed-this.params.deviationFactor*i;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>s||this.smoothed<n)&&(yD(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 In=class extends jt{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=vr(this.slow,e,this.params.emaAlphaSlow),this.fast=vr(this.fast,e,this.params.emaAlphaFast);let t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}};var En=class extends jt{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){let t=Yl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=vr(this.emaSmoothed,e,this.params.emaAlpha);let r=$y(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}};var xn=class extends jt{constructor(t){super(t);this.furtherValues=[];this.currentTopExtremumValue=0;this.extremumInterval=t.extremumInterval}next(t){this.currentTopExtremumValue<=t?(this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=t,this.furtherValues=[]):this.furtherValues.push(t)}updateSmoothedValue(t){this.smoothed=this.smoothed?vr(this.smoothed,t,this.params.emaAlpha):t}};var Sr=class{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new In({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new En({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveBufferSmoothedValue(e,t){return new xn(E({initial:e,label:"liveEdgeDelay"},t))}};var zl=(a,e)=>{a&&a.playbackRate!==e&&(a.playbackRate=e)};import{isNullable as TD,ValueSubject as ID}from"@vkontakte/videoplayer-shared/es2015";var Va=class a{constructor(e,t){this.currentRepresentation$=new ID(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(!TD(e))for(let r of this.representations)for(let i of r){let s=i.segmentReference,n=s.segments.length,o=s.segments[0].time.from,u=s.segments[n-1].time.to;if(e<o||e>u)continue;let l=s.segments.find(c=>c.time.from<=e&&c.time.to>=e);!l||((t=this.currentSegment)==null?void 0:t.time.from)===l.time.from&&this.currentSegment.time.to===l.time.to||(this.currentSegment=l,this.currentRepresentation$.next($(E({},i),{label:"Live Text",language:"ru",isAuto:!0,url:new URL(l.url,s.baseUrl).toString()})))}}destroy(){this.currentRepresentation$.next(null),this.currentSegment=null,this.representations=[]}processStreams(e){for(let t of e!=null?e:[]){let r=a.filterRepresentations(t.representations);if(r){this.representations[this.representationsCursor]=r,this.representationsCursor=(this.representationsCursor+1)%this.maxRepresentations;break}}}static isSupported(e){return!!(e!=null&&e.some(t=>a.filterRepresentations(t.representations)))}static filterRepresentations(e){return e==null?void 0:e.filter(t=>t.kind==="text"&&"segmentReference"in t&&ve(t.segmentReference))}};var $D=["timeupdate","progress","play","seeked","stalled","waiting"],LD=["timeupdate","progress","loadeddata","playing","seeked"];var wn=class{constructor(e){this.element=null;this.manifestUrlString="";this.source=null;this.manifest=null;this.subscription=new Oy;this.representationSubscription=new Oy;this.state$=new O("none");this.currentVideoRepresentation$=new ee(void 0);this.currentVideoRepresentationInit$=new ee(void 0);this.currentAudioRepresentation$=new ee(void 0);this.currentVideoSegmentLength$=new ee(0);this.currentAudioSegmentLength$=new ee(0);this.error$=new Cy;this.lastConnectionType$=new ee(void 0);this.lastConnectionReused$=new ee(void 0);this.lastRequestFirstBytes$=new ee(void 0);this.currentLiveTextRepresentation$=new ee(null);this.isLive$=new ee(!1);this.liveDuration$=new ee(0);this.liveAvailabilityStartTime$=new ee(void 0);this.bufferLength$=new ee(0);this.liveLatency$=new ee(void 0);this.liveLoadBufferLength$=new ee(0);this.livePositionFromPlayer$=new ee(0);this.isLowLatency$=new ee(!1);this.isActiveLowLatency$=new ee(!1);this.currentStallDuration$=new ee(0);this.videoLastDataObtainedTimestamp$=new ee(0);this.liveLastPeriodDuration$=new ee(null);this.isUpdatingLive=!1;this.isJumpGapAfterSeekLive=!1;this.liveLastSeekOffset=0;this.forceEnded$=new Cy;this.gapWatchdogActive=!1;this.destroyController=new fe;this.initManifest=Xl(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var i;this.tracer.log("initManifest"),this.element=e,this.manifestUrlString=me(t,r,2),this.state$.startTransitionTo("manifest_ready"),this.manifest=yield this.updateManifest(),(i=this.manifest)!=null&&i.streams.video.length?this.state$.setState("manifest_ready"):this.error$.next({id:"NoRepresentations",category:Gt.PARSER,message:"No playable video representations"})})}.bind(this));this.updateManifest=Xl(this.destroyController.signal,function(){return ae(this,null,function*(){var n,o;this.tracer.log("updateManifestStart",{manifestUrl:this.manifestUrlString});let e=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(u=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:Gt.NETWORK,message:"Failed to load manifest",thrown:u})});if(!e)return null;let t=null;try{t=Iy(e!=null?e:"",this.manifestUrlString)}catch(u){let l=(n=bS(e))!=null?n:{id:"ManifestParsing",category:Gt.PARSER,message:"Failed to parse MPD manifest",thrown:u};this.error$.next(l)}if(!t)return null;let r=(u,l,c)=>{var d,p,h,m;return!!((p=(d=this.element)==null?void 0:d.canPlayType)!=null&&p.call(d,l)&&((m=(h=gt())==null?void 0:h.isTypeSupported)!=null&&m.call(h,`${l}; codecs="${c}"`))||u==="text")};if(t.dynamic){this.isLive$.next(t.dynamic),this.liveAvailabilityStartTime$.next(t.liveAvailabilityStartTime);let u=((o=t.duration)!=null?o:0)/1e3;this.liveDuration$.next(-1*u),this.liveLastPeriodDuration$.next(t.liveLastPeriodDuration)}let i={text:t.streams.text,video:[],audio:[]};for(let u of["video","audio"]){let c=t.streams[u].filter(({mime:h,codecs:m})=>r(u,h,m)),d=new Set(c.map(({codecs:h})=>h)),p=Yv(d);if(p&&(i[u]=c.filter(({codecs:h})=>h.startsWith(p))),u==="video"){let h=this.tuning.preferHDR,m=i.video.some(g=>g.hdr),b=i.video.some(g=>!g.hdr);PD.isHDR&&h&&m?i.video=i.video.filter(g=>g.hdr):b&&(i.video=i.video.filter(g=>!g.hdr))}}let s=$(E({},t),{streams:i});return this.tracer.log("updateManifestEnd",_a(s)),s})}.bind(this));this.initRepresentations=Xl(this.destroyController.signal,function(e,t,r){return ae(this,null,function*(){var d;this.tracer.log("initRepresentationsStart",_a({initialVideo:e,initialAudio:t,sourceHls:r})),li(this.manifest),li(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo("representations_ready");let i=p=>{this.representationSubscription.add(yr(p,"error").pipe(Ba(h=>{var m;return!!((m=this.element)!=null&&m.played.length)})).subscribe(h=>{this.error$.next({id:"VideoSource",category:Gt.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:h})}))};this.source=this.tuning.useManagedMediaSource?Lv():new MediaSource;let s=document.createElement("source");if(i(s),s.src=URL.createObjectURL(this.source),this.element.appendChild(s),this.tuning.useManagedMediaSource&&on())if(r){let p=document.createElement("source");i(p),p.type="application/x-mpegurl",p.src=r.url,this.element.appendChild(p)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency$.next(this.isLive$.getValue()&&this.isLowLatency$.getValue());let n={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency$.getValue(),manifest:this.manifest},o=this.manifest.streams.video.reduce((p,h)=>[...p,...h.representations],[]);if(this.videoBufferManager=new La("video",this.source,o,n),this.bufferManagers=[this.videoBufferManager],Dy(t)){let p=this.manifest.streams.audio.reduce((h,m)=>[...h,...m.representations],[]);this.audioBufferManager=new La("audio",this.source,p,n),this.bufferManagers.push(this.audioBufferManager)}Va.isSupported(this.manifest.streams.text)&&!this.isLowLatency$.getValue()&&(this.liveTextManager=new Va(this.manifest.streams.text,n)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Jl(1e3).subscribe(p=>{var h;if((h=this.element)!=null&&h.paused){let m=Ys(this.manifestUrlString,2);this.manifestUrlString=me(this.manifestUrlString,m+1e3,2)}}));let u=()=>{var p;(p=this.stallWatchdogSubscription)==null||p.unsubscribe(),this.currentStallDuration$.next(0)};if(this.representationSubscription.add(Tr(...LD.map(p=>yr(this.element,p))).pipe(Na(p=>this.element?lt(this.element.buffered,this.element.currentTime*1e3):0),Pn(),kD(p=>{p>this.tuning.dash.bufferEmptinessTolerance&&u()})).subscribe(this.bufferLength$)),this.representationSubscription.add(Tr(yr(this.element,"ended"),this.forceEnded$).subscribe(()=>{u()})),this.isLive$.getValue()){this.representationSubscription.add(this.isActiveLowLatency$.pipe(Pn()).subscribe(h=>zl(this.element,1))),this.representationSubscription.add(ci({bufferLength:this.bufferLength$,isActiveLowLatency:this.isActiveLowLatency$}).pipe(Ba(({bufferLength:h,isActiveLowLatency:m})=>m&&!!h)).subscribe(({bufferLength:h})=>this.liveBuffer.next(h))),this.representationSubscription.add(ci({isActiveLowLatency:this.isActiveLowLatency$.pipe(Pn()),currentLowLatencySegmentLength:this.videoBufferManager.currentLowLatencySegmentLength$}).pipe(Ba(({isActiveLowLatency:h,currentLowLatencySegmentLength:m})=>h&&!!m)).subscribe(({currentLowLatencySegmentLength:h})=>{let m=this.liveDuration$.getValue()-h/1e3;this.liveDuration$.next(Math.min(m,this.tuning.dashCmafLive.maxLiveDuration))})),this.representationSubscription.add(ci({isLive:this.isLive$,rtt:this.throughputEstimator.rtt$,bufferLength:this.bufferLength$,segmentServerLatency:this.videoBufferManager.currentLiveSegmentServerLatency$}).pipe(Ba(({isLive:h})=>h),Na(h=>E({},h)),Pn((h,m)=>m.bufferLength<h.bufferLength),Na(({rtt:h,bufferLength:m,segmentServerLatency:b})=>{let g=Ys(this.manifestUrlString,2);return(h/2+m+b+g)/1e3})).subscribe(this.liveLatency$)),this.representationSubscription.add(ci({liveBuffer:this.liveBuffer.smoothed$,isActiveLowLatency:this.isActiveLowLatency$}).subscribe(({liveBuffer:h,isActiveLowLatency:m})=>{if(!m)return;let b=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,g=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,v=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,S=h-b,y=1;Math.abs(S)>g&&(y=1+Math.sign(S)*v),zl(this.element,y)})),this.representationSubscription.add(this.bufferLength$.subscribe(h=>{var b,g;let m=0;if(h){let v=((g=(b=this.element)==null?void 0:b.currentTime)!=null?g:0)*1e3;m=Math.min(...this.bufferManagers.map(y=>{var I,w;return(w=(I=y.getLiveSegmentsToLoadState(this.manifest))==null?void 0:I.to)!=null?w:v}))-v}this.liveLoadBufferLength$.getValue()!==m&&this.liveLoadBufferLength$.next(m)}));let p=0;this.representationSubscription.add(ci({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).pipe(RD(1e3)).subscribe(b=>A(this,[b],function*({liveLoadBufferLength:h,bufferLength:m}){if(!this.element||this.isUpdatingLive)return;let g=this.element.playbackRate,v=Ys(this.manifestUrlString,2),S=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,y=Math.min(S,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*g),I=this.tuning.dashCmafLive.normalizedActualBufferOffset*g,w=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*g,L=isFinite(h)?h:m,B=this.isActiveLowLatency$.getValue(),X=S<=this.tuning.live.activeLiveDelay&&v===0;this.isActiveLowLatency$.next(B&&X);let M="none";if(B?M="active_low_latency":this.isLowLatency$.getValue()&&X?(this.isActiveLowLatency$.next(!0),this.bufferManagers.forEach(F=>F.proceedLowLatencyLive()),M="active_low_latency"):v!==0&&L<y?M="live_forward_buffering":L<y+w&&(M="live_with_target_offset"),isFinite(h)&&(p=h>p?h:p),M==="live_forward_buffering"||M==="live_with_target_offset"){let F=p-(y+I),q=this.normolizeLiveOffset(Math.trunc(v+F/g)),R=Math.abs(q-v),H=0;!h||R<=this.tuning.dashCmafLive.offsetCalculationError?H=v:q>0&&R>this.tuning.dashCmafLive.offsetCalculationError&&(H=q),this.manifestUrlString=me(this.manifestUrlString,H,2)}M!=="none"&&M!=="active_low_latency"&&(p=0,this.updateLive())})))}let l=Tr(...this.bufferManagers.map(p=>p.fullyBuffered$)).pipe(Na(()=>this.bufferManagers.every(p=>p.fullyBuffered$.getValue()))),c=Tr(...this.bufferManagers.map(p=>p.onLastSegment$)).pipe(Na(()=>this.bufferManagers.some(p=>p.onLastSegment$.getValue())));if(this.representationSubscription.add(Tr(this.forceEnded$,ci({allBuffersFull:l,someBufferEnded:c}).pipe(Ba(({allBuffersFull:p,someBufferEnded:h})=>p&&h))).subscribe(()=>{var p;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(h=>!h.updating))try{(p=this.source)==null||p.endOfStream(),this.bufferManagers.forEach(h=>h.warmUpMediaSource())}catch(h){this.error$.next({id:"EndOfStream",category:Gt.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:h})}})),this.representationSubscription.add(Tr(...this.bufferManagers.map(p=>p.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.representationSubscription.add(this.videoBufferManager.currentSegmentLength$.subscribe(this.currentVideoSegmentLength$)),this.audioBufferManager&&(this.representationSubscription.add(this.audioBufferManager.playingRepresentation$.subscribe(this.currentAudioRepresentation$)),this.representationSubscription.add(this.audioBufferManager.currentSegmentLength$.subscribe(this.currentAudioSegmentLength$))),this.liveTextManager&&this.representationSubscription.add(this.liveTextManager.currentRepresentation$.subscribe(this.currentLiveTextRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(p=>{var h;return(h=this.source)==null?void 0:h.addEventListener("sourceopen",p)})),!this.isLive$.getValue()){let p=[(d=this.manifest.duration)!=null?d:0,...(0,Zl.default)((0,Zl.default)([...this.manifest.streams.audio,...this.manifest.streams.video],h=>h.representations),h=>{let m=[];return h.duration&&m.push(h.duration),ve(h.segmentReference)&&h.segmentReference.totalSegmentsDurationMs&&m.push(h.segmentReference.totalSegmentsDurationMs),m})];this.source.duration=Math.max(...p)/1e3}this.audioBufferManager&&Dy(t)?yield Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(t)]):yield this.videoBufferManager.startWith(e),this.state$.setState("representations_ready"),this.tracer.log("initRepresentationsEnd")})}.bind(this));this.tick=()=>{var t,r,i;if(!this.element||!this.videoBufferManager)return;let e=this.element.currentTime*1e3;this.videoBufferManager.maintain(e),(t=this.audioBufferManager)==null||t.maintain(e),(r=this.liveTextManager)==null||r.maintain(e),(this.videoBufferManager.gaps.length||(i=this.audioBufferManager)!=null&&i.gaps.length)&&!this.gapWatchdogActive&&(this.gapWatchdogActive=!0,this.gapWatchdogSubscription=Jl(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),s=>{this.error$.next({id:"GapWatchdog",category:Gt.WTF,message:"Error handling gaps",thrown:s})}),this.subscription.add(this.gapWatchdogSubscription))};this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.tracer=e.tracer.createComponentTracer(this.constructor.name),this.fetcher=new Tn({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode,tracer:this.tracer,useEnableSubtitlesParam:e.tuning.useEnableSubtitlesParam}),this.liveBuffer=Sr.getLiveBufferSmoothedValue(this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E({},e.tuning.dashCmafLive.lowLatency.bufferEstimator)),this.initTracerSubscription()}seekLive(e){return A(this,null,function*(){var r,i,s;li(this.element);let t=this.normolizeLiveOffset(e);this.isActiveLowLatency$.next(this.isLowLatency$.getValue()&&t===0),this.liveLastSeekOffset=t,this.manifestUrlString=me(this.manifestUrlString,t,2),this.manifest=yield this.updateManifest(),this.manifest&&(this.isJumpGapAfterSeekLive=!0,yield(r=this.videoBufferManager)==null?void 0:r.seekLive(this.manifest.streams.video),yield(i=this.audioBufferManager)==null?void 0:i.seekLive(this.manifest.streams.audio),(s=this.liveTextManager)==null||s.seekLive(this.manifest.streams.text))})}initBuffer(){li(this.element),this.state$.setState("running"),this.subscription.add(Tr(...$D.map(e=>yr(this.element,e)),yr(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:Gt.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(yr(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(yr(this.element,"waiting").subscribe(()=>{var t;this.element&&this.element.readyState===2&&!this.element.seeking&&qt(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime);let e=()=>{var h,m,b,g,v,S,y,I,w,L;if(!this.element)return;let r=this.currentStallDuration$.getValue();r+=50,this.currentStallDuration$.next(r);let i={timeInWaiting:r},s=AD(),n=100,o=(m=(h=this.videoBufferManager)==null?void 0:h.lastDataObtainedTimestamp)!=null?m:0;this.videoLastDataObtainedTimestamp$.next(o);let u=(g=(b=this.audioBufferManager)==null?void 0:b.lastDataObtainedTimestamp)!=null?g:0,l=(S=(v=this.videoBufferManager)==null?void 0:v.getForwardBufferDuration())!=null?S:0,c=(I=(y=this.audioBufferManager)==null?void 0:y.getForwardBufferDuration())!=null?I:0,d=l<n&&s-o>this.tuning.dash.crashOnStallTWithoutDataTimeout,p=this.audioBufferManager&&c<n&&s-u>this.tuning.dash.crashOnStallTWithoutDataTimeout;if((d||p)&&r>this.tuning.dash.crashOnStallTWithoutDataTimeout||r>=this.tuning.dash.crashOnStallTimeout)throw new Error(`Stall timeout exceeded: ${r} ms`);if(this.isLive$.getValue()&&r%5e3===0)this.seekLive(this.liveLastSeekOffset),i.liveLastSeekOffset=this.liveLastSeekOffset;else{let B=this.element.currentTime*1e3;(w=this.videoBufferManager)==null||w.maintain(B),(L=this.audioBufferManager)==null||L.maintain(B),i.position=B}this.tracer.log("stallIntervalCallback",_a(i))};(t=this.stallWatchdogSubscription)==null||t.unsubscribe(),this.stallWatchdogSubscription=Jl(50).subscribe(e,r=>{this.error$.next({id:"StallWatchdogCallback",category:Gt.NETWORK,message:"Can't restore DASH after stall.",thrown:r})}),this.subscription.add(this.stallWatchdogSubscription)})),this.tick()}switchRepresentation(e,t,r=!1){return A(this,null,function*(){let i={video:this.videoBufferManager,audio:this.audioBufferManager,text:null}[e];return i==null?void 0:i.switchTo(t,r)})}seek(e,t){return A(this,null,function*(){var i,s,n,o,u;li(this.element),li(this.videoBufferManager);let r;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?r=e:r=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!=null?i:e,(n=(s=this.audioBufferManager)==null?void 0:s.findSegmentStartTime(e))!=null?n:e),qt(this.element.buffered,r)||(yield Promise.all([this.videoBufferManager.abort(),(o=this.audioBufferManager)==null?void 0:o.abort()])),this.videoBufferManager.maintain(r),(u=this.audioBufferManager)==null||u.maintain(r),this.element.currentTime=r/1e3,this.tracer.log("seek",_a({requestedPosition:e,forcePrecise:t,position:r}))})}stop(){var e,t,r;this.tracer.log("stop"),(e=this.element)==null||e.querySelectorAll("source").forEach(i=>{URL.revokeObjectURL(i.src),i.remove()}),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)==null||t.destroy(),this.videoBufferManager=null,(r=this.audioBufferManager)==null||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState("none")}setBufferTarget(e){for(let t of this.bufferManagers)t.setTarget(e)}getStreams(){var e;return(e=this.manifest)==null?void 0:e.streams}setPreloadOnly(e){for(let t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)==null?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null,this.tracer.end()}initTracerSubscription(){let e=wD(this.tracer.error.bind(this.tracer));this.error$.subscribe(e("error"))}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){return A(this,null,function*(){var e,t;this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)==null||e.forEach(r=>r.updateLive(this.manifest)),(t=this.liveTextManager)==null||t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;let e=this.videoBufferManager.getDebugBufferState();if(!e)return;let t={isJumpGapAfterSeekLive:this.isJumpGapAfterSeekLive,isActiveLowLatency:this.isActiveLowLatency$.getValue(),initialCurrentTime:this.element.currentTime};this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency$.getValue()&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);let r=this.element.currentTime*1e3,i=[],s=this.element.readyState===1?this.tuning.endGapTolerance:0;for(let n of this.bufferManagers)for(let o of n.gaps)n.playingRepresentation$.getValue()===o.representation&&o.from-s<=r&&o.to+s>r&&(this.element.duration*1e3-o.to<this.tuning.endGapTolerance?i.push(1/0):i.push(o.to));if(i.length){let n=Math.max(...i)+10;this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogActive=!1,n===1/0?this.forceEnded$.next():(this.element.currentTime=n/1e3,t=$(E({},t),{gapEnds:i,jumpTo:n,resultCurrentTime:this.element.currentTime}),this.tracer.log("jumpGap",_a(t)))}}};var An=class{constructor(e,t){this.fov=e,this.orientation=t}};var kn=class{constructor(e,t){this.rotating=!1;this.fading=!1;this.lastTickTS=0;this.lastCameraTurnTS=0;this.fadeStartSpeed=null;this.fadeTime=0;this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/at(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);let i=e-this.camera.orientation.x,s=t-this.camera.orientation.y,n=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:i,y:s,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){let e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){let t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=E({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}let t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){let i=-this.fadeCorrection*at(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*i,this.fadeStartSpeed.y*i,this.fadeStartSpeed.z*i),i>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}};var Vy=`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 Ly=`#ifdef GL_ES
81
+ `;var By=`#ifdef GL_ES
82
82
  precision highp float;
83
83
  precision highp int;
84
84
  #else
@@ -121,5 +121,6 @@ void main(void) {
121
121
  // sample using new coordinates
122
122
  gl_FragColor = texture2D(u_texture, tc);
123
123
  }
124
- `;var $n=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new kn(this.params.fov,this.params.orientation),this.cameraRotationManager=new Rn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader($y,this.gl.VERTEX_SHADER),r=this.createShader(Ly,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as RC,now as My,Subscription as $C,filter as LC,combine as Cy,ValueSubject as Dy,isNonNullable as MC}from"@vkontakte/videoplayer-shared/es2015";var Jl=class{constructor(){this.isSeeked$=new Dy(!1);this.isBuffering$=new Dy(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new $C}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(Cy({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(LC(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Cy({currentStallDuration:this.currentStallDuration$,isSeeked:this.isSeeked$}).subscribe(({currentStallDuration:t,isSeeked:r})=>{if(RC(this.lastUniqueVideoTrackSelected))return;let{stallDurationBeforeQualityDecrease:i,stallDurationNoDataBeforeQualityDecrease:s,stallCountBeforeQualityDecrease:n,resetQualityRestrictionTimeout:o}=this.qualityLimitsOnStall,u=this.rtt$.getValue(),l=this.throughput$.getValue(),c=this.videoLastDataObtainedTimestamp$.getValue(),d=My(),p=n&&this.currentStallsCount>=n,h=i&&!r&&d-this.lastUniqueVideoTrackSelectedTimestamp>=i+u&&t>=i,f=s&&d-this.lastUniqueVideoTrackSelectedTimestamp>=s+u&&d-c>=s+u&&t>=s;(p||h||f)&&(window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,MC(this.lastUniqueVideoTrackSelected.bitrate)&&l>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},o))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=My(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Oy=Jl;import{combine as CC,map as DC,observeElementSize as OC,Subscription as BC,ValueSubject as Xl,noop as VC}from"@vkontakte/videoplayer-shared/es2015";var Ln=class{constructor(){this.subscription=new BC;this.pipSize$=new Xl(void 0);this.videoSize$=new Xl(void 0);this.elementSize$=new Xl(void 0);this.pictureInPictureWindowRemoveEventListener=VC}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(OC(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(CC({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(DC(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Er=class{constructor(e){this.subscription=new jC;this.videoState=new O("stopped");this.textTracksManager=new Fe;this.droppedFramesManager=new an;this.stallsManager=new Oy;this.elementSizeManager=new Ln;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Wi;this.audioTrackSwitchHistory=new Wi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&P(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return FC(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new $n(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.params=e,this.video=ye(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new An({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=Ee(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:Zl.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(By(c=>!!c.length),_y()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(ec(c=>c.to.state!=="none"),qa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(qa()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(By(Vy),_y()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(ec(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(Ie(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ne(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ue(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(qC(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let f of d.audio){h.push(Vl(f));let b=[];for(let g of f.representations){let S=uy(g);b.push(S),this.audioTracksMap.set(S,{stream:f,representation:g})}this.audioStreamsMap.set(f,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(_l(h));let f=[];for(let b of h.representations){let g=oy(C(x({},b),{streamId:h.id}));g&&(f.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,f)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let f of h.representations){let b=ly(h,f);this.textTracksMap.set(b,{stream:h,representation:f})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:Zl.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Mn(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$,HC(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,Ny.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,f]=p,b=[...this.videoTracksMap.keys()].find(S=>{var v;return((v=this.videoTracksMap.get(S))==null?void 0:v.representation.id)===h.id});Vy(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,f==null?void 0:f.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),f){let S=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",f.id,S).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(qa()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.videoStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.videoStream.setState(f.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(_l(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(qa()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,f=this.params.desiredState.audioStream.getTransition();f&&f.to&&f.to.id===h.id&&this.params.desiredState.audioStream.setState(f.to),e.currentAudioStream$.next(Vl(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(ec(({to:c})=>c==="ready"),qa());this.subscription.add(Mn(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,tc(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Mn(u,this.player.state$.stateChangeEnded$,tc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Mn(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,tc(["init"])).pipe(UC(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var $,B,J,L,F,q,R,U,N,W,A,T,D;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=($=e.videoTrack.getState())==null?void 0:$.id,n=[...this.videoTracksMap.keys()].find(({id:M})=>M===i),o=t.currentVideoTrack$.getValue(),u=((L=(J=e.videoStream.getState())!=null?J:n&&((B=this.videoTracksMap.get(n))==null?void 0:B.stream))!=null?L:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:M})=>M===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=ut(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),f=(F=e.audioStream.getState())!=null?F:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(q=[...this.audioStreamsMap.keys()].find(({id:M})=>M===(f==null?void 0:f.id)))!=null?q:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let M=Zs(n,c,(R=this.audioStreamsMap.get(b))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(U=M==null?void 0:M.bitrate)!=null?U:-1/0)}if(o){let M=Zs(o,c,(N=this.audioStreamsMap.get(b))!=null?N:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(W=M==null?void 0:M.bitrate)!=null?W:-1/0)}}let S=Ft(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),v=r?S!=null?S:n:n!=null?n:S,y=b&&Fg(v,c,(A=this.audioStreamsMap.get(b))!=null?A:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=(T=this.videoTracksMap.get(v))==null?void 0:T.representation,E=y&&((D=this.audioTracksMap.get(y))==null?void 0:D.representation);if(I&&E)return[I,E];if(I&&!E&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Zl.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.stallsManager.destroy(),this.elementSizeManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Te(this.video),this.tracer.end()}};var Ua=class extends Er{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Fy,interval as GC,map as qy}from"@vkontakte/videoplayer-shared/es2015";var Ha=class extends Er{constructor(e){super(e),this.liveOffset=new ft,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(qy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Fy({interval:GC(1e3),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(Fy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(qy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=cy(s);this.params.output.availableTextTracks$.next([n])}}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Hy=_(Ys(),1);import{assertNever as ja,assertNonNullable as Uy,debounce as QC,ErrorCategory as Cn,filter as WC,isNonNullable as YC,isNullable as zC,map as Dn,merge as KC,Observable as JC,observableFrom as XC,Subscription as ZC,videoSizeToQuality as e0}from"@vkontakte/videoplayer-shared/es2015";var et={};var di=(a,e)=>new JC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),Ga=class{constructor(e){this.subscription=new ZC;this.videoState=new O("initializing");this.textTracksManager=new Fe;this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:ja(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:ja(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:ja(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:ja(e)}break;default:ja(t)}};this.video=ye(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Te(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Cn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Hy.default)(import("hls.js").then(i=>{e||(et.Hls=i.default,et.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Uy(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(){Uy(et.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Cn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=Ee(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(nt(this.video,e.isLooped,r)),this.subscription.add(Ie(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ne(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ue(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Dn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(di(this.hls,et.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Cn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(di(this.hls,et.Events.MANIFEST_PARSED).pipe(Dn(({levels:l})=>l.reduce((c,d)=>{var v,y;let p=d.name||d.height.toString(10),{width:h,height:f}=d,b=(y=_t((v=d.attrs.QUALITY)!=null?v:""))!=null?y:e0({width:h,height:f});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,S={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:f},fps:g};return this.trackLevels.set(p,{track:S,level:d}),c.push(S),c},[]))),t.availableVideoTracks$),s(di(this.hls,et.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",f=d.lang;c.push({id:p,url:h,language:f,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(di(this.hls,et.Events.LEVEL_LOADING).pipe(Dn(({url:l})=>ue(l))),t.hostname$),s(di(this.hls,et.Events.FRAG_CHANGED),l=>{var p,h,f,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((f=d==null?void 0:d.endPTS)!=null?f:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Ot(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=di(this.hls,et.Events.LEVEL_SWITCHED).pipe(Dn(({level:l})=>n(this.hls.levels[l])));o.pipe(WC(YC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ot(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var f;if(zC(l))return;let c=(f=this.trackLevels.get(l.id))==null?void 0:f.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=KC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,XC(["init"])).pipe(QC(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return k(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Cn.DOM,thrown:t})))||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0)}};var jy="X-Playback-Duration",rc=a=>k(void 0,null,function*(){var i;let e=yield bt(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(jy)?parseInt(e.headers.get(jy),10):void 0});import{assertNever as n0,combine as o0,debounce as u0,ErrorCategory as Bn,filter as l0,filterChanged as c0,isNonNullable as Qy,isNullable as Vn,map as Wy,merge as d0,observableFrom as p0,Subscription as h0,ValueSubject as sc,VideoQuality as f0}from"@vkontakte/videoplayer-shared/es2015";var ac=_(uu(),1);import{videoSizeToQuality as t0,getExponentialDelay as r0}from"@vkontakte/videoplayer-shared/es2015";var i0=a=>{let e=null;if(a.QUALITY&&(e=_t(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=t0({width:t,height:r})}return e!=null?e:null},a0=(a,e)=>{var s,n;let t=a.split(`
125
- `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,ac.default)(l[1].split(",").map(v=>v.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=i0(d),f;d.BANDWIDTH&&(f=parseInt(d.BANDWIDTH,10)/1e3||void 0),!f&&d["AVERAGE-BANDWIDTH"]&&(f=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[v,y]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));v&&y&&(g={width:v,height:y})}let S=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:S,bandwidth:f,size:g,fps:b})}if(c){let d=(0,ac.default)(c[1].split(",").map(b=>b.split("=")).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,f=d.NAME;p&&h&&i.push({type:"internal",id:h,label:f,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},s0=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),ic=0,Gy=(r,...i)=>k(void 0,[r,...i],function*(a,e=a,t){let n=yield(yield bt(a)).text();ic+=1;try{let{qualityManifests:o,textTracks:u}=a0(n,e);return{qualityManifests:o,textTracks:u}}catch(o){if(ic<=t.manifestRetryMaxCount)return yield s0(r0(ic-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Gy(a,e,t)}return{qualityManifests:[],textTracks:[]}}),On=Gy;var Qa=class{constructor(e){this.subscription=new h0;this.videoState=new O("stopped");this.textTracksManager=new Fe;this.manifests$=new sc([]);this.liveOffset=new ft;this.manifestStartTime$=new sc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(P(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return n0(t)}};var t;this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:f0.INVARIANT,url:this.params.source.url},On(fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Bn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:Bn.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(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new sc((t=e.source.maxSeekBackTime)!=null?t:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Bn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ne(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ue(this.video),e.elementVisible$),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(c0(),Wy(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Qy(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ue(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(o0({startTime:this.manifestStartTime$.pipe(l0(Qy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Wy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=d0(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,p0(["init"])).pipe(u0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){var o,u;let e=this.selectManifest();if(Vn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:l,min:c}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[d,p]of[[l,"mq"],[c,"lq"]]){let h=String(parseFloat(d||""));p&&d&&i.searchParams.set(p,h)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=fe(i.toString(),this.liveOffset.getTotalOffset(),s);this.video.setAttribute("src",n),this.video.load(),rc(n).then(l=>{var c;if(!Vn(l))this.maxSeekBackTime$.next(l);else{let d=(c=this.params.source.maxSeekBackTime)!=null?c:this.maxSeekBackTime$.getValue();if(Vn(d)||!isFinite(d))try{bt(n).then(p=>p.text()).then(p=>{var f;let h=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(p))==null?void 0:f[1];if(h){let b=new URL(h,n).toString();rc(b).then(g=>{Vn(g)||this.maxSeekBackTime$.next(g)})}})}catch(p){}}})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Bn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}};import{assertNever as m0,debounce as b0,ErrorCategory as nc,fromEvent as oc,isNonNullable as g0,isNullable as v0,map as Yy,merge as zy,observableFrom as Ky,Subscription as S0,ValueSubject as y0,VideoQuality as T0,clientChecker as I0}from"@vkontakte/videoplayer-shared/es2015";var Wa=class{constructor(e){this.subscription=new S0;this.videoState=new O("stopped");this.textTracksManager=new Fe;this.manifests$=new y0([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?P(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return m0(t)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:T0.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),On(fe(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:nc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:nc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(Yy(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ne(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&g0(l.to)){let f=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===f);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(ue(b.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(Yy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!I0.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(zy(oc(o,"addtrack"),oc(o,"removetrack"),oc(o,"change"),Ky(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=zy(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ky(["init"])).pipe(b0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Te(this.video)}prepare(){var s,n;let e=this.selectManifest();if(v0(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:nc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var eT=_(Ur(),1),Ya=_(Zr(),1);import{assertNever as E0,assertNonNullable as Jy,debounce as x0,ErrorCategory as Xy,isHigher as P0,isHigherOrEqual as w0,isInvariantQuality as Zy,isLowerOrEqual as A0,isNonNullable as k0,merge as R0,observableFrom as $0,Subscription as L0,map as M0}from"@vkontakte/videoplayer-shared/es2015";var za=class{constructor(e){this.subscription=new L0;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new Fe;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?P(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return E0(e)}};this.params=e,this.video=ye(e.container,e.tuning),this.params.output.element$.next(this.video),(0,eT.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Ya.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:Xy.WTF,message:"MpegProvider internal logic error",thrown:o})},i=Ee(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(M0(o=>o.to)),this.params.output.playbackState$),this.subscription.add(nt(this.video,t.isLooped,r)),this.subscription.add(Ie(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ne(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ue(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),P(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),P(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&k0(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=R0(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,$0(["init"])).pipe(x0(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Te(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;Jy(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];Jy(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ma(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Xy.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Ya.default)(this.trackUrls).find(d=>!Zy(d.track.quality)&&A0(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&w0(c.quality,u.quality)&&(t=u),!t){let d=(0,Ya.default)(this.trackUrls).filter(h=>!Zy(h.track.quality)&&P0(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Ya.default)(this.trackUrls).map(l=>l.track);t=Ft(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as rT,debounce as B0,merge as iT,observableFrom as V0,Subscription as _0,map as aT,ValueSubject as N0,ErrorCategory as lc,VideoQuality as F0}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as C0}from"@vkontakte/videoplayer-shared/es2015";var tT=["stun:videostun.mycdn.me:80"],D0=1e3,O0=3,uc=()=>null,_n=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=uc;this.externalStopCallback=uc;this.externalErrorCallback=uc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return k(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return k(this,null,function*(){try{let e={iceServers:[{urls:tT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return k(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return k(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:C0.WTF,message:e.message})}onPeerConnectionStream(e){return k(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return k(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),D0)}normalizeOptions(e={}){let t={stunServerList:tT,maxRetryNumber:O0,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}};var Ka=class{constructor(e){this.videoState=new O("stopped");this.maxSeekBackTime$=new N0(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),P(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&P(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&P(this.params.desiredState.playbackState,"paused");return;default:return rT(e)}};this.subscription=new _0,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ye(e.container,e.tuning),this.liveStreamClient=new _n(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Te(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:lc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};iT(this.videoState.stateChangeStarted$.pipe(aT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(aT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=Ee(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Ue(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ie(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return rT(n.to)}},r)).add(iT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,V0(["init"])).pipe(B0(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:F0.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:lc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){xe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),P(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:lc.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}};var Ja=class{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}};import{assertNever as Za,assertNonNullable as Qt,ErrorCategory as Nn,filter as cT,isNonNullable as dT,isNullable as Y0,map as z0,merge as K0,once as J0,Subject as Re,Subscription as pT,ValueSubject as V,flattenObject as hT}from"@vkontakte/videoplayer-shared/es2015";import{Observable as q0,map as sT,Subscription as U0,Subject as H0}from"@vkontakte/videoplayer-shared/es2015";var nT=a=>new q0(e=>{let t=new U0,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(sT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(sT(({type:l})=>l!==void 0)),n=new H0,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as j0,Subscription as G0,combine as Q0,filter as uT,once as lT}from"@vkontakte/videoplayer-shared/es2015";function oT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as W0}from"@vkontakte/videoplayer-shared/es2015";var Xa=class Xa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new De;this.subscriptions=new G0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(uT(s=>!!s.type),lT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){W0.isSafari&&e!=="MPEG"||this.subscriptions.add(Q0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(uT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),lT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return k(this,null,function*(){let{volumeMultiplier:t}=this,r=oT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Xa.errorId,category:j0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Xa.errorId} exception`,thrown:e})}};Xa.errorId="VolumeMultiplierManager";var pi=Xa;var X0={chunkDuration:5e3,maxParallelRequests:5},es=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new Re;this.noAvailableProvidersError$=new Re;this.volumeMultiplierError$=new Re;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableVideoTracks$:new V([]),currentVideoTrack$:new V(void 0),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new Re,warning$:new Re,willSeekEvent$:new Re,soundProhibitedEvent$:new Re,seekedEvent$:new Re,loopedEvent$:new Re,endedEvent$:new Re,firstBytesEvent$:new Re,loadedMetadataEvent$:new Re,firstFrameEvent$:new Re,canplay$:new Re,isLive$:new V(void 0),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V("")};this.subscription=new pT;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=Vv([...Nv(this.params.tuning),..._v(this.params.tuning)],this.params.tuning).filter(l=>dT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,cc.default)(i,l)),...t.filter(l=>(0,cc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",hT(s)),this.screenFormatsIterator=new Ja(s);let n=[...vl(!0),...vl(!1)];this.chromecastFormatsIterator=new Ja(n.filter(l=>dT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&pi.isSupported()&&(this.volumeMultiplierManager=new pi(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(Y0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Nn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Za(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Qt(o),new Ua(C(x({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ha(C(x({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Qt(o),si||!this.params.tuning.useHlsJs?new Wa(C(x({},n),{source:o})):new Ga(C(x({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Qa(C(x({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Qt(o),new za(C(x({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new tv(C(x({},n),{source:o,config:C(x({},X0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ka({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Za(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Qt(o),new Hi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return Za(e)}}skipFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.next();case"CHROMECAST":return this.chromecastFormatsIterator.next();default:return Za(e)}}handleNoFormatsError(e){switch(e){case"SCREEN":this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case"CHROMECAST":this.params.dependencies.chromecastInitializer.disconnect();return;default:return Za(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;let t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;let r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return C(x({},e),{url:r(e.url)})}return(0,mT.default)((0,fT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new pT,t=!1,r=0;return e.add(K0(this.providerOutput.error$.pipe(cT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),nT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(z0(i=>({id:`ProviderHangup:${i}`,category:Nn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(cT(({to:s})=>s==="playing"),J0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Nn.NETWORK,u=i.category===Nn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=C(x({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",hT(n))})),e}};import{fromEvent as Fn,once as Z0,combine as eD,Subscription as bT,ValueSubject as dc,map as tD,filter as rD,isNonNullable as qn,now as Oe,safeStorage as pc}from"@vkontakte/videoplayer-shared/es2015";var iD=5e3,gT="one_video_throughput",vT="one_video_rtt",yt=window.navigator.connection,ST=()=>{let a=yt==null?void 0:yt.downlink;if(qn(a)&&a!==10)return a*1e3},yT=()=>{let a=yt==null?void 0:yt.rtt;if(qn(a)&&a!==3e3)return a},TT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},hc=class a{constructor(e){this.subscription=new bT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(gT)||(e.useBrowserEstimation?ST():void 0)||iD,r=(s=(i=a.load(vT))!=null?i:e.useBrowserEstimation?yT():void 0)!=null?s:0;if(this.throughput$=new dc(t),this.rtt$=new dc(r),this.rttAdjustedThroughput$=new dc(TT(t,r,e.rttPenaltyRequestSize)),this.throughput=Sr.getSmoothedValue(t,-1,e),this.rtt=Sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=ST();u&&this.throughput.next(u);let l=yT();qn(l)&&this.rtt.next(l)};yt&&"onchange"in yt&&this.subscription.add(Fn(yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{pc.set(gT,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{pc.set(vT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(eD({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(tD(({throughput:n,rtt:o})=>TT(n,o,e.rttPenaltyRequestSize)),rD(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Oe(),i=new bT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Fn(e,"progress").pipe(Z0()).subscribe(s=>{t=s.loaded,r=Oe()}));break;case 1:case 0:i.add(Fn(e,"loadstart").subscribe(()=>{t=0,r=Oe()}));break}i.add(Fn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Oe(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Oe(),n=0,o=Oe(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>k(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Oe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Oe();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Oe()}else n+=d.byteLength;o=Oe()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Oe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Oe()-o,this.concurrentDownloads.size),n=0,o=Oe());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=pc.get(e);if(qn(t))return(r=parseInt(t,10))!=null?r:void 0}},IT=hc;import{fillWithDefault as aD,VideoQuality as ET}from"@vkontakte/videoplayer-shared/es2015";var xT={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:ET.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:ET.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationBeforeQualityDecrease:0,stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,exposeInternalsToGlobal:!1},PT=a=>{var e;return C(x({},aD(a,xT)),{configName:[...(e=a.configName)!=null?e:[],...xT.configName]})};import{assertNonNullable as Un,combine as Tt,ErrorCategory as Hn,filter as ve,filterChanged as G,fromEvent as mc,isNonNullable as dD,isNullable as pD,Logger as hD,map as H,mapTo as RT,merge as Wt,now as jn,once as lt,Subject as z,Subscription as $T,tap as LT,ValueSubject as w,isHigher as fD,isInvariantQuality as MT,flattenObject as Yt,throttle as bc,getTraceSubscriptionMethod as CT,Tracer as mD,InternalsExposure as bD}from"@vkontakte/videoplayer-shared/es2015";import{merge as sD,map as nD,filter as wT,isNonNullable as oD}from"@vkontakte/videoplayer-shared/es2015";var fc=({seekState:a,position$:e})=>sD(a.stateChangeEnded$.pipe(nD(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),wT(oD)),e.pipe(wT(()=>a.getState().state==="none")));import{assertNonNullable as uD}from"@vkontakte/videoplayer-shared/es2015";var AT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return uD(e,`Wrong container or containerId {${a.container}}`),e};import{filter as lD,once as cD}from"@vkontakte/videoplayer-shared/es2015";var kT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(lD(i=>i.length>0),cD()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Gn=class{constructor(e={configName:[]},t=mD.createRootTracer(!1)){this.subscription=new $T;this.logger=new hD;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new w(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new w("stopped"),position$:new w(0),duration$:new w(1/0),muted$:new w(!1),volume$:new w(1),availableVideoStreams$:new w([]),currentVideoStream$:new w(void 0),availableQualities$:new w([]),availableQualitiesFps$:new w({}),currentQuality$:new w(void 0),isAutoQualityEnabled$:new w(!0),autoQualityLimitingAvailable$:new w(!1),autoQualityLimits$:new w({}),availableAudioStreams$:new w([]),currentAudioStream$:new w(void 0),availableAudioTracks$:new w([]),isAudioAvailable$:new w(!0),currentPlaybackRate$:new w(1),currentBuffer$:new w({start:0,end:0}),isBuffering$:new w(!0),isStalled$:new w(!1),isEnded$:new w(!1),isLooped$:new w(!1),isLive$:new w(void 0),canChangePlaybackSpeed$:new w(void 0),atLiveEdge$:new w(void 0),atLiveDurationEdge$:new w(void 0),liveTime$:new w(void 0),liveBufferTime$:new w(void 0),liveLatency$:new w(void 0),currentFormat$:new w(void 0),availableTextTracks$:new w([]),currentTextTrack$:new w(void 0),throughputEstimation$:new w(void 0),rttEstimation$:new w(void 0),videoBitrate$:new w(void 0),hostname$:new w(void 0),httpConnectionType$:new w(void 0),httpConnectionReused$:new w(void 0),surface$:new w("none"),chromecastState$:new w("NOT_AVAILABLE"),chromecastDeviceName$:new w(void 0),intrinsicVideoSize$:new w(void 0),availableSources$:new w(void 0),is3DVideo$:new w(!1),currentVideoSegmentLength$:new w(0),currentAudioSegmentLength$:new w(0)};this.events={inited$:new z,ready$:new z,started$:new z,playing$:new z,paused$:new z,stopped$:new z,willStart$:new z,willResume$:new z,willPause$:new z,willStop$:new z,willDestruct$:new z,watchCoverageRecord$:new z,watchCoverageLive$:new z,managedError$:new z,fatalError$:new z,ended$:new z,looped$:new z,seeked$:new z,willSeek$:new z,autoplaySoundProhibited$:new z,firstBytes$:new z,loadedMetadata$:new z,firstFrame$:new z,canplay$:new z,log$:new z};this.experimental={element$:new w(void 0),tuningConfigName$:new w([]),enableDebugTelemetry$:new w(!1),dumpTelemetry:$g};if(this.initLogs(),this.tuning=PT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new ys({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new IT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new bD("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,f)=>{let b=typeof f;return(0,DT.default)(["number","string","boolean"],b)?f:f===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Hn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=Xc(i,["container"]);return this.tracer.log("initVideo",Yt(r)),this.domContainer=AT(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new es({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(u=this.internalsExposure)==null||u.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Xi()?(this.tracer.log("request play from hidden tab"),mc(document,"visibilitychange").pipe(lt()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Un(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ve(r=>r.length>0),lt()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Yt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Un(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Yt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>x({type:"external"},t))),this}selectTextTrack(e){var t;return kT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",x({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(pD(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return dD(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(H(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(H(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ve(({from:e})=>e==="stopped"),lt()).subscribe(()=>{this.initedAt=jn(),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(x({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Hn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(lt()).subscribe(this.events.autoplaySoundProhibited$)).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(H(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(H(n=>n.destination),G()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Tt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(H(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>MT(u)?1:MT(l)?-1:fD(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(G()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(G()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(G()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(G()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(H(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(e.providerOutput.liveLatency$.subscribe(this.info.liveLatency$)).add(Tt({hasLiveOffsetByPaused:Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(H(n=>n.to),G(),H(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Tt({atLiveEdge:Tt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:fc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(H(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),G(),LT(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(H(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Tt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(H(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),G(),LT(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(H(n=>n.muted),G()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(H(n=>n.volume),G()).subscribe(this.info.volume$)).add(fc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Wt(e.providerOutput.endedEvent$.pipe(RT(!0)),e.providerOutput.seekedEvent$.pipe(RT(!1))).pipe(G()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(H(n=>({id:n?`No${n}`:"NoProviders",category:Hn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(lt(),H(n=>n!=null?n:jn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(lt(),H(()=>jn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(lt(),H(()=>jn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new w(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new w(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ve(({to:n})=>n==="playing"),lt()).subscribe(()=>r.next(!1)));let i=0,s=Wt(e.providerOutput.isBuffering$,t,r).pipe(H(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),G());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(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(H(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new $T;this.subscription.add(t),this.subscription.add(e.current$.pipe(G((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ve(r=>r.length>0),lt()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Wt(this.desiredState.videoTrack.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(H(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(H(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(H(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Un(this.providerContainer),Un(e),Rg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>kg(r)),this.providerContainer.current$.subscribe(({type:r})=>Qi("provider",r)),e.duration$.subscribe(r=>Qi("duration",r)),e.availableVideoTracks$.pipe(ve(r=>!!r.length),lt()).subscribe(r=>Qi("tracks",r)),this.events.fatalError$.subscribe(new be("fatalError")),this.events.managedError$.subscribe(new be("managedError")),e.position$.subscribe(new be("position")),e.currentVideoTrack$.pipe(H(r=>r==null?void 0:r.quality)).subscribe(new be("quality")),this.info.currentBuffer$.subscribe(new be("buffer")),e.isBuffering$.subscribe(new be("isBuffering"))].forEach(r=>this.subscription.add(r)),Qi("codecs",Bv())}initTracerSubscription(){let e=CT(this.tracer.log.bind(this.tracer)),t=CT(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(G()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Tt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(ve(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),G((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(ve(r=>r>0),G()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(ve(r=>r>0),G()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Tt({currentBuffer:this.info.currentBuffer$.pipe(ve(r=>r.end>0),G((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(G())}).pipe(bc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(G()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(G()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(G()).subscribe(e("canChangePlaybackSpeed"))).add(Tt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(ve(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),bc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(G(),ve(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(G(),ve(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(G()).subscribe(e("muted"))).add(this.info.volume$.pipe(G()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(G(),ve(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Tt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(ve(({throughputEstimation:r,rtt:i})=>!!r&&!!i),bc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(G(),ve(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>k(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Hn.DOM,message:String(i)})})});this.subscription.add(Wt(mc(document,"visibilitychange"),mc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Yt({quality:t,availableTracks:Yt(e),track:Yt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as c4,Observable as d4,Subject as p4,ValueSubject as h4,VideoQuality as f4}from"@vkontakte/videoplayer-shared/es2015";var m4=`@vkontakte/videoplayer-core@${Zc}`;export{fs as ChromecastState,eo as HttpConnectionType,d4 as Observable,Se as PlaybackState,Gn as Player,m4 as SDK_VERSION,p4 as Subject,c4 as Subscription,to as Surface,Zc as VERSION,h4 as ValueSubject,Lt as VideoFormat,f4 as VideoQuality};
124
+ `;var Rn=class{constructor(e,t,r){this.videoInitialized=!1;this.active=!1;this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();let i=this.canvas.getContext("webgl");if(!i)throw new Error("Could not initialize WebGL context");this.gl=i,this.container.appendChild(this.canvas),this.camera=new An(this.params.fov,this.params.orientation),this.cameraRotationManager=new kn(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();let t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),i=this.gl.getUniformLocation(this.program,"u_texture"),s=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(i,0),this.gl.uniform2f(s,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){let r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){let e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");let t=this.createShader(Vy,this.gl.VERTEX_SHADER),r=this.createShader(By,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){let e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1,i=this.frameHeight/(this.frameWidth/this.viewportWidth);return i>this.viewportHeight?t=this.viewportHeight/i:r=i/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){let e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){let e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,i=this.camera.fov.y/180/2,s=e-r,n=t-i,o=e+r,u=t-i,l=e+r,c=t+i,d=e-r,p=t+i;return[s,n,o,u,l,c,d,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){let e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}};import{isNullable as CD,now as _y,Subscription as OD,filter as VD,combine as Ny,ValueSubject as ec,isNonNullable as BD}from"@vkontakte/videoplayer-shared/es2015";var tc=class{constructor(){this.isSeeked$=new ec(!1);this.isBuffering$=new ec(!1);this.currentStallsCount=0;this.maxQualityLimit=void 0;this.lastUniqueVideoTrackSelectedTimestamp=0;this.predictedThroughputWithoutData=0;this.subscription=new OD;this.severeStallOccurred$=new ec(!1)}connect(e){this.currentStallDuration$=e.currentStallDuration$,this.videoLastDataObtainedTimestamp$=e.videoLastDataObtainedTimestamp$,this.throughput$=e.throughput$,this.rtt$=e.rtt$,this.qualityLimitsOnStall=e.qualityLimitsOnStall,this.subscription.add(e.isSeeked$.subscribe(this.isSeeked$)),this.subscription.add(e.isBuffering$.subscribe(this.isBuffering$)),this.subscription.add(Ny({isBuffering:this.isBuffering$,isSeeked:this.isSeeked$}).pipe(VD(({isBuffering:t,isSeeked:r})=>t&&!r)).subscribe(()=>{this.currentStallsCount++})),this.subscription.add(Ny({currentStallDuration:this.currentStallDuration$}).subscribe(({currentStallDuration:t})=>{if(CD(this.lastUniqueVideoTrackSelected))return;let{stallDurationNoDataBeforeQualityDecrease:r,stallCountBeforeQualityDecrease:i,resetQualityRestrictionTimeout:s}=this.qualityLimitsOnStall,n=this.rtt$.getValue(),o=this.throughput$.getValue(),u=this.videoLastDataObtainedTimestamp$.getValue(),l=_y(),c=i&&this.currentStallsCount>=i,d=r&&l-this.lastUniqueVideoTrackSelectedTimestamp>=r+n&&l-u>=r+n&&t>=r;(c||d)&&(this.severeStallOccurred$.next(!0),window.clearTimeout(this.qualityRestrictionTimer),this.maxQualityLimit=this.lastUniqueVideoTrackSelected.quality,BD(this.lastUniqueVideoTrackSelected.bitrate)&&o>this.lastUniqueVideoTrackSelected.bitrate&&(this.predictedThroughputWithoutData=this.lastUniqueVideoTrackSelected.bitrate)),t||(this.severeStallOccurred$.next(!1),window.clearTimeout(this.qualityRestrictionTimer),this.qualityRestrictionTimer=window.setTimeout(()=>{this.maxQualityLimit=void 0,this.predictedThroughputWithoutData=0},s))}))}get videoMaxQualityLimit(){return this.maxQualityLimit}get predictedThroughput(){return this.predictedThroughputWithoutData}set lastVideoTrackSelected(e){var t;((t=this.lastUniqueVideoTrackSelected)==null?void 0:t.id)!==e.id&&(this.lastUniqueVideoTrackSelected=e,this.lastUniqueVideoTrackSelectedTimestamp=_y(),this.currentStallsCount=0)}destroy(){window.clearTimeout(this.qualityRestrictionTimer),this.subscription.unsubscribe()}},Fy=tc;import{combine as _D,map as ND,observeElementSize as FD,Subscription as qD,ValueSubject as rc,noop as UD}from"@vkontakte/videoplayer-shared/es2015";var $n=class{constructor(){this.subscription=new qD;this.pipSize$=new rc(void 0);this.videoSize$=new rc(void 0);this.elementSize$=new rc(void 0);this.pictureInPictureWindowRemoveEventListener=UD}connect({observableVideo:e,video:t}){let r=i=>{let s=i.target;this.pipSize$.next({width:s.width,height:s.height})};this.subscription.add(FD(t).subscribe(this.videoSize$)).add(e.enterPip$.subscribe(({pictureInPictureWindow:i})=>{this.pipSize$.next({width:i.width,height:i.height}),i.addEventListener("resize",r),this.pictureInPictureWindowRemoveEventListener=()=>{i.removeEventListener("resize",r)}})).add(e.leavePip$.subscribe(()=>{this.pictureInPictureWindowRemoveEventListener()})).add(_D({videoSize:this.videoSize$,pipSize:this.pipSize$,inPip:e.inPiP$}).pipe(ND(({videoSize:i,inPip:s,pipSize:n})=>s?n:i)).subscribe(this.elementSize$))}getValue(){return this.elementSize$.getValue()}subscribe(e,t){return this.elementSize$.subscribe(e,t)}getObservable(){return this.elementSize$}destroy(){this.pictureInPictureWindowRemoveEventListener(),this.subscription.unsubscribe()}};var Ir=class{constructor(e){this.subscription=new zD;this.videoState=new O("stopped");this.droppedFramesManager=new rn;this.stallsManager=new Fy;this.elementSizeManager=new $n;this.videoTracksMap=new Map;this.audioTracksMap=new Map;this.textTracksMap=new Map;this.videoStreamsMap=new Map;this.audioStreamsMap=new Map;this.videoTrackSwitchHistory=new Wi;this.audioTrackSwitchHistory=new Wi;this.syncPlayback=()=>{var n,o,u;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(i.state==="requested"&&(r==null?void 0:r.to)!=="paused"&&e!=="stopped"&&t!=="stopped"){let l=(o=(n=this.liveOffset)==null?void 0:n.getTotalPausedTime())!=null?o:0;this.seek(i.position-l,i.forcePrecise)}if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.player.stop(),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}switch(e){case"stopped":this.videoState.startTransitionTo("ready"),this.prepare();return;case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="ready"&&x(this.params.desiredState.playbackState,"ready");return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),(u=this.liveOffset)==null||u.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return GD(e)}}};this.init3DScene=e=>{var r,i,s;if(this.scene3D)return;this.scene3D=new Rn(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=e.projectionData)==null?void 0:r.pose.yaw)||0,y:((i=e.projectionData)==null?void 0:i.pose.pitch)||0,z:((s=e.projectionData)==null?void 0:s.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});let t=this.elementSizeManager.getValue();t&&this.scene3D.setViewportSize(t.width,t.height)};this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)};this.textTracksManager=new Fe(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.player=new wn({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode,tracer:this.tracer}),this.subscribe()}getProviderSubscriptionInfo(){let{output:e,desiredState:t}=this.params,r=xe(this.video),i=this.constructor.name,s=o=>{e.error$.next({id:i,category:ic.WTF,message:`${i} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:(o,u)=>this.subscription.add(o.subscribe(u,s))}}subscribe(){let{output:e,desiredState:t,observableVideo:r,genericErrorListener:i,connect:s}=this.getProviderSubscriptionInfo();this.subscription.add(this.params.output.availableVideoTracks$.pipe(qy(c=>!!c.length),Hy()).subscribe(c=>{this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks:c})}));let n=this.params.desiredState.seekState.stateChangeEnded$.pipe(ac(c=>c.to.state!=="none"),Fa());this.stallsManager.connect({isSeeked$:n,currentStallDuration$:this.player.currentStallDuration$.pipe(Fa()),videoLastDataObtainedTimestamp$:this.player.videoLastDataObtainedTimestamp$,throughput$:this.params.dependencies.throughputEstimator.throughput$,rtt$:this.params.dependencies.throughputEstimator.rtt$,qualityLimitsOnStall:this.params.tuning.dash.qualityLimitsOnStall,isBuffering$:r.isBuffering$}),s(r.ended$,e.endedEvent$),s(r.looped$,e.loopedEvent$),s(r.error$,e.error$),s(r.isBuffering$,e.isBuffering$),s(r.currentBuffer$,e.currentBuffer$),s(r.playing$,e.firstFrameEvent$),s(r.canplay$,e.canplay$),s(r.inPiP$,e.inPiP$),s(r.inFullscreen$,e.inFullscreen$),s(r.loadedMetadata$,e.loadedMetadataEvent$),s(this.player.error$,e.error$),s(this.player.lastConnectionType$,e.httpConnectionType$),s(this.player.lastConnectionReused$,e.httpConnectionReused$),s(this.player.isLive$,e.isLive$),s(this.player.lastRequestFirstBytes$.pipe(qy(Uy),Hy()),e.firstBytesEvent$),s(this.videoState.stateChangeEnded$.pipe(ac(c=>c.to)),this.params.output.playbackState$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Ee(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ne(this.video,t.playbackRate,r.playbackRateState$,i)),this.elementSizeManager.connect({video:this.video,observableVideo:r}),s(Ue(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),e.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing"),this.scene3D&&this.scene3D.play()},i)).add(r.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},i)).add(r.canplay$.subscribe(()=>{this.videoState.getState()==="playing"&&this.playIfAllowed()},i)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:c})=>{if(c==="manifest_ready"){this.videoTracksMap=new Map,this.audioTracksMap=new Map,this.textTracksMap=new Map;let d=this.player.getStreams();if(QD(d,"Manifest not loaded or empty"),!this.params.tuning.isAudioDisabled){let h=[];for(let m of d.audio){h.push(Bl(m));let b=[];for(let g of m.representations){let v=by(g);b.push(v),this.audioTracksMap.set(v,{stream:m,representation:g})}this.audioStreamsMap.set(m,b)}this.params.output.availableAudioStreams$.next(h)}let p=[];for(let h of d.video){p.push(_l(h));let m=[];for(let b of h.representations){let g=fy($(E({},b),{streamId:h.id}));g&&(m.push(g),this.videoTracksMap.set(g,{stream:h,representation:b}))}this.videoStreamsMap.set(h,m)}this.params.output.availableVideoStreams$.next(p);for(let h of d.text)for(let m of h.representations){let b=gy(h,m);this.textTracksMap.set(b,{stream:h,representation:m})}this.params.output.availableVideoTracks$.next(Array.from(this.videoTracksMap.keys())),this.params.output.availableAudioTracks$.next(Array.from(this.audioTracksMap.keys())),this.params.output.isAudioAvailable$.next(!!this.audioTracksMap.size),this.audioTracksMap.size&&this.textTracksMap.size&&this.params.desiredState.internalTextTracks.startTransitionTo(Array.from(this.textTracksMap.keys()))}else c==="representations_ready"&&(this.videoState.setState("ready"),this.player.initBuffer())},i));let o=c=>e.error$.next({id:"RepresentationSwitch",category:ic.WTF,message:"Switching representations threw",thrown:c});this.subscription.add(Ln(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$,YD(this.video,"progress")).subscribe(()=>{let c=this.player.state$.getState(),d=this.player.state$.getTransition();if(!(0,jy.default)(["manifest_ready","running"],c)||d)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());let p=this.selectVideoAudioRepresentations();if(!p)return;let[h,m]=p,b=[...this.videoTracksMap.keys()].find(v=>{var S;return((S=this.videoTracksMap.get(v))==null?void 0:S.representation.id)===h.id});Uy(b)&&(this.stallsManager.lastVideoTrackSelected=b);let g=this.params.desiredState.autoVideoTrackLimits.getTransition();if(g&&this.params.output.autoVideoTrackLimits$.next(g.to),c==="manifest_ready")this.player.initRepresentations(h.id,m==null?void 0:m.id,this.params.sourceHls);else if(this.player.switchRepresentation("video",h.id).catch(o),m){let v=!!t.audioStream.getTransition();this.player.switchRepresentation("audio",m.id,v).catch(o)}},i)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:c})=>{this.scene3D&&c&&this.scene3D.pointCameraTo(c.x,c.y)})),this.subscription.add(this.elementSizeManager.subscribe(c=>{this.scene3D&&c&&this.scene3D.setViewportSize(c.width,c.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(Fa()).subscribe(c=>{let d=[...this.videoTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentVideoTrack$.next(void 0),e.currentVideoStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.videoStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.videoStream.setState(m.to),e.currentVideoTrack$.next(p),e.currentVideoStream$.next(_l(h))},i)),this.subscription.add(this.player.currentAudioRepresentation$.pipe(Fa()).subscribe(c=>{let d=[...this.audioTracksMap.entries()].find(([,{representation:b}])=>b.id===c);if(!d){e.currentAudioStream$.next(void 0);return}let[p,{stream:h}]=d,m=this.params.desiredState.audioStream.getTransition();m&&m.to&&m.to.id===h.id&&this.params.desiredState.audioStream.setState(m.to),e.currentAudioStream$.next(Bl(h))},i)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(c=>{var d,p;if(c!=null&&c.is3dVideo&&((d=this.params.tuning.spherical)!=null&&d.enabled))try{this.init3DScene(c),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),(p=this.params.tuning.spherical)!=null&&p.enabled&&e.is3DVideo$.next(!1)},i)),this.subscription.add(this.player.currentVideoSegmentLength$.subscribe(e.currentVideoSegmentLength$,i)),this.subscription.add(this.player.currentAudioSegmentLength$.subscribe(e.currentAudioSegmentLength$,i)),this.textTracksManager.connect(this.video,t,e);let u=t.playbackState.stateChangeStarted$.pipe(ac(({to:c})=>c==="ready"),Fa());this.subscription.add(Ln(u,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$,sc(["init"])).subscribe(()=>{let c=t.autoVideoTrackSwitching.getState(),p=t.playbackState.getState()==="ready"?this.params.tuning.dash.forwardBufferTargetPreload:c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(p)})),this.subscription.add(Ln(u,this.player.state$.stateChangeEnded$,sc(["init"])).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()==="ready")));let l=Ln(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,sc(["init"])).pipe(WD(0));this.subscription.add(l.subscribe(this.syncPlayback,i))}selectVideoAudioRepresentations(){var L,B,X,M,F,q,R,H,N,W,k,T,C;let{desiredState:e,output:t}=this.params,r=e.autoVideoTrackSwitching.getState(),i=(L=e.videoTrack.getState())==null?void 0:L.id,n=[...this.videoTracksMap.keys()].find(({id:D})=>D===i),o=t.currentVideoTrack$.getValue(),u=((M=(X=e.videoStream.getState())!=null?X:n&&((B=this.videoTracksMap.get(n))==null?void 0:B.stream))!=null?M:this.videoStreamsMap.size===1)?this.videoStreamsMap.keys().next().value:void 0;if(!u)return;let l=[...this.videoStreamsMap.keys()].find(({id:D})=>D===u.id),c=l&&this.videoStreamsMap.get(l);if(!c)return;let d=lt(this.video.buffered,this.video.currentTime*1e3),p=r?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,h=Math.min(d/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=(F=e.audioStream.getState())!=null?F:this.audioStreamsMap.size===1?this.audioStreamsMap.keys().next().value:void 0,b=(q=[...this.audioStreamsMap.keys()].find(({id:D})=>D===(m==null?void 0:m.id)))!=null?q:this.audioStreamsMap.keys().next().value,g=0;if(b){if(n&&!r){let D=Js(n,c,(R=this.audioStreamsMap.get(b))!=null?R:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(H=D==null?void 0:D.bitrate)!=null?H:-1/0)}if(o){let D=Js(o,c,(N=this.audioStreamsMap.get(b))!=null?N:[],this.params.tuning.autoTrackSelection.minVideoAudioRatio);g=Math.max(g,(W=D==null?void 0:D.bitrate)!=null?W:-1/0)}}let v=Ft(c,{container:this.elementSizeManager.getValue(),estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:g,forwardBufferHealth:h,current:o,visible:this.params.output.elementVisible$.getValue(),history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,stallsVideoMaxQualityLimit:this.stallsManager.videoMaxQualityLimit,stallsPredictedThroughput:this.stallsManager.predictedThroughput,abrLogger:this.params.dependencies.abrLogger}),S=r?v!=null?v:n:n!=null?n:v,y=b&&Yg(S,c,(k=this.audioStreamsMap.get(b))!=null?k:[],{estimatedThroughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),stallsPredictedThroughput:this.stallsManager.predictedThroughput,tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:h,history:this.audioTrackSwitchHistory,playbackRate:this.video.playbackRate,abrLogger:this.params.dependencies.abrLogger}),I=(T=this.videoTracksMap.get(S))==null?void 0:T.representation,w=y&&((C=this.audioTracksMap.get(y))==null?void 0:C.representation);if(I&&w)return[I,w];if(I&&!w&&this.audioTracksMap.size===0)return[I,void 0]}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Pe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{var t;e||((t=this.liveOffset)==null||t.pause(),this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:ic.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),Ie(this.video),this.tracer.end()}};var qa=class extends Ir{subscribe(){super.subscribe();let{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};import{combine as Gy,map as Qy,throttle as KD,filter as XD}from"@vkontakte/videoplayer-shared/es2015";var Ua=class extends Ir{constructor(e){super(e),this.liveOffset=new ft,this.textTracksManager.destroy()}subscribe(){super.subscribe();let{output:e,observableVideo:t,desiredState:r,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),this.params.output.isLive$.next(!0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),i(this.player.liveLatency$,e.liveLatency$),this.subscription.add(r.isLowLatency.stateChangeEnded$.pipe(Qy(s=>s.to)).subscribe(this.player.isLowLatency$)).add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(t.playbackRateState$.subscribe(s=>{var n;if(this.videoState.getState()==="playing"){let o=e.position$.getValue()+(s-1);o<=0&&e.position$.next(o),(n=this.liveOffset)==null||n.resetTo(-o*1e3)}})).add(Gy({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(Qy(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$)).add(this.player.currentLiveTextRepresentation$.subscribe(s=>{if(s){let n=vy(s);this.params.output.availableTextTracks$.next([n])}})).add(Gy({timeUpdate:t.timeUpdate$,liveLastPeriodDuration:this.player.liveLastPeriodDuration$,liveDuration:this.player.liveDuration$}).pipe(KD(1e3),XD(({liveLastPeriodDuration:s})=>!!s)).subscribe(({liveDuration:s,timeUpdate:n})=>{let o=Math.abs(s);n+1>=o&&e.isLiveEnded$.next(!0)}))}seek(e){this.params.output.willSeekEvent$.next();let t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),i=t==="paused"&&r==="paused",s=-e,n=Math.trunc(s/1e3<=Math.abs(this.params.output.duration$.getValue())?s:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)==null||o.resetTo(n,i)})}};var Yy=_(Ws(),1);import{assertNever as Ha,assertNonNullable as Wy,debounce as JD,ErrorCategory as Mn,filter as ZD,isNonNullable as eC,isNullable as tC,map as Dn,merge as rC,Observable as iC,observableFrom as aC,Subscription as sC,videoSizeToQuality as nC}from"@vkontakte/videoplayer-shared/es2015";var tt={};var di=(a,e)=>new iC(t=>{let r=(i,s)=>t.next(s);return a.on(e,r),()=>a.off(e,r)}),ja=class{constructor(e){this.subscription=new sC;this.videoState=new O("initializing");this.trackLevels=new Map;this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),i=this.params.desiredState.seekState.getState();if(e!=="initializing")switch((r==null?void 0:r.to)!=="paused"&&i.state==="requested"&&this.seek(i.position),t){case"stopped":switch(e){case"stopped":break;case"ready":case"playing":case"paused":this.stop();break;default:Ha(e)}break;case"ready":switch(e){case"stopped":this.prepare();break;case"ready":case"playing":case"paused":break;default:Ha(e)}break;case"playing":switch(e){case"playing":break;case"stopped":this.prepare();break;case"ready":case"paused":this.playIfAllowed();break;default:Ha(e)}break;case"paused":switch(e){case"paused":break;case"stopped":this.prepare();break;case"ready":this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused");break;case"playing":this.pause();break;default:Ha(e)}break;default:Ha(t)}};this.textTracksManager=new Fe(e.source.url),this.video=Te(e.container,e.tuning),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)==null||e.detachMedia(),(t=this.hls)==null||t.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}loadHlsJs(){let e=!1,t=i=>{e||this.params.output.error$.next({id:i==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:Mn.NETWORK,message:"Failed to load Hls.js",thrown:i}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);(0,Yy.default)(import("hls.js").then(i=>{e||(tt.Hls=i.default,tt.Events=i.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){Wy(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState("stopped")}subscribe(){Wy(tt.Events,"hls.js not loaded");let{desiredState:e,output:t}=this.params,r=l=>{t.error$.next({id:"HlsJsProvider",category:Mn.WTF,message:"HlsJsProvider internal logic error",thrown:l})},i=xe(this.video),s=(l,c)=>this.subscription.add(l.subscribe(c,r));s(i.timeUpdate$,t.position$),s(i.durationChange$,t.duration$),s(i.ended$,t.endedEvent$),s(i.looped$,t.loopedEvent$),s(i.error$,t.error$),s(i.isBuffering$,t.isBuffering$),s(i.currentBuffer$,t.currentBuffer$),s(i.loadStart$,t.firstBytesEvent$),s(i.loadedMetadata$,t.loadedMetadataEvent$),s(i.playing$,t.firstFrameEvent$),s(i.canplay$,t.canplay$),s(i.seeked$,t.seekedEvent$),s(i.inPiP$,t.inPiP$),s(i.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,r)),this.subscription.add(Ee(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ne(this.video,e.playbackRate,i.playbackRateState$,r)),s(Ue(this.video),t.elementVisible$),s(this.videoState.stateChangeEnded$.pipe(Dn(l=>l.to)),this.params.output.playbackState$),this.subscription.add(di(this.hls,tt.Events.ERROR).subscribe(l=>{var c;l.fatal&&t.error$.next({id:["HlsJsFatal",l.type,l.details].join("_"),category:Mn.WTF,message:`HlsJs fatal ${l.type} ${l.details}, ${(c=l.err)==null?void 0:c.message} ${l.reason}`,thrown:l.error})})),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(e.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(e.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())==null?void 0:l.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),s(di(this.hls,tt.Events.MANIFEST_PARSED).pipe(Dn(({levels:l})=>l.reduce((c,d)=>{var S,y;let p=d.name||d.height.toString(10),{width:h,height:m}=d,b=(y=_t((S=d.attrs.QUALITY)!=null?S:""))!=null?y:nC({width:h,height:m});if(!b)return c;let g=d.attrs["FRAME-RATE"]?parseFloat(d.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:b,bitrate:d.bitrate/1e3,size:{width:h,height:m},fps:g};return this.trackLevels.set(p,{track:v,level:d}),c.push(v),c},[]))),t.availableVideoTracks$),s(di(this.hls,tt.Events.MANIFEST_PARSED),l=>{if(l.subtitleTracks.length>0){let c=[];for(let d of l.subtitleTracks){let p=d.name,h=d.attrs.URI||"",m=d.lang;c.push({id:p,url:h,language:m,type:"internal"})}e.internalTextTracks.startTransitionTo(c)}}),s(di(this.hls,tt.Events.LEVEL_LOADING).pipe(Dn(({url:l})=>ue(l))),t.hostname$),s(di(this.hls,tt.Events.FRAG_CHANGED),l=>{var p,h,m,b;let{video:c,audio:d}=l.frag.elementaryStreams;t.currentVideoSegmentLength$.next((((p=c==null?void 0:c.endPTS)!=null?p:0)-((h=c==null?void 0:c.startPTS)!=null?h:0))*1e3),t.currentAudioSegmentLength$.next((((m=d==null?void 0:d.endPTS)!=null?m:0)-((b=d==null?void 0:d.startPTS)!=null?b:0))*1e3)}),this.subscription.add(Ot(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,l=>{this.hls.nextLevel=l?-1:this.hls.currentLevel,this.hls.loadLevel=l?-1:this.hls.loadLevel},{onError:r}));let n=l=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:d})=>d===l))==null?void 0:c.track},o=di(this.hls,tt.Events.LEVEL_SWITCHED).pipe(Dn(({level:l})=>n(this.hls.levels[l])));o.pipe(ZD(eC)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ot(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),l=>{var m;if(tC(l))return;let c=(m=this.trackLevels.get(l.id))==null?void 0:m.level;if(!c)return;let d=this.hls.levels.indexOf(c),p=this.hls.currentLevel,h=this.hls.levels[p];!h||c.bitrate>h.bitrate?this.hls.nextLevel=d:(this.hls.loadLevel=d,this.hls.loadLevel=d)},{changed$:o,onError:r})),s(i.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);let u=rC(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,aC(["init"])).pipe(JD(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo("ready"),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return A(this,null,function*(){this.videoState.startTransitionTo("playing"),(yield Pe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Mn.DOM,thrown:t})))||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))})}pause(){this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0)}};var zy="X-Playback-Duration",nc=a=>A(void 0,null,function*(){var i;let e=yield Ze(a),t=yield e.text(),r=(i=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(t))==null?void 0:i[1];return r?parseInt(r,10):e.headers.has(zy)?parseInt(e.headers.get(zy),10):void 0});import{assertNever as gC,combine as vC,debounce as SC,ErrorCategory as Vn,filter as yC,filterChanged as TC,isNonNullable as Jy,isNullable as Bn,map as Zy,merge as IC,observableFrom as EC,Subscription as xC,ValueSubject as lc,VideoQuality as PC}from"@vkontakte/videoplayer-shared/es2015";var uc=_(uu(),1);import{videoSizeToQuality as oC,getExponentialDelay as uC}from"@vkontakte/videoplayer-shared/es2015";var lC=a=>{let e=null;if(a.QUALITY&&(e=_t(a.QUALITY)),!e&&a.RESOLUTION){let[t,r]=a.RESOLUTION.split("x").map(i=>parseInt(i,10));e=oC({width:t,height:r})}return e!=null?e:null},cC=(a,e)=>{var s,n;let t=a.split(`
125
+ `),r=[],i=[];for(let o=0;o<t.length;o++){let u=t[o],l=u.match(/^#EXT-X-STREAM-INF:(.+)/),c=u.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!l&&!c)){if(l){let d=(0,uc.default)(l[1].split(",").map(S=>S.split("="))),p=(s=d.QUALITY)!=null?s:`stream-${d.BANDWIDTH}`,h=lC(d),m;d.BANDWIDTH&&(m=parseInt(d.BANDWIDTH,10)/1e3||void 0),!m&&d["AVERAGE-BANDWIDTH"]&&(m=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);let b=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0,g;if(d.RESOLUTION){let[S,y]=d.RESOLUTION.split("x").map(I=>parseInt(I,10));S&&y&&(g={width:S,height:y})}let v=new URL(t[++o],e).toString();h&&r.push({id:p,quality:h,url:v,bandwidth:m,size:g,fps:b})}if(c){let d=(0,uc.default)(c[1].split(",").map(b=>{let g=b.indexOf("=");return[b.substring(0,g),b.substring(g+1)]}).map(([b,g])=>[b,g.replace(/^"|"$/g,"")])),p=(n=d.URI)==null?void 0:n.replace(/playlist$/,"subtitles.vtt"),h=d.LANGUAGE,m=d.NAME;p&&h&&i.push({type:"internal",id:h,label:m,language:h,url:p,isAuto:!1})}}}if(!r.length)throw new Error("Empty manifest");return{qualityManifests:r,textTracks:i}},dC=a=>new Promise(e=>{setTimeout(()=>{e()},a)}),oc=0,Ky=(i,...s)=>A(void 0,[i,...s],function*(a,e=a,t,r){let o=yield(yield Ze(a,r)).text();oc+=1;try{let{qualityManifests:u,textTracks:l}=cC(o,e);return{qualityManifests:u,textTracks:l}}catch(u){if(oc<=t.manifestRetryMaxCount)return yield dC(uC(oc-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),Ky(a,e,t)}return{qualityManifests:[],textTracks:[]}}),Cn=Ky;import{isNonNullable as pC,Subscription as hC,throttle as mC,ValueSubject as Xy,Subject as fC,ErrorCategory as bC}from"@vkontakte/videoplayer-shared/es2015";var On=class{constructor(e,t,r,i,s){this.subscription=new hC;this.abortControllers={destroy:new fe,nextManifest:null};this.prepareUrl=void 0;this.currentTextTrackData=null;this.availableTextTracks$=new Xy(null);this.getCurrentTime$=new Xy(null);this.error$=new fC;this.params={fetchManifestData:r,sourceUrl:i,downloadThreshold:s},this.subscription.add(e.pipe(mC(1e3)).subscribe(n=>{this.processLiveTime(n)})),this.getCurrentTime$.next(()=>this.currentTextTrackData?this.currentTextTrackData.playlist.segmentStartTime/1e3+t.currentTime:0)}destroy(){this.subscription.unsubscribe(),this.abortControllers.destroy.abort()}prepare(e){return A(this,null,function*(){try{let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),this.prepareUrl=t.toString();let{textTracks:r}=yield this.fetchManifestData();yield this.processTextTracks(r,this.params.sourceUrl)}catch(t){this.error("prepare",t)}})}processTextTracks(e,t){return A(this,null,function*(){try{let r=yield this.parseTextTracks(e,t);r&&(this.currentTextTrackData=r)}catch(r){this.error("processTextTracks",r)}})}parseTextTracks(e,t){return A(this,null,function*(){for(let r of e){let i=new URL(r.url,t).toString(),n=yield(yield Ze(i,{signal:this.abortControllers.destroy.signal})).text(),o=this.parsePlaylist(n,i);return{textTrack:r,playlist:o}}})}parsePlaylist(e,t){let r={mediaSequence:0,programDateTime:"",segments:[],targetDuration:0,vkPlaybackDuration:0,segmentStartTime:0,vkStartTime:""},i=e.split(`
126
+ `),s=0;for(let n=0;n<i.length;++n){let o=i[n];switch(!0){case o.startsWith("#EXTINF:"):{let u=i[++n],l=new URL(u,t).toString(),c=Number(this.extractPlaylistRowValue("#EXTINF:",o))*1e3;if(r.segments.push({time:{from:s,to:s+c},url:l}),s=s+c,!r.segmentStartTime){let d=new Date(r.vkStartTime).valueOf(),p=new Date(r.programDateTime).valueOf();r.segmentStartTime=p-d}break}case o.startsWith("#EXT-X-TARGETDURATION:"):r.targetDuration=Number(this.extractPlaylistRowValue("#EXT-X-TARGETDURATION:",o));break;case o.startsWith("#EXT-X-MEDIA-SEQUENCE:"):r.mediaSequence=Number(this.extractPlaylistRowValue("#EXT-X-MEDIA-SEQUENCE:",o));break;case o.startsWith("#EXT-X-VK-PLAYBACK-DURATION:"):r.vkPlaybackDuration=Number(this.extractPlaylistRowValue("#EXT-X-VK-PLAYBACK-DURATION:",o));break;case o.startsWith("#EXT-X-PROGRAM-DATE-TIME:"):{let u=this.extractPlaylistRowValue("#EXT-X-PROGRAM-DATE-TIME:",o);r.programDateTime=u;let l=new Date(u);l.setMilliseconds(0),s=l.valueOf();break}case o.startsWith("#EXT-X-VK-START-TIME:"):r.vkStartTime=this.extractPlaylistRowValue("#EXT-X-VK-START-TIME:",o);break}}return r}extractPlaylistRowValue(e,t){switch(e){case"#EXTINF:":return t.substring(e.length,t.length-1);default:return t.substring(e.length)}}processLiveTime(e){if(pC(e)&&this.currentTextTrackData){let{segments:t}=this.currentTextTrackData.playlist,{from:r}=t[0].time,{to:i}=t[t.length-1].time;if(e<r||e>i)return;i-e<this.params.downloadThreshold&&this.fetchNextManifestData();for(let n of t)if(n.time.from<=e&&n.time.to>=e){this.availableTextTracks$.next([$(E({},this.currentTextTrackData.textTrack),{url:n.url,isAuto:!0})]);break}}}fetchNextManifestData(){return A(this,null,function*(){try{if(this.abortControllers.nextManifest)return;this.abortControllers.nextManifest=new fe;let{textTracks:e}=yield this.fetchManifestData(),t=yield this.parseTextTracks(e,this.params.sourceUrl);this.currentTextTrackData&&t&&(this.currentTextTrackData.playlist.segments=t.playlist.segments)}catch(e){this.error("fetchNextManifestData",e)}finally{this.abortControllers.nextManifest=null}})}fetchManifestData(){return A(this,null,function*(){var t;let e=(t=this.prepareUrl)!=null?t:this.params.sourceUrl;return yield this.params.fetchManifestData(e,{signal:this.abortControllers.destroy.signal})})}error(e,t){this.error$.next({id:"[LiveTextManager][HLS_LIVE_CMAF]",category:bC.WTF,thrown:t,message:e})}};var Ga=class{constructor(e){this.subscription=new xC;this.videoState=new O("stopped");this.textTracksManager=null;this.liveTextManager=null;this.manifests$=new lc([]);this.liveOffset=new ft;this.manifestStartTime$=new lc(void 0);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c),this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((i==null?void 0:i.to)!=="paused"&&l.state==="requested"){this.videoState.startTransitionTo("ready"),this.seek(l.position&&l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.liveOffset.pause(),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":if(r==="playing")if(this.videoState.startTransitionTo("playing"),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.prepare()}else(i==null?void 0:i.to)==="paused"&&(x(this.params.desiredState.playbackState,"paused"),this.liveOffset.pause());return;case"changing_manifest":break;default:return gC(t)}};var r;this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:PC.INVARIANT,url:this.params.source.url};let t=(i,s)=>Cn(i,this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},s);this.params.tuning.useHlsLiveNewTextManager?this.liveTextManager=new On(this.params.output.liveTime$,this.video,t,this.params.source.url,this.params.tuning.hlsLiveNewTextManagerDownloadThreshold):this.textTracksManager=new Fe(e.source.url),t(this.generateLiveUrl()).then(({qualityManifests:i,textTracks:s})=>{var n;i.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:Vn.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),(n=this.liveTextManager)==null||n.processTextTracks(s,this.params.source.url),this.manifests$.next([this.masterManifest,...i])}).catch(i=>{this.params.output.error$.next({id:"ExtractHlsQualities",category:Vn.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})}),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.availableTextTracks$.next([]),this.params.desiredState.internalTextTracks.setState([]),this.maxSeekBackTime$=new lc((r=e.source.maxSeekBackTime)!=null?r:1/0),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsLiveProvider",category:Vn.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},i=xe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.ended$,e.endedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ne(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ue(this.video),e.elementVisible$),this.liveTextManager?(s(this.liveTextManager.getCurrentTime$,this.params.output.getCurrentTime$),s(this.liveTextManager.error$,this.params.output.error$)):this.textTracksManager&&this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.liveTextManager&&this.subscription.add(this.liveTextManager.availableTextTracks$.subscribe(o=>{o&&this.params.output.availableTextTracks$.next(o)})),this.subscription.add(this.maxSeekBackTime$.pipe(TC(),Zy(o=>-o/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(i.loadedMetadata$.subscribe(()=>{let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&Jy(l.to)){let d=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let p=this.manifests$.getValue().find(h=>h.id===d);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(ue(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o&&o.state==="requested"&&this.seek(o.position)},r)),this.subscription.add(i.loadedData$.subscribe(()=>{var u,l,c;let o=(c=(l=(u=this.video)==null?void 0:u.getStartDate)==null?void 0:l.call(u))==null?void 0:c.getTime();this.manifestStartTime$.next(o||void 0)},r)),this.subscription.add(vC({startTime:this.manifestStartTime$.pipe(yC(Jy)),currentTime:i.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),r)),this.subscription.add(this.manifests$.pipe(Zy(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r));let n=IC(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,EC(["init"])).pipe(SC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){var e,t;this.subscription.unsubscribe(),(e=this.textTracksManager)==null||e.destroy(),(t=this.liveTextManager)==null||t.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){var o,u,l;let e=this.selectManifest();if(Bn(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:c,min:d}=(u=(o=t==null?void 0:t.to)!=null?o:r)!=null?u:{};for(let[p,h]of[[c,"mq"],[d,"lq"]]){let m=String(parseFloat(p||""));h&&p&&i.searchParams.set(h,m)}}let s=this.params.format==="HLS_LIVE_CMAF"?2:0,n=me(i.toString(),this.liveOffset.getTotalOffset(),s);(l=this.liveTextManager)==null||l.prepare(n),this.video.setAttribute("src",n),this.video.load(),nc(n).then(c=>{var d;if(!Bn(c))this.maxSeekBackTime$.next(c);else{let p=(d=this.params.source.maxSeekBackTime)!=null?d:this.maxSeekBackTime$.getValue();(Bn(p)||!isFinite(p))&&Ze(n).then(h=>h.text()).then(h=>{var b;let m=(b=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))==null?void 0:b[1];if(m){let g=new URL(m,n).toString();nc(g).then(v=>{Bn(v)||this.maxSeekBackTime$.next(v)})}}).catch(()=>{})}})}playIfAllowed(){Pe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),this.liveOffset.pause(),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:Vn.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();let t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}generateLiveUrl(){let e=me(this.params.source.url);if(this.params.tuning.useHlsLiveNewTextManager){let t=new URL(e);t.searchParams.set("enable-subtitles","yes"),e=t.toString()}return e}};import{assertNever as wC,debounce as AC,ErrorCategory as cc,fromEvent as dc,isNonNullable as kC,isNullable as RC,map as eT,merge as tT,observableFrom as rT,Subscription as $C,ValueSubject as LC,VideoQuality as MC,clientChecker as DC}from"@vkontakte/videoplayer-shared/es2015";var Qa=class{constructor(e){this.subscription=new $C;this.videoState=new O("stopped");this.manifests$=new LC([]);this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;let t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),n=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r==="stopped"){t!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let l=this.params.desiredState.seekState.getState();if(t==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s||n||o){let c=this.videoState.getState();this.videoState.setState("changing_manifest"),this.videoState.startTransitionTo(c);let{currentTime:d}=this.video;this.prepare(),o&&this.params.output.autoVideoTrackLimits$.next(o.to),l.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0});return}switch((i==null?void 0:i.to)!=="paused"&&l.state==="requested"&&this.seek(l.position),t){case"ready":r==="ready"?x(this.params.desiredState.playbackState,"ready"):r==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):r==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":r==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(i==null?void 0:i.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":r==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(i==null?void 0:i.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;case"changing_manifest":break;default:return wC(t)}};this.textTracksManager=new Fe(e.source.url),this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:MC.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Cn(me(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:cc.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var u,l,c,d;let{autoVideoTrackSwitching:e,videoTrack:t}=this.params.desiredState,r=e.getState(),i=t.getTransition(),s=(d=(c=(u=i==null?void 0:i.to)==null?void 0:u.id)!=null?c:(l=t.getState())==null?void 0:l.id)!=null?d:"master",n=this.manifests$.getValue();if(!n.length)return;let o=r?"master":s;return r&&!i&&t.startTransitionTo(this.masterManifest),n.find(p=>p.id===o)}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"HlsProvider",category:cc.WTF,message:"HlsProvider internal logic error",thrown:o})},i=xe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u));if(s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(eT(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ne(this.video,t.playbackRate,i.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())==null?void 0:o.to)==="ready"&&this.videoState.setState("ready"),this.videoState.getState()==="playing"&&this.playIfAllowed()},r).add(i.loadedMetadata$.subscribe(()=>{var h;let o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&kC(l.to)){let m=l.to.id;this.params.desiredState.videoTrack.setState(l.to);let b=this.manifests$.getValue().find(g=>g.id===m);b&&(this.params.output.currentVideoTrack$.next(b),this.params.output.hostname$.next(ue(b.url)))}let d=this.params.desiredState.playbackRate.getState(),p=(h=this.params.output.element$.getValue())==null?void 0:h.playbackRate;if(d!==p){let m=this.params.output.element$.getValue();m&&(this.params.desiredState.playbackRate.setState(d),m.playbackRate=d)}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),u&&u.from==="changing_manifest"&&this.videoState.setState(u.to),o.state==="requested"&&this.seek(o.position)},r))),this.subscription.add(this.manifests$.pipe(eT(o=>o.map(({id:u,quality:l,size:c,bandwidth:d,fps:p})=>({id:u,quality:l,size:c,fps:p,bitrate:d})))).subscribe(this.params.output.availableVideoTracks$,r)),!DC.isIOS||!this.params.tuning.useNativeHLSTextTracks){let{textTracks:o}=this.video;this.subscription.add(tT(dc(o,"addtrack"),dc(o,"removetrack"),dc(o,"change"),rT(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},r))}let n=tT(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,rT(["init"])).pipe(AC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ie(this.video)}prepare(){var s,n;let e=this.selectManifest();if(RC(e))return;let t=this.params.desiredState.autoVideoTrackLimits.getTransition(),r=this.params.desiredState.autoVideoTrackLimits.getState(),i=new URL(e.url);if((t||r)&&e.id===this.masterManifest.id){let{max:o,min:u}=(n=(s=t==null?void 0:t.to)!=null?s:r)!=null?n:{};for(let[l,c]of[[o,"mq"],[u,"lq"]]){let d=String(parseFloat(l||""));c&&l&&i.searchParams.set(c,d)}}this.video.setAttribute("src",i.toString()),this.video.load()}playIfAllowed(){Pe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:cc.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}};var nT=_(qr(),1),Wa=_(Jr(),1);import{assertNever as CC,assertNonNullable as iT,debounce as OC,ErrorCategory as aT,isHigher as VC,isHigherOrEqual as BC,isInvariantQuality as sT,isLowerOrEqual as _C,isNonNullable as NC,merge as FC,observableFrom as qC,Subscription as UC,map as HC}from"@vkontakte/videoplayer-shared/es2015";var Ya=class{constructor(e){this.subscription=new UC;this.videoState=new O("stopped");this.trackUrls={};this.textTracksManager=new Fe;this.syncPlayback=()=>{var u,l,c;let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(s&&e!=="ready"&&!n){this.handleQualityLimitTransition(s.to.max);return}if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(n){let{currentTime:d}=this.video;this.prepare(),o.state==="none"&&this.params.desiredState.seekState.setState({state:"requested",position:d*1e3,forcePrecise:!0}),n.to&&((u=this.params.desiredState.autoVideoTrackLimits.getState())==null?void 0:u.max)!==((c=(l=this.trackUrls[n.to.id])==null?void 0:l.track)==null?void 0:c.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((r==null?void 0:r.to)!=="paused"&&o.state==="requested"&&this.seek(o.position),e){case"ready":t==="ready"?x(this.params.desiredState.playbackState,"ready"):t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return CC(e)}};this.params=e,this.video=Te(e.container,e.tuning),this.params.output.element$.next(this.video),(0,nT.default)(this.params.source).reverse().forEach(([t,r],i)=>{let s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next((0,Wa.default)(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){let{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"MpegProvider",category:aT.WTF,message:"MpegProvider internal logic error",thrown:o})},i=xe(this.video),s=(o,u)=>this.subscription.add(o.subscribe(u,r));s(i.timeUpdate$,e.position$),s(i.durationChange$,e.duration$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(i.loadedMetadata$,e.firstBytesEvent$),s(i.loadedMetadata$,e.loadedMetadataEvent$),s(i.playing$,e.firstFrameEvent$),s(i.canplay$,e.canplay$),s(i.seeked$,e.seekedEvent$),s(i.inPiP$,e.inPiP$),s(i.inFullscreen$,e.inFullscreen$),s(this.videoState.stateChangeEnded$.pipe(HC(o=>o.to)),this.params.output.playbackState$),this.subscription.add(ot(this.video,t.isLooped,r)),this.subscription.add(Ee(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ne(this.video,t.playbackRate,i.playbackRateState$,r)),s(Ue(this.video),e.elementVisible$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState("playing"),x(t.playbackState,"playing")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused"),x(t.playbackState,"paused")},r)).add(i.canplay$.subscribe(()=>{var u,l;((u=this.videoState.getTransition())==null?void 0:u.to)==="ready"&&this.videoState.setState("ready");let o=this.params.desiredState.videoTrack.getTransition();if(o&&NC(o.to)){this.params.desiredState.videoTrack.setState(o.to),this.params.output.currentVideoTrack$.next(this.trackUrls[o.to.id].track);let c=this.params.desiredState.playbackRate.getState(),d=(l=this.params.output.element$.getValue())==null?void 0:l.playbackRate;if(c!==d){let p=this.params.output.element$.getValue();p&&(this.params.desiredState.playbackRate.setState(c),p.playbackRate=c)}}this.videoState.getState()==="playing"&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);let n=FC(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,qC(["init"])).pipe(OC(0));this.subscription.add(n.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ie(this.video)}prepare(){var r;let e=(r=this.params.desiredState.videoTrack.getState())==null?void 0:r.id;iT(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];iT(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Ma(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(ue(t))}playIfAllowed(){Pe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:aT.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var i,s,n,o;let t,r=e;if(e&&((i=this.params.output.currentVideoTrack$.getValue())==null?void 0:i.quality)!==e){let u=(s=(0,Wa.default)(this.trackUrls).find(d=>!sT(d.track.quality)&&_C(d.track.quality,e)))==null?void 0:s.track,l=(n=this.params.desiredState.videoTrack.getState())==null?void 0:n.id,c=(o=this.trackUrls[l!=null?l:"0"])==null?void 0:o.track;if(u&&c&&BC(c.quality,u.quality)&&(t=u),!t){let d=(0,Wa.default)(this.trackUrls).filter(h=>!sT(h.track.quality)&&VC(h.track.quality,e)),p=d.length;p&&(t=d[p-1].track)}t&&(r=t.quality)}else if(!e){let u=(0,Wa.default)(this.trackUrls).map(l=>l.track);t=Ft(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},estimatedThroughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}t&&(this.params.output.currentVideoTrack$.next(t),this.params.desiredState.videoTrack.startTransitionTo(t)),this.params.output.autoVideoTrackLimits$.next({max:r})}};import{assertNever as uT,debounce as WC,merge as lT,observableFrom as YC,Subscription as zC,map as cT,ValueSubject as KC,ErrorCategory as hc,VideoQuality as XC}from"@vkontakte/videoplayer-shared/es2015";import{ErrorCategory as jC}from"@vkontakte/videoplayer-shared/es2015";var oT=["stun:videostun.mycdn.me:80"],GC=1e3,QC=3,pc=()=>null,_n=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=pc;this.externalStopCallback=pc;this.externalErrorCallback=pc;this.options=this.normalizeOptions(t);let r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{let t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return A(this,null,function*(){try{let t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return A(this,null,function*(){try{let e={iceServers:[{urls:oT}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);let t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return A(this,null,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return A(this,null,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:jC.WTF,message:e.message})}onPeerConnectionStream(e){return A(this,null,function*(){let t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){let e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return A(this,null,function*(){let e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");let t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){let e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),GC)}normalizeOptions(e={}){let t={stunServerList:oT,maxRetryNumber:QC,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 O("stopped");this.maxSeekBackTime$=new KC(0);this.syncPlayback=()=>{let e=this.videoState.getState(),t=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(t==="stopped"){e!=="stopped"&&(this.videoState.startTransitionTo("stopped"),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState("stopped"),x(this.params.desiredState.playbackState,"stopped",!0));return}if(this.videoState.getTransition())return;let s=this.params.desiredState.videoTrack.getTransition();if(e==="stopped"){this.videoState.startTransitionTo("ready"),this.prepare();return}if(s){this.prepare();return}switch(e){case"ready":t==="paused"?(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused")):t==="playing"&&(this.videoState.startTransitionTo("playing"),this.playIfAllowed());return;case"playing":t==="paused"?(this.videoState.startTransitionTo("paused"),this.video.paused?this.videoState.setState("paused"):this.video.pause()):(r==null?void 0:r.to)==="playing"&&x(this.params.desiredState.playbackState,"playing");return;case"paused":t==="playing"?(this.videoState.startTransitionTo("playing"),this.playIfAllowed()):(r==null?void 0:r.to)==="paused"&&x(this.params.desiredState.playbackState,"paused");return;default:return uT(e)}};this.subscription=new zC,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Te(e.container,e.tuning),this.liveStreamClient=new _n(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),Ie(this.video)}subscribe(){let{output:e,desiredState:t}=this.params,r=n=>{e.error$.next({id:"WebRTCLiveProvider",category:hc.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};lT(this.videoState.stateChangeStarted$.pipe(cT(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(cT(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});let i=xe(this.video),s=(n,o)=>this.subscription.add(n.subscribe(o,r));s(i.timeUpdate$,e.liveTime$),s(i.ended$,e.endedEvent$),s(i.looped$,e.loopedEvent$),s(i.error$,e.error$),s(i.isBuffering$,e.isBuffering$),s(i.currentBuffer$,e.currentBuffer$),s(Ue(this.video),this.params.output.elementVisible$),this.subscription.add(i.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(i.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())==null?void 0:n.to)==="ready"&&this.videoState.setState("ready")},r)).add(i.pause$.subscribe(()=>{this.videoState.setState("paused")},r)).add(i.playing$.subscribe(()=>{this.videoState.setState("playing")},r)).add(i.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ee(this.video,t.volume,i.volumeState$,r)).add(i.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case"stopped":e.position$.next(0),e.duration$.next(0),t.playbackState.setState("stopped");break;case"ready":break;case"paused":t.playbackState.setState("paused");break;case"playing":t.playbackState.setState("playing");break;default:return uT(n.to)}},r)).add(lT(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,YC(["init"])).pipe(WC(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ue(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:XC.INVARIANT}),this.video.srcObject=e,x(this.params.desiredState.playbackState,"playing")}onLiveStreamStop(){this.videoState.startTransitionTo("stopped"),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:hc.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Pe(this.video,()=>{this.params.output.soundProhibitedEvent$.next()}).then(e=>{e||(this.videoState.setState("paused"),x(this.params.desiredState.playbackState,"paused",!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:hc.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 Qt,ErrorCategory as Nn,filter as bT,isNonNullable as gT,isNullable as s0,map as n0,merge as o0,once as u0,Subject as $e,Subscription as vT,ValueSubject as V,flattenObject as ST}from"@vkontakte/videoplayer-shared/es2015";import{Observable as JC,map as dT,Subscription as ZC,Subject as e0}from"@vkontakte/videoplayer-shared/es2015";var pT=a=>new JC(e=>{let t=new ZC,r=a.desiredPlaybackState$.stateChangeStarted$.pipe(dT(({from:l,to:c})=>`${l}-${c}`)),i=a.desiredPlaybackState$.stateChangeEnded$,s=a.providerChanged$.pipe(dT(({type:l})=>l!==void 0)),n=new e0,o=0,u="unknown";return t.add(r.subscribe(l=>{o&&window.clearTimeout(o),u=l,o=window.setTimeout(()=>n.next(l),a.maxTransitionInterval)})),t.add(i.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(s.subscribe(l=>{o&&(window.clearTimeout(o),o=0,l&&(o=window.setTimeout(()=>n.next(u),a.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});import{ErrorCategory as t0,Subscription as r0,combine as i0,filter as mT,once as fT}from"@vkontakte/videoplayer-shared/es2015";function hT(){return new(window.AudioContext||window.webkitAudioContext)}import{clientChecker as a0}from"@vkontakte/videoplayer-shared/es2015";var Xa=class Xa{constructor(e,t,r,i){this.providerOutput=e;this.provider$=t;this.volumeMultiplierError$=r;this.volumeMultiplier=i;this.destroyController=new fe;this.subscriptions=new r0;this.audioContext=null;this.gainNode=null;this.mediaElementSource=null;this.subscriptions.add(this.provider$.pipe(mT(s=>!!s.type),fT()).subscribe(({type:s})=>this.subscribe(s)))}subscribe(e){a0.isSafari&&e!=="MPEG"||this.subscriptions.add(i0({video:this.providerOutput.element$,playbackState:this.providerOutput.playbackState$,volume:this.providerOutput.volume$}).pipe(mT(({playbackState:t,video:r,volume:{muted:i,volume:s}})=>t==="playing"&&!!r&&!i&&!!s),fT()).subscribe(({video:t})=>{this.initAudioContextOnce(t).then(r=>{r||this.destroy()}).catch(r=>{this.handleError(r),this.destroy()})}))}static isSupported(){return"AudioContext"in window&&"GainNode"in window&&"MediaElementAudioSourceNode"in window}initAudioContextOnce(e){return A(this,null,function*(){let{volumeMultiplier:t}=this,r=hT();this.audioContext=r;let i=r.createGain();if(this.gainNode=i,i.gain.value=t,i.connect(r.destination),r.state==="suspended"&&(yield r.resume(),this.destroyController.signal.aborted))return!1;let s=r.createMediaElementSource(e);return this.mediaElementSource=s,s.connect(i),!0})}cleanup(){this.mediaElementSource&&(this.mediaElementSource.disconnect(),this.mediaElementSource=null),this.gainNode&&(this.gainNode.disconnect(),this.gainNode=null),this.audioContext&&(this.audioContext.state!=="closed"&&this.audioContext.close(),this.audioContext=null)}destroy(){this.destroyController.abort(),this.subscriptions.unsubscribe(),this.cleanup()}handleError(e){var t;this.volumeMultiplierError$.next({id:Xa.errorId,category:t0.VIDEO_PIPELINE,message:(t=e==null?void 0:e.message)!=null?t:`${Xa.errorId} exception`,thrown:e})}};Xa.errorId="VolumeMultiplierManager";var pi=Xa;var l0={chunkDuration:5e3,maxParallelRequests:5},Za=class{constructor(e){this.current$=new V({type:void 0});this.providerError$=new $e;this.noAvailableProvidersError$=new $e;this.volumeMultiplierError$=new $e;this.providerOutput={position$:new V(0),duration$:new V(1/0),volume$:new V({muted:!1,volume:1}),availableVideoStreams$:new V([]),currentVideoStream$:new V(void 0),availableVideoTracks$:new V([]),currentVideoTrack$:new V(void 0),availableAudioStreams$:new V([]),currentAudioStream$:new V(void 0),availableAudioTracks$:new V([]),currentVideoSegmentLength$:new V(0),currentAudioSegmentLength$:new V(0),isAudioAvailable$:new V(!0),autoVideoTrackLimitingAvailable$:new V(!1),autoVideoTrackLimits$:new V(void 0),currentBuffer$:new V(void 0),isBuffering$:new V(!0),error$:new $e,warning$:new $e,willSeekEvent$:new $e,soundProhibitedEvent$:new $e,seekedEvent$:new $e,loopedEvent$:new $e,endedEvent$:new $e,firstBytesEvent$:new $e,loadedMetadataEvent$:new $e,firstFrameEvent$:new $e,canplay$:new $e,isLive$:new V(void 0),isLiveEnded$:new V(null),isLowLatency$:new V(!1),canChangePlaybackSpeed$:new V(!0),liveTime$:new V(void 0),liveBufferTime$:new V(void 0),liveLatency$:new V(void 0),availableTextTracks$:new V([]),currentTextTrack$:new V(void 0),hostname$:new V(void 0),httpConnectionType$:new V(void 0),httpConnectionReused$:new V(void 0),inPiP$:new V(!1),inFullscreen$:new V(!1),element$:new V(void 0),elementVisible$:new V(!0),availableSources$:new V(void 0),is3DVideo$:new V(!1),playbackState$:new V(""),getCurrentTime$:new V(null)};this.subscription=new vT;this.volumeMultiplierManager=null;this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer"),this.tracer=e.dependencies.tracer.createComponentTracer(this.constructor.name);let t=Gv([...Wv(this.params.tuning),...Qv(this.params.tuning)],this.params.tuning).filter(l=>gT(e.sources[l])),{forceFormat:r,formatsToAvoid:i}=this.params.tuning,s=[];r?s=[r]:i.length?s=[...t.filter(l=>!(0,mc.default)(i,l)),...t.filter(l=>(0,mc.default)(i,l))]:s=t,this.log({message:`Selected formats: ${s.join(" > ")}`}),this.tracer.log("Selected formats",ST(s)),this.screenFormatsIterator=new Ka(s);let n=[...vl(!0),...vl(!1)];this.chromecastFormatsIterator=new Ka(n.filter(l=>gT(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources);let{volumeMultiplier:o=1,tuning:{useVolumeMultiplier:u}}=this.params;u&&o!==1&&pi.isSupported()&&(this.volumeMultiplierManager=new pi(this.providerOutput,this.current$,this.volumeMultiplierError$,o))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){var e;this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe(),(e=this.volumeMultiplierManager)==null||e.destroy(),this.volumeMultiplierManager=null,this.tracer.end()}initProvider(){let e=this.chooseDestination(),t=this.chooseFormat(e);if(s0(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(i){this.providerError$.next({id:"ProviderNotConstructed",category:Nn.WTF,message:"Failed to create provider",thrown:i})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.tracer.log("reinitProvider"),this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.tracer.log("switchToNextProvider",{destination:e}),this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){let e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"}),this.tracer.log("destroyProvider");let t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),i=r.state!=="none";if(this.params.desiredState.seekState.setState({state:"requested",position:i?r.position:t,forcePrecise:i?r.forcePrecise:!1}),e.scene3D){let n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();let s=this.providerOutput.isBuffering$;s.getValue()||s.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),this.tracer.log("createProvider",{destination:e,format:t}),e){case"SCREEN":return this.createScreenProvider(t);case"CHROMECAST":return this.createChromecastProvider(t);default:return Ja(e)}}createScreenProvider(e){let{sources:t,container:r,desiredState:i}=this.params,s=this.providerOutput,n={container:r,source:null,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case"DASH_SEP":case"DASH_WEBM":case"DASH_WEBM_AV1":case"DASH_ONDEMAND":case"DASH_STREAMS":{let o=this.applyFailoverHost(t[e]),u=this.applyFailoverHost(t.HLS_ONDEMAND||t.HLS);return Qt(o),new qa($(E({},n),{source:o,sourceHls:u}))}case"DASH_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ua($(E({},n),{source:o}))}case"HLS":case"HLS_ONDEMAND":{let o=this.applyFailoverHost(t[e]);return Qt(o),ai||!this.params.tuning.useHlsJs?new Qa($(E({},n),{source:o})):new ja($(E({},n),{source:o}))}case"HLS_LIVE":case"HLS_LIVE_CMAF":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ga($(E({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case"MPEG":{let o=this.applyFailoverHost(t[e]);return Qt(o),new Ya($(E({},n),{source:o}))}case"DASH_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new lv($(E({},n),{source:o,config:$(E({},l0),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case"WEB_RTC_LIVE":{let o=this.applyFailoverHost(t[e]);return Qt(o),new za({container:r,source:o,desiredState:i,output:s,dependencies:this.params.dependencies,tuning:this.params.tuning})}case"DASH":case"DASH_LIVE_WEBM":throw new Error(`${e} is no longer supported`);default:return Ja(e)}}createChromecastProvider(e){let{sources:t,container:r,desiredState:i,meta:s}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return Qt(o),new Hi({connection:o,meta:s,container:r,source:t,format:e,desiredState:i,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?"CHROMECAST":"SCREEN"}chooseFormat(e){switch(e){case"SCREEN":return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case"CHROMECAST":return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return 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 r=i=>{let s=new URL(i);return s.host=t,s.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return $(E({},e),{url:r(e.url)})}return(0,TT.default)((0,yT.default)(e).map(([i,s])=>[i,r(s)]))}initProviderErrorHandling(){let e=new vT,t=!1,r=0;return e.add(o0(this.providerOutput.error$.pipe(bT(i=>!this.params.tuning.ignoreAudioRendererError||!i.message||!/AUDIO_RENDERER_ERROR/ig.test(i.message))),pT({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(n0(i=>({id:`ProviderHangup:${i}`,category:Nn.WTF,message:`A ${i} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;let i=this.params.desiredState.playbackState.transitionEnded$.pipe(bT(({to:s})=>s==="playing"),u0()).subscribe(()=>t=!0);e.add(i)})),e.add(this.providerError$.subscribe(i=>{let s=this.current$.getValue().destination,n={error:i,currentDestination:s};if(s==="CHROMECAST")this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider("SCREEN"),()=>this.params.dependencies.chromecastInitializer.disconnect());else{let o=i.category===Nn.NETWORK,u=i.category===Nn.FATAL,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit&&!u,d=l&&!u&&(o&&t||!c);n=$(E({},n),{isNetworkError:o,isFatalError:u,haveFailoverHost:l,tryFailover:d,canReinitProvider:c}),c?(r++,this.reinitProvider()):d?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):this.switchToNextProvider(s!=null?s:"SCREEN")}this.tracer.error("providerError",ST(n))})),e}};import{fromEvent as Fn,once as c0,combine as d0,Subscription as IT,ValueSubject as fc,map as p0,filter as h0,isNonNullable as qn,now as Oe,safeStorage as bc}from"@vkontakte/videoplayer-shared/es2015";var m0=5e3,ET="one_video_throughput",xT="one_video_rtt",yt=window.navigator.connection,PT=()=>{let a=yt==null?void 0:yt.downlink;if(qn(a)&&a!==10)return a*1e3},wT=()=>{let a=yt==null?void 0:yt.rtt;if(qn(a)&&a!==3e3)return a},AT=(a,e,t)=>{let r=t*8,i=r/a;return r/(i+e)},gc=class a{constructor(e){this.subscription=new IT;this.concurrentDownloads=new Set;var i,s;this.tuningConfig=e;let t=a.load(ET)||(e.useBrowserEstimation?PT():void 0)||m0,r=(s=(i=a.load(xT))!=null?i:e.useBrowserEstimation?wT():void 0)!=null?s:0;if(this.throughput$=new fc(t),this.rtt$=new fc(r),this.rttAdjustedThroughput$=new fc(AT(t,r,e.rttPenaltyRequestSize)),this.throughput=Sr.getSmoothedValue(t,-1,e),this.rtt=Sr.getSmoothedValue(r,1,e),e.useBrowserEstimation){let n=()=>{let u=PT();u&&this.throughput.next(u);let l=wT();qn(l)&&this.rtt.next(l)};yt&&"onchange"in yt&&this.subscription.add(Fn(yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{bc.set(ET,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{bc.set(xT,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(d0({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(p0(({throughput:n,rtt:o})=>AT(n,o,e.rttPenaltyRequestSize)),h0(n=>{let o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=Oe(),i=new IT;switch(this.subscription.add(i),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:i.add(Fn(e,"progress").pipe(c0()).subscribe(s=>{t=s.loaded,r=Oe()}));break;case 1:case 0:i.add(Fn(e,"loadstart").subscribe(()=>{t=0,r=Oe()}));break}i.add(Fn(e,"loadend").subscribe(s=>{if(e.status===200){let n=s.loaded,o=Oe(),u=n-t,l=o-r;this.addRawSpeed(u,l,1)}this.concurrentDownloads.delete(e),i.unsubscribe()}))}trackStream(e,t=!1){let r=e.getReader();if(!r){e.cancel("Could not get reader");return}let i=0,s=Oe(),n=0,o=Oe(),u=c=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},l=p=>A(this,[p],function*({done:c,value:d}){if(c)!t&&this.addRawSpeed(i,Oe()-s,1),this.concurrentDownloads.delete(e);else if(d){if(t){let h=Oe();if(h-o>this.tuningConfig.lowLatency.continuesByteSequenceInterval||h-s>this.tuningConfig.lowLatency.maxLastEvaluationTimeout){let b=o-s;b&&this.addRawSpeed(n,b,1,t),n=d.byteLength,s=Oe()}else n+=d.byteLength;o=Oe()}else i+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&Oe()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,Oe()-o,this.concurrentDownloads.size),n=0,o=Oe());yield r==null?void 0:r.read().then(l,u)}});this.concurrentDownloads.add(e),r==null||r.read().then(l,u)}addRawSpeed(e,t,r=1,i=!1){if(a.sanityCheck(e,t,i)){let s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){let i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var r;let t=bc.get(e);if(qn(t))return(r=parseInt(t,10))!=null?r:void 0}},kT=gc;import{fillWithDefault as f0,VideoQuality as RT}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:RT.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:RT.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,crashOnStallTimeout:25e3,crashOnStallTWithoutDataTimeout:5e3,enableSubSegmentBufferFeeding:!0,bufferEmptinessTolerance:100,useFetchPriorityHints:!0,qualityLimitsOnStall:{stallDurationNoDataBeforeQualityDecrease:500,stallCountBeforeQualityDecrease:3,resetQualityRestrictionTimeout:1e4},enableBaseUrlSupport:!0,maxSegmentRetryCount:5},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,maxLiveDuration:72e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:250,playbackCatchupSpeedup:.05,isActiveOnDefault:!1,bufferEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:"07A4434E",useWebmBigRequest:!1,webmCodec:"vp9",androidPreferredFormat:"dash",preferCMAF:!1,preferWebRTC:!1,preferMultiStream:!1,preferHDR:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useNativeHLSTextTracks:!1,useManagedMediaSource:!0,useNewSwitchTo:!1,useSafariEndlessRequestBugfix:!0,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,audioVideoSyncRate:20,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50},useVolumeMultiplier:!1,ignoreAudioRendererError:!1,useEnableSubtitlesParam:!1,useOldMSEDetection:!1,useHlsLiveNewTextManager:!1,exposeInternalsToGlobal:!1,hlsLiveNewTextManagerDownloadThreshold:4e3},LT=a=>{var e;return $(E({},f0(a,$T)),{configName:[...(e=a.configName)!=null?e:[],...$T.configName]})};import{assertNonNullable as Un,combine as Tt,ErrorCategory as Hn,filter as Se,filterChanged as G,fromEvent as Sc,isNonNullable as I0,isNullable as E0,Logger as x0,map as U,mapTo as OT,merge as Wt,now as jn,once as ct,Subject as z,Subscription as VT,tap as yc,ValueSubject as P,isHigher as P0,isInvariantQuality as BT,flattenObject as Yt,throttle as Tc,getTraceSubscriptionMethod as _T,Tracer as w0,InternalsExposure as A0}from"@vkontakte/videoplayer-shared/es2015";import{merge as b0,map as g0,filter as MT,isNonNullable as v0}from"@vkontakte/videoplayer-shared/es2015";var vc=({seekState:a,position$:e})=>b0(a.stateChangeEnded$.pipe(g0(({to:t})=>{var r;return t.state==="none"?void 0:((r=t.position)!=null?r:NaN)/1e3}),MT(v0)),e.pipe(MT(()=>a.getState().state==="none")));import{assertNonNullable as S0}from"@vkontakte/videoplayer-shared/es2015";var DT=a=>{let e=typeof a.container=="string"?document.getElementById(a.container):a.container;return S0(e,`Wrong container or containerId {${a.container}}`),e};import{filter as y0,once as T0}from"@vkontakte/videoplayer-shared/es2015";var CT=(a,e,t,r)=>{a!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(y0(i=>i.length>0),T0()).subscribe(i=>{i.find(r)&&e.startTransitionTo(a)}):(a===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(a)};var Gn=class{constructor(e={configName:[]},t=w0.createRootTracer(!1)){this.subscription=new VT;this.logger=new x0;this.abrLogger=this.logger.createComponentLog("ABR");this.internalsExposure=null;this.isPlaybackStarted=!1;this.hasLiveOffsetByPaused=new P(!1);this.hasLiveOffsetByPausedTimer=0;this.wasSetStartedQuality=!1;this.desiredState={playbackState:new O("stopped"),seekState:new O({state:"none"}),volume:new O({volume:1,muted:!1}),videoTrack:new O(void 0),videoStream:new O(void 0),audioStream:new O(void 0),autoVideoTrackSwitching:new O(!0),autoVideoTrackLimits:new O({}),isLooped:new O(!1),isLowLatency:new O(!1),playbackRate:new O(1),externalTextTracks:new O([]),internalTextTracks:new O([]),currentTextTrack:new O(void 0),textTrackCuesSettings:new O({}),cameraOrientation:new O({x:0,y:0})};this.info={playbackState$:new P("stopped"),position$:new P(0),duration$:new P(1/0),muted$:new P(!1),volume$:new P(1),availableVideoStreams$:new P([]),currentVideoStream$:new P(void 0),availableQualities$:new P([]),availableQualitiesFps$:new P({}),currentQuality$:new P(void 0),isAutoQualityEnabled$:new P(!0),autoQualityLimitingAvailable$:new P(!1),autoQualityLimits$:new P({}),availableAudioStreams$:new P([]),currentAudioStream$:new P(void 0),availableAudioTracks$:new P([]),isAudioAvailable$:new P(!0),currentPlaybackRate$:new P(1),currentBuffer$:new P({start:0,end:0}),isBuffering$:new P(!0),isStalled$:new P(!1),isEnded$:new P(!1),isLooped$:new P(!1),isLive$:new P(void 0),isLiveEnded$:new P(null),canChangePlaybackSpeed$:new P(void 0),atLiveEdge$:new P(void 0),atLiveDurationEdge$:new P(void 0),liveTime$:new P(void 0),liveBufferTime$:new P(void 0),liveLatency$:new P(void 0),currentFormat$:new P(void 0),availableTextTracks$:new P([]),currentTextTrack$:new P(void 0),throughputEstimation$:new P(void 0),rttEstimation$:new P(void 0),videoBitrate$:new P(void 0),hostname$:new P(void 0),httpConnectionType$:new P(void 0),httpConnectionReused$:new P(void 0),surface$:new P("none"),chromecastState$:new P("NOT_AVAILABLE"),chromecastDeviceName$:new P(void 0),intrinsicVideoSize$:new P(void 0),availableSources$:new P(void 0),is3DVideo$:new P(!1),currentVideoSegmentLength$:new P(0),currentAudioSegmentLength$:new P(0)};this.events={inited$:new z,ready$:new z,started$:new z,playing$:new z,paused$:new z,stopped$:new z,willStart$:new z,willResume$:new z,willPause$:new z,willStop$:new z,willDestruct$:new z,watchCoverageRecord$:new z,watchCoverageLive$:new z,managedError$:new z,fatalError$:new z,ended$:new z,looped$:new z,seeked$:new z,willSeek$:new z,autoplaySoundProhibited$:new z,firstBytes$:new z,loadedMetadata$:new z,firstFrame$:new z,canplay$:new z,log$:new z};this.experimental={element$:new P(void 0),tuningConfigName$:new P([]),enableDebugTelemetry$:new P(!1),dumpTelemetry:_g,getCurrentTime$:new P(null)};if(this.initLogs(),this.tuning=LT(e),this.tracer=t,this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ss({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new kT(this.tuning.throughputEstimator),e.exposeInternalsToGlobal&&(this.internalsExposure=new A0("CORE"),this.internalsExposure.expose({player:this})),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(r,i,s)=>{let n=Reflect.get(r,i,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(r,o)}catch(u){let l=o.map(p=>JSON.stringify(p,(h,m)=>{let b=typeof m;return(0,NT.default)(["number","string","boolean"],b)?m:m===null?null:`<${b}>`})),c=`Player.${String(i)}`,d=`Exception calling ${c} (${l.join(", ")})`;throw this.events.fatalError$.next({id:c,category:Hn.WTF,message:d,thrown:u}),u}}}})}initVideo(e){var s,n,o,u;this.config=e;let i=e,{container:t}=i,r=nd(i,["container"]);return this.tracer.log("initVideo",Yt(r)),this.domContainer=DT(e),this.chromecastInitializer.contentId=(s=e.meta)==null?void 0:s.videoId,this.providerContainer=new Za({sources:e.sources,meta:(n=e.meta)!=null?n:{},failoverHosts:(o=e.failoverHosts)!=null?o:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,tracer:this.tracer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning,volumeMultiplier:e.volumeMultiplier}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.initTracerSubscription(),this.providerContainer.init(),this.setLiveLowLatency(this.tuning.dashCmafLive.lowLatency.isActiveOnDefault),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),(u=this.internalsExposure)==null||u.expose({config:e,logger:this.logger,tuning:this.tuning}),this}destroy(){var e,t;this.tracer.log("destroy"),window.clearTimeout(this.hasLiveOffsetByPausedTimer),this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)==null||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe(),this.tracer.end(),(t=this.internalsExposure)==null||t.destroy()}prepare(){let e=this.desiredState.playbackState;return this.tracer.log("prepare",{currentPlayBackState:e.getState()}),e.getState()==="stopped"&&e.startTransitionTo("ready"),this}play(){let e=()=>{let t=this.desiredState.playbackState;this.tracer.log("play",{currentPlayBackState:t.getState()}),t.getState()!=="playing"&&t.startTransitionTo("playing")};return document.hidden&&this.tuning.autoplayOnlyInActiveTab&&!Ji()?(this.tracer.log("request play from hidden tab"),Sc(document,"visibilitychange").pipe(ct()).subscribe(e)):e(),this}pause(){let e=this.desiredState.playbackState;return this.tracer.log("pause",{currentPlayBackState:e.getState()}),e.getState()!=="paused"&&e.startTransitionTo("paused"),this}stop(){let e=this.desiredState.playbackState;return this.tracer.log("stop",{currentPlayBackState:e.getState()}),e.getState()!=="stopped"&&e.startTransitionTo("stopped"),this}seekTime(e,t=!0){let r=this.info.duration$.getValue(),i=this.info.isLive$.getValue(),s=e;return e>=r&&!i&&(s=r-.1),this.tracer.log("seekTime",{duration:r,isLive:i,time:e,calculatedTime:s,forcePrecise:t}),this.events.willSeek$.next({from:this.getExactTime(),to:s}),this.desiredState.seekState.setState({state:"requested",position:s*1e3,forcePrecise:t}),this}seekPercent(e){let t=this.info.duration$.getValue();return this.tracer.log("seekPercent",{percent:e,duration:t}),isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){let t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.tracer.log("setVolume",{volume:e,isAudioDisabled:this.tuning.isAudioDisabled,isDesiredStateMuted:this.desiredState.volume.getState().muted,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){let t=this.tuning.isAudioDisabled||e;return this.tracer.log("setMuted",{isMuted:e,isAudioDisabled:this.tuning.isAudioDisabled,desiredStateVolume:this.desiredState.volume.getState().volume,chromecastState:this.chromecastInitializer.castState$.getValue(),muted:t}),this.chromecastInitializer.castState$.getValue()==="CONNECTED"?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setVideoStream(e){return this.desiredState.videoStream.startTransitionTo(e),this}setAudioStream(e){return this.desiredState.audioStream.startTransitionTo(e),this}setQuality(e){Un(this.providerContainer);let t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.tracer.log("setQuality",{isDelayed:t.length===0,quality:e}),this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.wasSetStartedQuality?this.providerContainer.providerOutput.availableVideoTracks$.pipe(Se(r=>r.length>0),ct()).subscribe(r=>{this.setVideoTrackIdByQuality(r,e)}):this.explicitInitialQuality=e:t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.tracer.log("setAutoQuality",{enable:e}),this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.tracer.log("setAutoQualityLimits",Yt(e)),this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var r;Un(this.providerContainer);let t=(r=this.providerContainer)==null?void 0:r.providerOutput.element$.getValue();return this.tracer.log("setPlaybackRate",{playbackRate:e,isVideoElementAvailable:!!t}),t&&(this.desiredState.playbackRate.setState(e),t.playbackRate=e),this}setExternalTextTracks(e){return e.length&&this.tracer.log("setExternalTextTracks",Yt(e)),this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>E({type:"external"},t))),this}selectTextTrack(e){var t;return CT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)==null?void 0:t.providerOutput.availableTextTracks$,r=>r.id===e),this.tracer.log("selectTextTrack",{textTrackId:e}),this}setTextTrackCueSettings(e){return this.tracer.log("setTextTrackCueSettings",E({},e)),this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLiveLowLatency(e){let t=this.info.isLive$.getValue(),r=this.desiredState.isLowLatency.getState();return!t||r===e?this:(this.tracer.log("live switch to low latency "+e),this.desiredState.isLowLatency.setState(e),this.seekTime(0))}setLooped(e){return this.tracer.log("setLooped",{isLooped:e}),this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.tracer.log("toggleChromecast"),this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){let r=this.getScene3D();return this.tracer.log("startCameraManualRotation",{isScene3DAvailable:!!r,mx:e,my:t}),r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){let t=this.getScene3D();return this.tracer.log("stopCameraManualRotation",{isScene3DAvailable:!!t,immediate:e}),t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){let r=this.getScene3D();if(this.tracer.log("moveCameraFocusPX",{isScene3DAvailable:!!r,dxpx:e,dypx:t}),r){let i=r.getCameraRotation(),s=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:i.x+s.x,y:i.y+s.y})}return this}holdCamera(){let e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){let e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;let e=this.providerContainer.providerOutput.element$.getValue();if(E0(e))return this.info.position$.getValue();let t=this.desiredState.seekState.getState(),r=t.state==="none"?void 0:t.position;return I0(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var t,r;let e=(t=this.providerContainer)==null?void 0:t.current$.getValue();if((r=e==null?void 0:e.provider)!=null&&r.scene3D)return e.provider.scene3D}setIntrinsicVideoSize(...e){let t={width:e.reduce((r,{width:i})=>r||i||0,0),height:e.reduce((r,{height:i})=>r||i||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(U(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(Se(({from:e})=>e==="stopped"),ct()).subscribe(()=>{this.initedAt=jn(),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($(E({},n),{state:"applying"})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:Hn.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.soundProhibitedEvent$.pipe(ct()).subscribe(this.events.autoplaySoundProhibited$)).add(e.providerOutput.seekedEvent$.subscribe(()=>{let n=this.desiredState.seekState.getState();this.tracer.log("seekedEvent",Yt(n)),n.state==="applying"&&(this.desiredState.seekState.setState({state:"none"}),this.events.seeked$.next())})).add(e.current$.pipe(U(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(U(n=>n.destination),G()).subscribe(()=>this.isPlaybackStarted=!1)).add(e.providerOutput.availableVideoStreams$.subscribe(this.info.availableVideoStreams$)).add(Tt({availableVideoTracks:e.providerOutput.availableVideoTracks$,currentVideoStream:e.providerOutput.currentVideoStream$}).pipe(U(({availableVideoTracks:n,currentVideoStream:o})=>n.filter(u=>o?o.id===u.streamId:!0).map(({quality:u})=>u).sort((u,l)=>BT(u)?1:BT(l)?-1:P0(l,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{let o={};for(let u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioStreams$.subscribe(this.info.availableAudioStreams$)).add(e.providerOutput.currentVideoStream$.subscribe(this.info.currentVideoStream$)).add(e.providerOutput.currentAudioStream$.subscribe(this.info.currentAudioStream$)).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.pipe(G()).subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.currentVideoSegmentLength$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentVideoSegmentLength$)).add(e.providerOutput.currentAudioSegmentLength$.pipe(G((n,o)=>Math.round(n)===Math.round(o))).subscribe(this.info.currentAudioSegmentLength$)).add(e.providerOutput.hostname$.pipe(G()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(G()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(G()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(U(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.isLiveEnded$.pipe(yc(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(Tt({hasLiveOffsetByPaused:Wt(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(U(n=>n.to),G(),U(n=>n==="paused")),isLowLatency:e.providerOutput.isLowLatency$}).subscribe(({hasLiveOffsetByPaused:n,isLowLatency:o})=>{if(window.clearTimeout(this.hasLiveOffsetByPausedTimer),n){this.hasLiveOffsetByPausedTimer=window.setTimeout(()=>{this.hasLiveOffsetByPaused.next(!0)},this.getActiveLiveDelay(o));return}this.hasLiveOffsetByPaused.next(!1)})).add(Tt({atLiveEdge:Tt({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:vc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(U(({isLive:n,position:o,isLowLatency:u})=>{let l=this.getActiveLiveDelay(u);return n&&Math.abs(o)<l/1e3}),G(),yc(n=>n&&this.setPlaybackRate(1))),hasPausedTimeoutCase:this.hasLiveOffsetByPaused}).pipe(U(({atLiveEdge:n,hasPausedTimeoutCase:o})=>n&&!o)).subscribe(this.info.atLiveEdge$)).add(Tt({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(U(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),G(),yc(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(U(n=>n.muted),G()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(U(n=>n.volume),G()).subscribe(this.info.volume$)).add(vc({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(Wt(e.providerOutput.endedEvent$.pipe(OT(!0)),e.providerOutput.seekedEvent$.pipe(OT(!1))).pipe(G()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.volumeMultiplierError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(U(n=>({id:n?`No${n}`:"NoProviders",category:Hn.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.getCurrentTime$.subscribe(this.experimental.getCurrentTime$)).add(e.providerOutput.firstBytesEvent$.pipe(ct(),U(n=>n!=null?n:jn()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.loadedMetadataEvent$.subscribe(this.events.loadedMetadata$)).add(e.providerOutput.firstFrameEvent$.pipe(ct(),U(()=>jn()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ct(),U(()=>jn()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));let t=new P(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));let r=new P(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(Se(({to:n})=>n==="playing"),ct()).subscribe(()=>r.next(!1)));let i=0,s=Wt(e.providerOutput.isBuffering$,t,r).pipe(U(()=>{let n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||r.getValue();return n&&!o}),G());this.subscription.add(s.subscribe(n=>{n?i=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(i),this.info.isStalled$.next(!1))})),this.subscription.add(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(U(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){let t=new VT;this.subscription.add(t),this.subscription.add(e.current$.pipe(G((r,i)=>r.provider===i.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(Se(r=>r.length>0),ct()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var i,s;let t;this.wasSetStartedQuality=!0;let r=(s=this.explicitInitialQuality)!=null?s:(i=this.desiredState.videoTrack.getState())==null?void 0:i.quality;r&&(t=e.find(({quality:n})=>n===r),t||this.setAutoQuality(!0)),t||(t=Ft(e,{container:this.domContainer.getBoundingClientRect(),estimatedThroughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(Wt(this.desiredState.videoTrack.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(U(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(U(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(U(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;let e=(t=this.providerContainer)==null?void 0:t.providerOutput;Un(this.providerContainer),Un(e),Bg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Vg(r)),this.providerContainer.current$.subscribe(({type:r})=>Qi("provider",r)),e.duration$.subscribe(r=>Qi("duration",r)),e.availableVideoTracks$.pipe(Se(r=>!!r.length),ct()).subscribe(r=>Qi("tracks",r)),this.events.fatalError$.subscribe(new ge("fatalError")),this.events.managedError$.subscribe(new ge("managedError")),e.position$.subscribe(new ge("position")),e.currentVideoTrack$.pipe(U(r=>r==null?void 0:r.quality)).subscribe(new ge("quality")),this.info.currentBuffer$.subscribe(new ge("buffer")),e.isBuffering$.subscribe(new ge("isBuffering"))].forEach(r=>this.subscription.add(r)),Qi("codecs",jv())}initTracerSubscription(){let e=_T(this.tracer.log.bind(this.tracer)),t=_T(this.tracer.error.bind(this.tracer));this.subscription.add(this.info.playbackState$.subscribe(e("playbackState"))).add(this.info.isLooped$.subscribe(e("isLooped"))).add(this.info.currentPlaybackRate$.pipe(G()).subscribe(e("currentPlaybackRate"))).add(this.info.isAutoQualityEnabled$.subscribe(e("isAutoQualityEnabled"))).add(this.info.autoQualityLimits$.subscribe(e("autoQualityLimits"))).add(this.info.currentFormat$.subscribe(e("currentFormat"))).add(this.info.availableQualities$.subscribe(e("availableQualities"))).add(this.info.availableQualitiesFps$.subscribe(e("availableQualitiesFps"))).add(this.info.availableAudioTracks$.subscribe(e("availableAudioTracks"))).add(this.info.isAudioAvailable$.subscribe(e("isAudioAvailable"))).add(Tt({currentQuality:this.info.currentQuality$,videoBitrate:this.info.videoBitrate$}).pipe(Se(({currentQuality:r,videoBitrate:i})=>!!r&&!!i),G((r,i)=>r.currentQuality===i.currentQuality)).subscribe(e("currentVideoTrack"))).add(this.info.currentVideoSegmentLength$.pipe(Se(r=>r>0),G()).subscribe(e("currentVideoSegmentLength"))).add(this.info.currentAudioSegmentLength$.pipe(Se(r=>r>0),G()).subscribe(e("currentAudioSegmentLength"))).add(this.info.hostname$.subscribe(e("hostname"))).add(this.info.currentTextTrack$.subscribe(e("currentTextTrack"))).add(this.info.availableTextTracks$.subscribe(e("availableTextTracks"))).add(this.info.autoQualityLimitingAvailable$.subscribe(e("autoQualityLimitingAvailable"))).add(Tt({currentBuffer:this.info.currentBuffer$.pipe(Se(r=>r.end>0),G((r,i)=>r.end===i.end&&r.start===i.start)),position:this.info.position$.pipe(G())}).pipe(Tc(1e3)).subscribe(e("currentBufferAndPosition"))).add(this.info.duration$.pipe(G()).subscribe(e("duration"))).add(this.info.isBuffering$.subscribe(e("isBuffering"))).add(this.info.isLive$.pipe(G()).subscribe(e("isLive"))).add(this.info.canChangePlaybackSpeed$.pipe(G()).subscribe(e("canChangePlaybackSpeed"))).add(Tt({liveTime:this.info.liveTime$,liveBufferTime:this.info.liveBufferTime$,position:this.info.position$}).pipe(Se(({liveTime:r,liveBufferTime:i})=>!!r&&!!i),Tc(1e3)).subscribe(e("liveBufferAndPosition"))).add(this.info.atLiveEdge$.pipe(G(),Se(r=>r===!0)).subscribe(e("atLiveEdge"))).add(this.info.atLiveDurationEdge$.pipe(G(),Se(r=>r===!0)).subscribe(e("atLiveDurationEdge"))).add(this.info.muted$.pipe(G()).subscribe(e("muted"))).add(this.info.volume$.pipe(G()).subscribe(e("volume"))).add(this.info.isEnded$.pipe(G(),Se(r=>r===!0)).subscribe(e("isEnded"))).add(this.info.availableSources$.subscribe(e("availableSources"))).add(Tt({throughputEstimation:this.info.throughputEstimation$,rtt:this.info.rttEstimation$}).pipe(Se(({throughputEstimation:r,rtt:i})=>!!r&&!!i),Tc(3e3)).subscribe(e("throughputEstimation"))).add(this.info.isStalled$.subscribe(e("isStalled"))).add(this.info.is3DVideo$.pipe(G(),Se(r=>r===!0)).subscribe(e("is3DVideo"))).add(this.info.surface$.subscribe(e("surface"))).add(this.events.ended$.subscribe(e("ended"))).add(this.events.looped$.subscribe(e("looped"))).add(this.events.managedError$.subscribe(t("managedError"))).add(this.events.fatalError$.subscribe(t("fatalError"))).add(this.events.firstBytes$.subscribe(e("firstBytes"))).add(this.events.firstFrame$.subscribe(e("firstFrame"))).add(this.events.canplay$.subscribe(e("canplay")))}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e,t=()=>{e==null||e.release(),e=void 0},r=()=>A(this,null,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(i=>{i instanceof DOMException&&i.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:Hn.DOM,message:String(i)})})});this.subscription.add(Wt(Sc(document,"visibilitychange"),Sc(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{let i=document.visibilityState==="visible",s=this.desiredState.playbackState.getState()==="playing",n=!!e&&!(e!=null&&e.released);i&&s?n||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){let r=e.find(i=>i.quality===t);this.tracer.log("setVideoTrackIdByQuality",Yt({quality:t,availableTracks:Yt(e),track:Yt(r),isAutoQuality:!r})),r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}getActiveLiveDelay(e=!1){return e?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay}};import{Subscription as M4,Observable as D4,Subject as C4,ValueSubject as O4,VideoQuality as V4}from"@vkontakte/videoplayer-shared/es2015";var B4=`@vkontakte/videoplayer-core@${od}`;export{hs as ChromecastState,eo as HttpConnectionType,D4 as Observable,ye as PlaybackState,Gn as Player,B4 as SDK_VERSION,C4 as Subject,M4 as Subscription,to as Surface,od as VERSION,O4 as ValueSubject,Lt as VideoFormat,V4 as VideoQuality};